context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Management.Automation.Runspaces;
using System.Text;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Internal
{
internal static class ModuleUtils
{
// Default option for local file system enumeration:
// - Ignore files/directories when access is denied;
// - Search top directory only.
private static readonly System.IO.EnumerationOptions s_defaultEnumerationOptions =
new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden };
// Default option for UNC path enumeration. Same as above plus a large buffer size.
// For network shares, a large buffer may result in better performance as more results can be batched over the wire.
// The buffer size 16K is recommended in the comment of the 'BufferSize' property:
// "A "large" buffer, for example, would be 16K. Typical is 4K."
private static readonly System.IO.EnumerationOptions s_uncPathEnumerationOptions =
new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden, BufferSize = 16384 };
private static readonly string EnCulturePath = Path.DirectorySeparatorChar + "en";
private static readonly string EnUsCulturePath = Path.DirectorySeparatorChar + "en-us";
/// <summary>
/// Check if a directory is likely a localized resources folder.
/// </summary>
/// <param name="dir">Directory to check if it is a possible resource folder.</param>
/// <returns>True if the directory name matches a culture.</returns>
internal static bool IsPossibleResourceDirectory(string dir)
{
// Assume locale directories do not contain modules.
if (dir.EndsWith(EnCulturePath, StringComparison.OrdinalIgnoreCase) ||
dir.EndsWith(EnUsCulturePath, StringComparison.OrdinalIgnoreCase))
{
return true;
}
dir = Path.GetFileName(dir);
// Use some simple pattern matching to avoid the call into GetCultureInfo when we know it will fail (and throw).
if ((dir.Length == 2 && char.IsLetter(dir[0]) && char.IsLetter(dir[1]))
||
(dir.Length == 5 && char.IsLetter(dir[0]) && char.IsLetter(dir[1]) && (dir[2] == '-') && char.IsLetter(dir[3]) && char.IsLetter(dir[4])))
{
try
{
// This might not throw on invalid culture still
// 4096 is considered the unknown locale - so assume that could be a module
var cultureInfo = new CultureInfo(dir);
return cultureInfo.LCID != 4096;
}
catch { }
}
return false;
}
/// <summary>
/// Get all module files by searching the given directory recursively.
/// All sub-directories that could be a module folder will be searched.
/// </summary>
internal static IEnumerable<string> GetAllAvailableModuleFiles(string topDirectoryToCheck)
{
if (!Directory.Exists(topDirectoryToCheck)) { yield break; }
var options = Utils.PathIsUnc(topDirectoryToCheck) ? s_uncPathEnumerationOptions : s_defaultEnumerationOptions;
Queue<string> directoriesToCheck = new Queue<string>();
directoriesToCheck.Enqueue(topDirectoryToCheck);
bool firstSubDirs = true;
while (directoriesToCheck.Count > 0)
{
string directoryToCheck = directoriesToCheck.Dequeue();
try
{
foreach (string toAdd in Directory.EnumerateDirectories(directoryToCheck, "*", options))
{
if (firstSubDirs || !IsPossibleResourceDirectory(toAdd))
{
directoriesToCheck.Enqueue(toAdd);
}
}
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
firstSubDirs = false;
foreach (string moduleFile in Directory.EnumerateFiles(directoryToCheck, "*", options))
{
foreach (string ext in ModuleIntrinsics.PSModuleExtensions)
{
if (moduleFile.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
{
yield return moduleFile;
break; // one file can have only one extension
}
}
}
}
}
/// <summary>
/// Check if the CompatiblePSEditions field of a given module
/// declares compatibility with the running PowerShell edition.
/// </summary>
/// <param name="moduleManifestPath">The path to the module manifest being checked.</param>
/// <param name="compatiblePSEditions">The value of the CompatiblePSEditions field of the module manifest.</param>
/// <returns>True if the module is compatible with the running PowerShell edition, false otherwise.</returns>
internal static bool IsPSEditionCompatible(
string moduleManifestPath,
IEnumerable<string> compatiblePSEditions)
{
#if UNIX
return true;
#else
if (!ModuleUtils.IsOnSystem32ModulePath(moduleManifestPath))
{
return true;
}
return Utils.IsPSEditionSupported(compatiblePSEditions);
#endif
}
internal static IEnumerable<string> GetDefaultAvailableModuleFiles(bool isForAutoDiscovery, ExecutionContext context)
{
HashSet<string> uniqueModuleFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string directory in ModuleIntrinsics.GetModulePath(isForAutoDiscovery, context))
{
var needWriteProgressCompleted = false;
ProgressRecord analysisProgress = null;
// Write a progress message for UNC paths, so that users know what is happening
try
{
if ((context.CurrentCommandProcessor != null) && Utils.PathIsUnc(directory))
{
analysisProgress = new ProgressRecord(0,
Modules.DeterminingAvailableModules,
string.Format(CultureInfo.InvariantCulture, Modules.SearchingUncShare, directory))
{
RecordType = ProgressRecordType.Processing
};
context.CurrentCommandProcessor.CommandRuntime.WriteProgress(analysisProgress);
needWriteProgressCompleted = true;
}
}
catch (InvalidOperationException)
{
// This may be called when we are not allowed to write progress,
// So eat the invalid operation
}
try
{
foreach (string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(directory))
{
if (uniqueModuleFiles.Add(moduleFile))
{
yield return moduleFile;
}
}
}
finally
{
if (needWriteProgressCompleted)
{
analysisProgress.RecordType = ProgressRecordType.Completed;
context.CurrentCommandProcessor.CommandRuntime.WriteProgress(analysisProgress);
}
}
}
}
/// <summary>
/// Get a list of module files from the given directory without recursively searching all sub-directories.
/// This method assumes the given directory is a module folder or a version sub-directory of a module folder.
/// </summary>
internal static List<string> GetModuleFilesFromAbsolutePath(string directory)
{
List<string> result = new List<string>();
string fileName = Path.GetFileName(directory);
// If the given directory doesn't exist or it's the root folder, then return an empty list.
if (!Directory.Exists(directory) || string.IsNullOrEmpty(fileName)) { return result; }
// If the user give the module path including version, the module name could be the parent folder name.
if (Version.TryParse(fileName, out Version ver))
{
string parentDirPath = Path.GetDirectoryName(directory);
string parentDirName = Path.GetFileName(parentDirPath);
// If the parent directory is NOT a root folder, then it could be the module folder.
if (!string.IsNullOrEmpty(parentDirName))
{
string manifestPath = Path.Combine(directory, parentDirName);
manifestPath += StringLiterals.PowerShellDataFileExtension;
if (File.Exists(manifestPath) && ver.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath)))
{
result.Add(manifestPath);
return result;
}
}
}
// If we reach here, then use the given directory as the module folder.
foreach (Version version in GetModuleVersionSubfolders(directory))
{
string manifestPath = Path.Combine(directory, version.ToString(), fileName);
manifestPath += StringLiterals.PowerShellDataFileExtension;
if (File.Exists(manifestPath) && version.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath)))
{
result.Add(manifestPath);
}
}
foreach (string ext in ModuleIntrinsics.PSModuleExtensions)
{
string moduleFile = Path.Combine(directory, fileName) + ext;
if (File.Exists(moduleFile))
{
result.Add(moduleFile);
// when finding the default modules we stop when the first
// match is hit - searching in order .psd1, .psm1, .dll,
// if a file is found but is not readable then it is an error.
break;
}
}
return result;
}
/// <summary>
/// Get a list of the available module files from the given directory.
/// Search all module folders under the specified directory, but do not search sub-directories under a module folder.
/// </summary>
internal static IEnumerable<string> GetDefaultAvailableModuleFiles(string topDirectoryToCheck)
{
if (!Directory.Exists(topDirectoryToCheck)) { yield break; }
var options = Utils.PathIsUnc(topDirectoryToCheck) ? s_uncPathEnumerationOptions : s_defaultEnumerationOptions;
List<Version> versionDirectories = new List<Version>();
LinkedList<string> directoriesToCheck = new LinkedList<string>();
directoriesToCheck.AddLast(topDirectoryToCheck);
while (directoriesToCheck.Count > 0)
{
versionDirectories.Clear();
string[] subdirectories;
string directoryToCheck = directoriesToCheck.First.Value;
directoriesToCheck.RemoveFirst();
try
{
subdirectories = Directory.GetDirectories(directoryToCheck, "*", options);
ProcessPossibleVersionSubdirectories(subdirectories, versionDirectories);
}
catch (IOException) { subdirectories = Array.Empty<string>(); }
catch (UnauthorizedAccessException) { subdirectories = Array.Empty<string>(); }
bool isModuleDirectory = false;
string proposedModuleName = Path.GetFileName(directoryToCheck);
foreach (Version version in versionDirectories)
{
string manifestPath = Path.Combine(directoryToCheck, version.ToString(), proposedModuleName);
manifestPath += StringLiterals.PowerShellDataFileExtension;
if (File.Exists(manifestPath))
{
isModuleDirectory = true;
yield return manifestPath;
}
}
if (!isModuleDirectory)
{
foreach (string ext in ModuleIntrinsics.PSModuleExtensions)
{
string moduleFile = Path.Combine(directoryToCheck, proposedModuleName) + ext;
if (File.Exists(moduleFile))
{
isModuleDirectory = true;
yield return moduleFile;
// when finding the default modules we stop when the first
// match is hit - searching in order .psd1, .psm1, .dll, .exe
// if a file is found but is not readable then it is an
// error
break;
}
}
}
if (!isModuleDirectory)
{
foreach (var subdirectory in subdirectories)
{
if (subdirectory.EndsWith("Microsoft.PowerShell.Management", StringComparison.OrdinalIgnoreCase) ||
subdirectory.EndsWith("Microsoft.PowerShell.Utility", StringComparison.OrdinalIgnoreCase))
{
directoriesToCheck.AddFirst(subdirectory);
}
else
{
directoriesToCheck.AddLast(subdirectory);
}
}
}
}
}
/// <summary>
/// Gets the list of versions under the specified module base path in descending sorted order.
/// </summary>
/// <param name="moduleBase">Module base path.</param>
/// <returns>Sorted list of versions.</returns>
internal static List<Version> GetModuleVersionSubfolders(string moduleBase)
{
var versionFolders = new List<Version>();
if (!string.IsNullOrWhiteSpace(moduleBase) && Directory.Exists(moduleBase))
{
var options = Utils.PathIsUnc(moduleBase) ? s_uncPathEnumerationOptions : s_defaultEnumerationOptions;
IEnumerable<string> subdirectories = Directory.EnumerateDirectories(moduleBase, "*", options);
ProcessPossibleVersionSubdirectories(subdirectories, versionFolders);
}
return versionFolders;
}
private static void ProcessPossibleVersionSubdirectories(IEnumerable<string> subdirectories, List<Version> versionFolders)
{
foreach (string subdir in subdirectories)
{
string subdirName = Path.GetFileName(subdir);
if (Version.TryParse(subdirName, out Version version))
{
versionFolders.Add(version);
}
}
if (versionFolders.Count > 1)
{
versionFolders.Sort(static (x, y) => y.CompareTo(x));
}
}
internal static bool IsModuleInVersionSubdirectory(string modulePath, out Version version)
{
version = null;
string folderName = Path.GetDirectoryName(modulePath);
if (folderName != null)
{
folderName = Path.GetFileName(folderName);
return Version.TryParse(folderName, out version);
}
return false;
}
internal static bool IsOnSystem32ModulePath(string path)
{
#if UNIX
return false;
#else
Dbg.Assert(!string.IsNullOrEmpty(path), $"Caller to verify that {nameof(path)} is not null or empty");
string windowsPowerShellPSHomePath = ModuleIntrinsics.GetWindowsPowerShellPSHomeModulePath();
return path.StartsWith(windowsPowerShellPSHomePath, StringComparison.OrdinalIgnoreCase);
#endif
}
/// <summary>
/// Gets a list of fuzzy matching commands and their scores.
/// </summary>
/// <param name="pattern">Command pattern.</param>
/// <param name="context">Execution context.</param>
/// <param name="commandOrigin">Command origin.</param>
/// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param>
/// <param name="moduleVersionRequired">Specific module version to be required.</param>
/// <returns>IEnumerable tuple containing the CommandInfo and the match score.</returns>
internal static IEnumerable<CommandScore> GetFuzzyMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false)
{
foreach (CommandInfo command in GetMatchingCommands(pattern, context, commandOrigin, rediscoverImportedModules, moduleVersionRequired, useFuzzyMatching: true))
{
int score = FuzzyMatcher.GetDamerauLevenshteinDistance(command.Name, pattern);
if (score <= FuzzyMatcher.MinimumDistance)
{
yield return new CommandScore(command, score);
}
}
}
/// <summary>
/// Gets a list of matching commands.
/// </summary>
/// <param name="pattern">Command pattern.</param>
/// <param name="context">Execution context.</param>
/// <param name="commandOrigin">Command origin.</param>
/// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param>
/// <param name="moduleVersionRequired">Specific module version to be required.</param>
/// <param name="useFuzzyMatching">Use fuzzy matching.</param>
/// <param name="useAbbreviationExpansion">Use abbreviation expansion for matching.</param>
/// <returns>Returns matching CommandInfo IEnumerable.</returns>
internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false)
{
// Otherwise, if it had wildcards, just return the "AvailableCommand"
// type of command info.
WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))))
{
foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context))
{
// Skip modules that have already been loaded so that we don't expose private commands.
string moduleName = Path.GetFileNameWithoutExtension(modulePath);
List<PSModuleInfo> modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
PSModuleInfo tempModuleInfo = null;
if (modules.Count != 0)
{
// 1. We continue to the next module path if we don't want to re-discover those imported modules
// 2. If we want to re-discover the imported modules, but one or more commands from the module were made private,
// then we don't do re-discovery
if (!rediscoverImportedModules || modules.Exists(static module => module.ModuleHasPrivateMembers))
{
continue;
}
if (modules.Count == 1)
{
PSModuleInfo psModule = modules[0];
tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null);
tempModuleInfo.SetModuleBase(psModule.ModuleBase);
foreach (KeyValuePair<string, CommandInfo> entry in psModule.ExportedCommands)
{
if (commandPattern.IsMatch(entry.Value.Name) ||
(useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) ||
(useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase)))
{
CommandInfo current = null;
switch (entry.Value.CommandType)
{
case CommandTypes.Alias:
current = new AliasInfo(entry.Value.Name, definition: null, context);
break;
case CommandTypes.Function:
current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
break;
case CommandTypes.Filter:
current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
break;
case CommandTypes.Configuration:
current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
break;
case CommandTypes.Cmdlet:
current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context);
break;
default:
Dbg.Assert(false, "cannot be hit");
break;
}
current.Module = tempModuleInfo;
yield return current;
}
}
continue;
}
}
string moduleShortName = Path.GetFileNameWithoutExtension(modulePath);
IDictionary<string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context);
if (exportedCommands == null) { continue; }
tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null);
if (InitialSessionState.IsEngineModule(moduleShortName))
{
tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase);
}
// moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
}
foreach (KeyValuePair<string, CommandTypes> pair in exportedCommands)
{
string commandName = pair.Key;
CommandTypes commandTypes = pair.Value;
if (commandPattern.IsMatch(commandName) ||
(useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) ||
(useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase)))
{
bool shouldExportCommand = true;
// Verify that we don't already have it represented in the initial session state.
if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
{
foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
{
string moduleCompareName = null;
if (commandEntry.Module != null)
{
moduleCompareName = commandEntry.Module.Name;
}
else if (commandEntry.PSSnapIn != null)
{
moduleCompareName = commandEntry.PSSnapIn.Name;
}
if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
{
if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
{
shouldExportCommand = false;
}
}
}
}
if (shouldExportCommand)
{
if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
{
yield return new AliasInfo(commandName, null, context)
{
Module = tempModuleInfo
};
}
if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
{
yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
{
Module = tempModuleInfo
};
}
if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
{
yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
{
Module = tempModuleInfo
};
}
if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
{
yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
{
Module = tempModuleInfo
};
}
}
}
}
}
}
}
/// <summary>
/// Returns abbreviated version of a command name.
/// </summary>
/// <param name="commandName">Name of the command to transform.</param>
/// <returns>Abbreviated version of the command name.</returns>
internal static string AbbreviateName(string commandName)
{
// Use default size of 6 which represents expected average abbreviation length
StringBuilder abbreviation = new StringBuilder(6);
foreach (char c in commandName)
{
if (char.IsUpper(c) || c == '-')
{
abbreviation.Append(c);
}
}
return abbreviation.ToString();
}
}
internal struct CommandScore
{
public CommandScore(CommandInfo command, int score)
{
Command = command;
Score = score;
}
public CommandInfo Command;
public int Score;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for the ProjectChooseElement class (and for ProjectWhenElement and ProjectOtherwiseElement).</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectChooseElement class (and for ProjectWhenElement and ProjectOtherwiseElement)
/// </summary>
[TestClass]
public class ProjectChooseElement_Tests
{
/// <summary>
/// Read choose with unexpected attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidAttribute()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose X='Y'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read choose with unexpected Condition attribute.
/// Condition is not currently allowed on Choose.
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidConditionAttribute()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose Condition='true'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read choose with unexpected child
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidChild()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<X/>
</Choose>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read choose with a When containing no Condition attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidWhen()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<When>
<PropertyGroup><x/></PropertyGroup>
</When>
<Otherwise>
<PropertyGroup><y/></PropertyGroup>
</Otherwise>
</Choose>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read choose with only an otherwise
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidOnlyOtherwise()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<Otherwise/>
</Choose>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read choose with two otherwises
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidTwoOtherwise()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<Otherwise/>
<Otherwise/>
</Choose>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read choose with otherwise before when
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidOtherwiseBeforeWhen()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<Otherwise/>
<When Condition='c'/>
</Choose>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read empty choose
/// </summary>
/// <remarks>
/// One might think this should work but 2.0 required at least one When.
/// </remarks>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidEmptyChoose()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose/>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children);
Assert.AreEqual(null, Helpers.GetFirst(choose.Children));
}
/// <summary>
/// Read choose with only a when
/// </summary>
[TestMethod]
public void ReadChooseOnlyWhen()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<When Condition='c'/>
</Choose>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children);
Assert.AreEqual(1, Helpers.Count(choose.WhenElements));
Assert.AreEqual(null, choose.OtherwiseElement);
}
/// <summary>
/// Read basic choose
/// </summary>
[TestMethod]
public void ReadChooseBothWhenOtherwise()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<When Condition='c1'/>
<When Condition='c2'/>
<Otherwise/>
</Choose>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children);
List<ProjectWhenElement> whens = Helpers.MakeList(choose.WhenElements);
Assert.AreEqual(2, whens.Count);
Assert.AreEqual("c1", whens[0].Condition);
Assert.AreEqual("c2", whens[1].Condition);
Assert.IsNotNull(choose.OtherwiseElement);
}
/// <summary>
/// Test stack overflow is prevented.
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ExcessivelyNestedChoose()
{
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
for (int i = 0; i < 52; i++)
{
builder1.Append("<Choose><When Condition='true'>");
builder2.Append("</When></Choose>");
}
string content = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>";
content += builder1.ToString();
content += builder2.ToString();
content += @"</Project>";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Setting a When's condition should dirty the project
/// </summary>
[TestMethod]
public void SettingWhenConditionDirties()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Choose>
<When Condition='true'>
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</When>
</Choose>
</Project>
";
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectChooseElement choose = Helpers.GetFirst(project.Xml.ChooseElements);
ProjectWhenElement when = Helpers.GetFirst(choose.WhenElements);
when.Condition = "false";
Assert.AreEqual("v1", project.GetPropertyValue("p"));
project.ReevaluateIfNecessary();
Assert.AreEqual(String.Empty, project.GetPropertyValue("p"));
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ResultPropertiesTests : ExpressionCompilerTestBase
{
[Fact]
public void Category()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "F", "p", "l" })
{
Assert.Equal(DkmEvaluationResultCategory.Data, GetResultProperties(context, expr).Category);
}
Assert.Equal(DkmEvaluationResultCategory.Method, GetResultProperties(context, "M()").Category);
Assert.Equal(DkmEvaluationResultCategory.Property, GetResultProperties(context, "P").Category);
}
[Fact]
public void StorageType()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
static int SP { get; set; }
static int SF;
static int SM() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "P", "F", "M()", "p", "l" })
{
Assert.Equal(DkmEvaluationResultStorageType.None, GetResultProperties(context, expr).StorageType);
}
foreach (var expr in new[] { "SP", "SF", "SM()" })
{
Assert.Equal(DkmEvaluationResultStorageType.Static, GetResultProperties(context, expr).StorageType);
}
}
[Fact]
public void AccessType()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 Private
.field family int32 Protected
.field assembly int32 Internal
.field public int32 Public
.field famorassem int32 ProtectedInternal
.field famandassem int32 ProtectedAndInternal
.method public hidebysig instance void
Test() cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method C::.ctor
} // end of class C
";
ImmutableArray<byte> exeBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out exeBytes, pdbBytes: out pdbBytes);
var runtime = CreateRuntimeInstance(
assemblyName: GetUniqueName(),
references: ImmutableArray.Create(MscorlibRef),
exeBytes: exeBytes.ToArray(),
symReader: new SymReader(pdbBytes.ToArray()));
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultAccessType.Private, GetResultProperties(context, "Private").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Protected, GetResultProperties(context, "Protected").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "Internal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "Public").AccessType);
// As in dev12.
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedAndInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.None, GetResultProperties(context, "null").AccessType);
}
[Fact]
public void AccessType_Nested()
{
var source = @"
using System;
internal class C
{
public int F;
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
// Used the declared accessibility, rather than the effective accessibility.
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "F").AccessType);
}
[Fact]
public void ModifierFlags_Virtual()
{
var source = @"
using System;
class C
{
public int P { get; set; }
public int M() { return 0; }
public event Action E;
public virtual int VP { get; set; }
public virtual int VM() { return 0; }
public virtual event Action VE;
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "P").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VP").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "M()").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VM()").ModifierFlags);
// Field-like events are borderline since they bind as event accesses, but get emitted as field accesses.
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "E").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VE").ModifierFlags);
}
[Fact]
public void ModifierFlags_Virtual_Variations()
{
var source = @"
using System;
abstract class Base
{
public abstract int Override { get; set; }
}
abstract class Derived : Base
{
public override int Override { get; set; }
public abstract int Abstract { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "Derived.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Abstract").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Override").ModifierFlags);
}
[Fact]
public void ModifierFlags_Constant()
{
var source = @"
using System;
class C
{
int F = 1;
const int CF = 1;
static readonly int SRF = 1;
void Test(int p)
{
int l = 2;
const int cl = 2;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "null", "1", "1 + 1", "CF", "cl" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Constant, GetResultProperties(context, expr).ModifierFlags);
}
foreach (var expr in new[] { "this", "F", "SRF", "p", "l" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, expr).ModifierFlags);
}
}
[Fact]
public void ModifierFlags_Volatile()
{
var source = @"
using System;
class C
{
int F = 1;
volatile int VF = 1;
void Test(int p)
{
int l;
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "F").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Volatile, GetResultProperties(context, "VF").ModifierFlags);
}
[Fact]
public void Assignment()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileAssignment(DefaultInspectionContext.Instance, "P", "1", DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); // Not Public
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); // Not Virtual
}
[Fact]
public void LocalDeclaration()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
InspectionContextFactory.Empty,
"int z = 1;",
DkmEvaluationFlags.None,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
}
[Fact]
public void Error()
{
var source = @"
class C
{
void Test()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var runtime = CreateRuntimeInstance(comp);
var context = CreateMethodContext(runtime, methodName: "C.Test");
VerifyErrorResultProperties(context, "x => x");
VerifyErrorResultProperties(context, "Test");
VerifyErrorResultProperties(context, "Missing");
VerifyErrorResultProperties(context, "C");
}
private static ResultProperties GetResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.Null(error);
return resultProperties;
}
private static void VerifyErrorResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.NotNull(error);
Assert.Equal(default(ResultProperties), resultProperties);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Implementation of the LineOutput interface for printer.
/// </summary>
internal sealed class PrinterLineOutput : LineOutput
{
#region LineOutput implementation
/// <summary>
/// Full buffering for printer.
/// </summary>
internal override bool RequiresBuffering { get { return true; } }
/// <summary>
/// Do the printing on playback.
/// </summary>
internal override void ExecuteBufferPlayBack(DoPlayBackCall playback)
{
_playbackCall = playback;
DoPrint();
}
/// <summary>
/// The # of columns for the printer.
/// </summary>
/// <value></value>
internal override int ColumnNumber
{
get
{
CheckStopProcessing();
return _deviceColumns;
}
}
/// <summary>
/// The # of rows for the printer.
/// </summary>
/// <value></value>
internal override int RowNumber
{
get
{
CheckStopProcessing();
return _deviceRows;
}
}
/// <summary>
/// Write a line to the output device.
/// </summary>
/// <param name="s">Line to write.</param>
internal override void WriteLine(string s)
{
CheckStopProcessing();
// delegate the action to the helper,
// that will properly break the string into
// screen lines
_writeLineHelper.WriteLine(s, this.ColumnNumber);
}
#endregion
/// <summary>
/// Used for static initializations like DefaultPrintFontName.
/// </summary>
static PrinterLineOutput()
{
// This default must be loaded from a resource file as different
// cultures will have different defaults and the localizer would
// know the default for different cultures.
s_defaultPrintFontName = OutPrinterDisplayStrings.DefaultPrintFontName;
}
/// <summary>
/// Constructor for the class.
/// </summary>
/// <param name="printerName">Name of printer, if null use default printer.</param>
internal PrinterLineOutput(string printerName)
{
_printerName = printerName;
// instantiate the helper to do the line processing when LineOutput.WriteXXX() is called
WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine);
WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite);
_writeLineHelper = new WriteLineHelper(true, wl, w, this.DisplayCells);
}
/// <summary>
/// Callback to be called when IConsole.WriteLine() is called by WriteLineHelper.
/// </summary>
/// <param name="s">String to write.</param>
private void OnWriteLine(string s)
{
_lines.Enqueue(s);
}
/// <summary>
/// Callback to be called when Console.Write() is called by WriteLineHelper.
/// This is called when the WriteLineHelper needs to write a line whose length
/// is the same as the width of the screen buffer.
/// </summary>
/// <param name="s">String to write.</param>
private void OnWrite(string s)
{
_lines.Enqueue(s);
}
/// <summary>
/// Do the printing.
/// </summary>
private void DoPrint()
{
try
{
// create a new print document object and set the printer name, if available
PrintDocument pd = new PrintDocument();
if (!string.IsNullOrEmpty(_printerName))
{
pd.PrinterSettings.PrinterName = _printerName;
}
// set up the callback mechanism
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
// start printing
pd.Print();
}
finally
{
// make sure we do not leak the font
if (_printFont != null)
{
_printFont.Dispose();
_printFont = null;
}
}
}
/// <summary>
/// Helper to create a font.
/// If the font object exists, it does nothing.
/// Else, the a new object is created and verified.
/// </summary>
/// <param name="g">GDI+ graphics object needed for verification.</param>
private void CreateFont(Graphics g)
{
if (_printFont != null)
return;
// create the font
// do we have a specified font?
if (string.IsNullOrEmpty(_printFontName))
{
_printFontName = s_defaultPrintFontName;
}
if (_printFontSize <= 0)
{
_printFontSize = DefaultPrintFontSize;
}
_printFont = new Font(_printFontName, _printFontSize);
VerifyFont(g);
}
/// <summary>
/// Internal helper to verify that the font is fixed pitch. If the test fails,
/// it reverts to the default font.
/// </summary>
/// <param name="g">GDI+ graphics object needed for verification.</param>
private void VerifyFont(Graphics g)
{
// check if the font is fixed pitch
// HEURISTICS:
// we compute the length of two strings, one made of "large" characters
// one made of "narrow" ones. If they are the same length, we assume that
// the font is fixed pitch.
string large = "ABCDEF";
float wLarge = g.MeasureString(large, _printFont).Width / large.Length;
string narrow = ".;'}l|";
float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length;
if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F)
{
// we passed the test
return;
}
// just get back to the default, since it's not fixed pitch
_printFont.Dispose();
_printFont = new Font(s_defaultPrintFontName, DefaultPrintFontSize);
}
/// <summary>
/// Event fired for each page to print.
/// </summary>
/// <param name="sender">Sender, not used.</param>
/// <param name="ev">Print page event.</param>
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float yPos = 0; // GDI+ coordinate down the page
int linesPrinted = 0; // linesPrinted
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
CreateFont(ev.Graphics);
// compute the height of a line of text
float lineHeight = _printFont.GetHeight(ev.Graphics);
// Work out the number of lines per page
// Use the MarginBounds on the event to do this
float linesPerPage = ev.MarginBounds.Height / _printFont.GetHeight(ev.Graphics);
if (!_printingInitialized)
{
// on the first page we have to initialize the metrics for LineOutput
// work out the number of columns per page assuming fixed pitch font
string s = "ABCDEF";
float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length;
float columnsPerPage = ev.MarginBounds.Width / w;
_printingInitialized = true;
_deviceRows = (int)linesPerPage;
_deviceColumns = (int)columnsPerPage;
// now that we initialized the column and row count for the LineOutput
// interface we can tell the outputter to playback from cache to do the
// proper computations of line widths
// returning from this call, the string queue on this object is full of
// lines of text to print
_playbackCall();
}
// now iterate over the file printing out each line
while ((linesPrinted < linesPerPage) && (_lines.Count > 0))
{
// get the string to be printed
string line = _lines.Dequeue();
// compute the Y position where to draw
yPos = topMargin + (linesPrinted * lineHeight);
// do the actual drawing
ev.Graphics.DrawString(line, _printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
linesPrinted++;
}
// If we have more lines then print another page
ev.HasMorePages = _lines.Count > 0;
}
/// <summary>
/// Flag for one-time initialization of the interface (columns, etc.).
/// </summary>
private bool _printingInitialized = false;
/// <summary>
/// Callback to ask the outputter to playback its cache.
/// </summary>
private DoPlayBackCall _playbackCall;
/// <summary>
/// Name of the printer to print to. Null means default printer.
/// </summary>
private string _printerName = null;
/// <summary>
/// Name of the font to use, if null the default is used.
/// </summary>
private string _printFontName = null;
/// <summary>
/// Font size.
/// </summary>
private int _printFontSize = 0;
/// <summary>
/// Default font, used if the printFont is not specified or if the
/// printFont is not fixed pitch.
/// </summary>
/// <remarks>
/// This default must be loaded from a resource file as different
/// cultures will have different defaults and the localizer would
/// know the default for different cultures.
/// </remarks>
private static readonly string s_defaultPrintFontName;
/// <summary>
/// Default size for the default font.
/// </summary>
private const int DefaultPrintFontSize = 8;
/// <summary>
/// Number of columns on the sheet.
/// </summary>
private int _deviceColumns = 80;
// number of rows per sheet
private int _deviceRows = 40;
/// <summary>
/// Text lines ready to print (after output cache playback).
/// </summary>
private Queue<string> _lines = new Queue<string>();
/// <summary>
/// Cached font object.
/// </summary>
private Font _printFont = null;
private WriteLineHelper _writeLineHelper;
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.LogicalTree;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using Xunit;
namespace Avalonia.Controls.UnitTests.Primitives
{
public class TemplatedControlTests
{
[Fact]
public void Template_Doesnt_Get_Executed_On_Set()
{
bool executed = false;
var template = new FuncControlTemplate(_ =>
{
executed = true;
return new Control();
});
var target = new TemplatedControl
{
Template = template,
};
Assert.False(executed);
}
[Fact]
public void Template_Gets_Executed_On_Measure()
{
bool executed = false;
var template = new FuncControlTemplate(_ =>
{
executed = true;
return new Control();
});
var target = new TemplatedControl
{
Template = template,
};
target.Measure(new Size(100, 100));
Assert.True(executed);
}
[Fact]
public void ApplyTemplate_Should_Create_Visual_Children()
{
var target = new TemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator
{
Child = new Panel
{
Children = new Controls
{
new TextBlock(),
new Border(),
}
}
}),
};
target.ApplyTemplate();
var types = target.GetVisualDescendants().Select(x => x.GetType()).ToList();
Assert.Equal(
new[]
{
typeof(Decorator),
typeof(Panel),
typeof(TextBlock),
typeof(Border)
},
types);
Assert.Empty(target.GetLogicalChildren());
}
[Fact]
public void Templated_Child_Should_Be_NameScope()
{
var target = new TemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator
{
Child = new Panel
{
Children = new Controls
{
new TextBlock(),
new Border(),
}
}
}),
};
target.ApplyTemplate();
Assert.NotNull(NameScope.GetNameScope((Control)target.GetVisualChildren().Single()));
}
[Fact]
public void Templated_Children_Should_Have_TemplatedParent_Set()
{
var target = new TemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator
{
Child = new Panel
{
Children = new Controls
{
new TextBlock(),
new Border(),
}
}
}),
};
target.ApplyTemplate();
var templatedParents = target.GetVisualDescendants()
.OfType<IControl>()
.Select(x => x.TemplatedParent)
.ToList();
Assert.Equal(4, templatedParents.Count);
Assert.True(templatedParents.All(x => x == target));
}
[Fact]
public void Templated_Child_Should_Have_Parent_Set()
{
var target = new TemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator())
};
target.ApplyTemplate();
var child = (Decorator)target.GetVisualChildren().Single();
Assert.Equal(target, child.Parent);
Assert.Equal(target, child.GetLogicalParent());
}
[Fact]
public void Nested_Templated_Control_Should_Not_Have_Template_Applied()
{
var target = new TemplatedControl
{
Template = new FuncControlTemplate(_ => new ScrollViewer())
};
target.ApplyTemplate();
var child = (ScrollViewer)target.GetVisualChildren().Single();
Assert.Empty(child.GetVisualChildren());
}
[Fact]
public void Templated_Children_Should_Be_Styled()
{
using (UnitTestApplication.Start(TestServices.MockStyler))
{
TestTemplatedControl target;
var root = new TestRoot
{
Child = target = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ =>
{
return new StackPanel
{
Children = new Controls
{
new TextBlock
{
}
}
};
}),
}
};
target.ApplyTemplate();
var styler = Mock.Get(UnitTestApplication.Current.Services.Styler);
styler.Verify(x => x.ApplyStyles(It.IsAny<TestTemplatedControl>()), Times.Once());
styler.Verify(x => x.ApplyStyles(It.IsAny<StackPanel>()), Times.Once());
styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once());
}
}
[Fact]
public void Nested_Templated_Controls_Have_Correct_TemplatedParent()
{
var target = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ =>
{
return new ContentControl
{
Template = new FuncControlTemplate(parent =>
{
return new Border
{
Child = new ContentPresenter
{
[~ContentPresenter.ContentProperty] = parent.GetObservable(ContentControl.ContentProperty).ToBinding(),
}
};
}),
Content = new Decorator
{
Child = new TextBlock()
}
};
}),
};
target.ApplyTemplate();
var contentControl = target.GetTemplateChildren().OfType<ContentControl>().Single();
contentControl.ApplyTemplate();
var border = contentControl.GetTemplateChildren().OfType<Border>().Single();
var presenter = contentControl.GetTemplateChildren().OfType<ContentPresenter>().Single();
var decorator = (Decorator)presenter.Content;
var textBlock = (TextBlock)decorator.Child;
Assert.Equal(target, contentControl.TemplatedParent);
Assert.Equal(contentControl, border.TemplatedParent);
Assert.Equal(contentControl, presenter.TemplatedParent);
Assert.Equal(target, decorator.TemplatedParent);
Assert.Equal(target, textBlock.TemplatedParent);
}
[Fact]
public void Nested_TemplatedControls_Should_Register_With_Correct_NameScope()
{
var target = new ContentControl
{
Template = new FuncControlTemplate<ContentControl>(ScrollingContentControlTemplate),
Content = "foo"
};
var root = new TestRoot { Child = target };
target.ApplyTemplate();
var border = target.GetVisualChildren().FirstOrDefault();
Assert.IsType<Border>(border);
var scrollViewer = border.GetVisualChildren().FirstOrDefault();
Assert.IsType<ScrollViewer>(scrollViewer);
((ScrollViewer)scrollViewer).ApplyTemplate();
var scrollContentPresenter = scrollViewer.GetVisualChildren().FirstOrDefault();
Assert.IsType<ScrollContentPresenter>(scrollContentPresenter);
((ContentPresenter)scrollContentPresenter).UpdateChild();
var contentPresenter = scrollContentPresenter.GetVisualChildren().FirstOrDefault();
Assert.IsType<ContentPresenter>(contentPresenter);
var borderNs = NameScope.GetNameScope((Control)border);
var scrollContentPresenterNs = NameScope.GetNameScope((Control)scrollContentPresenter);
Assert.NotNull(borderNs);
Assert.Same(scrollViewer, borderNs.Find("ScrollViewer"));
Assert.Same(contentPresenter, borderNs.Find("PART_ContentPresenter"));
Assert.Same(scrollContentPresenter, scrollContentPresenterNs.Find("PART_ContentPresenter"));
}
[Fact]
public void ApplyTemplate_Should_Raise_TemplateApplied()
{
var target = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator())
};
var raised = false;
target.TemplateApplied += (s, e) =>
{
Assert.Equal(TemplatedControl.TemplateAppliedEvent, e.RoutedEvent);
Assert.Same(target, e.Source);
Assert.NotNull(e.NameScope);
raised = true;
};
target.ApplyTemplate();
Assert.True(raised);
}
[Fact]
public void Applying_New_Template_Clears_TemplatedParent_Of_Old_Template_Children()
{
var target = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator
{
Child = new Border(),
})
};
target.ApplyTemplate();
var decorator = (Decorator)target.GetVisualChildren().Single();
var border = (Border)decorator.Child;
Assert.Equal(target, decorator.TemplatedParent);
Assert.Equal(target, border.TemplatedParent);
target.Template = new FuncControlTemplate(_ => new Canvas());
// Templated children should not be removed here: the control may be re-added
// somewhere with the same template, so they could still be of use.
Assert.Same(decorator, target.GetVisualChildren().Single());
Assert.Equal(target, decorator.TemplatedParent);
Assert.Equal(target, border.TemplatedParent);
target.ApplyTemplate();
Assert.Null(decorator.TemplatedParent);
Assert.Null(border.TemplatedParent);
}
[Fact]
public void TemplateChild_AttachedToLogicalTree_Should_Be_Raised()
{
Border templateChild = new Border();
var root = new TestRoot
{
Child = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator
{
Child = templateChild,
})
}
};
var raised = false;
templateChild.AttachedToLogicalTree += (s, e) => raised = true;
root.Child.ApplyTemplate();
Assert.True(raised);
}
[Fact]
public void TemplateChild_DetachedFromLogicalTree_Should_Be_Raised()
{
Border templateChild = new Border();
var root = new TestRoot
{
Child = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator
{
Child = templateChild,
})
}
};
root.Child.ApplyTemplate();
var raised = false;
templateChild.DetachedFromLogicalTree += (s, e) => raised = true;
root.Child = null;
Assert.True(raised);
}
[Fact]
public void Removing_From_LogicalTree_Should_Not_Remove_Child()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
Border templateChild = new Border();
TestTemplatedControl target;
var root = new TestRoot
{
Styles = new Styles
{
new Style(x => x.OfType<TestTemplatedControl>())
{
Setters = new[]
{
new Setter(
TemplatedControl.TemplateProperty,
new FuncControlTemplate(_ => new Decorator
{
Child = new Border(),
}))
}
}
},
Child = target = new TestTemplatedControl()
};
Assert.NotNull(target.Template);
target.ApplyTemplate();
root.Child = null;
Assert.Null(target.Template);
Assert.IsType<Decorator>(target.GetVisualChildren().Single());
}
}
[Fact]
public void Re_adding_To_Same_LogicalTree_Should_Not_Recreate_Template()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
TestTemplatedControl target;
var root = new TestRoot
{
Styles = new Styles
{
new Style(x => x.OfType<TestTemplatedControl>())
{
Setters = new[]
{
new Setter(
TemplatedControl.TemplateProperty,
new FuncControlTemplate(_ => new Decorator
{
Child = new Border(),
}))
}
}
},
Child = target = new TestTemplatedControl()
};
Assert.NotNull(target.Template);
target.ApplyTemplate();
var expected = (Decorator)target.GetVisualChildren().Single();
root.Child = null;
root.Child = target;
target.ApplyTemplate();
Assert.Same(expected, target.GetVisualChildren().Single());
}
}
[Fact]
public void Re_adding_To_Different_LogicalTree_Should_Recreate_Template()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
TestTemplatedControl target;
var root = new TestRoot
{
Styles = new Styles
{
new Style(x => x.OfType<TestTemplatedControl>())
{
Setters = new[]
{
new Setter(
TemplatedControl.TemplateProperty,
new FuncControlTemplate(_ => new Decorator
{
Child = new Border(),
}))
}
}
},
Child = target = new TestTemplatedControl()
};
var root2 = new TestRoot
{
Styles = new Styles
{
new Style(x => x.OfType<TestTemplatedControl>())
{
Setters = new[]
{
new Setter(
TemplatedControl.TemplateProperty,
new FuncControlTemplate(_ => new Decorator
{
Child = new Border(),
}))
}
}
},
};
Assert.NotNull(target.Template);
target.ApplyTemplate();
var expected = (Decorator)target.GetVisualChildren().Single();
root.Child = null;
root2.Child = target;
target.ApplyTemplate();
var child = target.GetVisualChildren().Single();
Assert.NotNull(target.Template);
Assert.NotNull(child);
Assert.NotSame(expected, child);
}
}
[Fact]
public void Moving_To_New_LogicalTree_Should_Detach_Attach_Template_Child()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
TestTemplatedControl target;
var root = new TestRoot
{
Child = target = new TestTemplatedControl
{
Template = new FuncControlTemplate(_ => new Decorator()),
}
};
Assert.NotNull(target.Template);
target.ApplyTemplate();
var templateChild = (ILogical)target.GetVisualChildren().Single();
Assert.True(templateChild.IsAttachedToLogicalTree);
root.Child = null;
Assert.False(templateChild.IsAttachedToLogicalTree);
var newRoot = new TestRoot { Child = target };
Assert.True(templateChild.IsAttachedToLogicalTree);
}
}
private static IControl ScrollingContentControlTemplate(ContentControl control)
{
return new Border
{
Child = new ScrollViewer
{
Template = new FuncControlTemplate<ScrollViewer>(ScrollViewerTemplate),
Name = "ScrollViewer",
Content = new ContentPresenter
{
Name = "PART_ContentPresenter",
[!ContentPresenter.ContentProperty] = control[!ContentControl.ContentProperty],
}
}
};
}
private static Control ScrollViewerTemplate(ScrollViewer control)
{
var result = new ScrollContentPresenter
{
Name = "PART_ContentPresenter",
[~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty],
};
return result;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: Error.cs 923 2011-12-23 22:02:10Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Principal;
using System.Web;
using System.Xml;
using Mannex;
using Thread = System.Threading.Thread;
using NameValueCollection = System.Collections.Specialized.NameValueCollection;
using System.Security.Cryptography;
using System.Text;
#endregion
/// <summary>
/// Represents a logical application error (as opposed to the actual
/// exception it may be representing).
/// </summary>
[ Serializable ]
public sealed class Error : ICloneable
{
private readonly Exception _exception;
private string _applicationName;
private string _hostName;
private string _typeName;
private string _source;
private string _message;
private string _detail;
private string _user;
private DateTime _time;
private int _statusCode;
private string _webHostHtmlMessage;
private NameValueCollection _serverVariables;
private NameValueCollection _queryString;
private NameValueCollection _form;
private NameValueCollection _cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class.
/// </summary>
public Error() {}
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class
/// from a given <see cref="Exception"/> instance.
/// </summary>
public Error(Exception e) :
this(e, null) {}
/// <summary>
/// Initializes a new instance of the <see cref="Error"/> class
/// from a given <see cref="Exception"/> instance and
/// <see cref="HttpContext"/> instance representing the HTTP
/// context during the exception.
/// </summary>
public Error(Exception e, HttpContextBase context)
{
if (e == null)
throw new ArgumentNullException("e");
_exception = e;
Exception baseException = e.GetBaseException();
//
// Load the basic information.
//
_hostName = Environment.TryGetMachineName(context);
_typeName = baseException.GetType().FullName;
_message = baseException.Message;
_source = baseException.Source;
_detail = e.ToString();
_user = Thread.CurrentPrincipal.Identity.Name ?? string.Empty;
_time = DateTime.Now;
//
// If this is an HTTP exception, then get the status code
// and detailed HTML message provided by the host.
//
HttpException httpException = e as HttpException;
if (httpException != null)
{
_statusCode = httpException.GetHttpCode();
_webHostHtmlMessage = TryGetHtmlErrorMessage(httpException) ?? string.Empty;
}
//
// If the HTTP context is available, then capture the
// collections that represent the state request as well as
// the user.
//
if (context != null)
{
IPrincipal webUser = context.User;
if (webUser != null
&& (webUser.Identity.Name ?? string.Empty).Length > 0)
{
_user = webUser.Identity.Name;
}
var request = context.Request;
var qsfc = request.TryGetUnvalidatedCollections((form, qs, cookies) => new
{
QueryString = qs,
Form = form,
Cookies = cookies,
});
_serverVariables = CopyCollection(request.ServerVariables);
// patch to include raw URL so error reports are useful when URL rewriting (isite/dvanderwilt)
_serverVariables.Add("RAW_URL", context.Request.RawUrl);
_queryString = CopyCollection(qsfc.QueryString);
_form = CopyCollection(qsfc.Form);
_cookies = CopyCollection(qsfc.Cookies);
}
var callerInfo = e.TryGetCallerInfo() ?? CallerInfo.Empty;
if (!callerInfo.IsEmpty)
{
_detail = "# caller: " + callerInfo
+ System.Environment.NewLine
+ _detail;
}
}
/// <summary>
/// Generates a unique identitifer for this exception. Useful when tracking exceptions to dedupe instances of the same exception.
/// Patch kfigy/isitedesign
/// </summary>
public string UniqueId
{
get { return GetUniqueId(Exception); }
}
private string GetUniqueId(Exception ex)
{
var hash = new SHA1Managed();
var signature = ex.Message + ex.StackTrace + ((ex.InnerException != null) ? GetUniqueId(ex.InnerException) : string.Empty);
var result = hash.ComputeHash(Encoding.UTF8.GetBytes(signature));
return Convert.ToBase64String(result);
}
private static string TryGetHtmlErrorMessage(HttpException e)
{
Debug.Assert(e != null);
try
{
return e.GetHtmlErrorMessage();
}
catch (SecurityException se)
{
// In partial trust environments, HttpException.GetHtmlErrorMessage()
// has been known to throw:
// System.Security.SecurityException: Request for the
// permission of type 'System.Web.AspNetHostingPermission' failed.
//
// See issue #179 for more background:
// http://code.google.com/p/elmah/issues/detail?id=179
Trace.WriteLine(se);
return null;
}
}
/// <summary>
/// Gets the <see cref="Exception"/> instance used to initialize this
/// instance.
/// </summary>
/// <remarks>
/// This is a run-time property only that is not written or read
/// during XML serialization via <see cref="ErrorXml.Decode"/> and
/// <see cref="ErrorXml.Encode(Error,XmlWriter)"/>.
/// </remarks>
public Exception Exception
{
get { return _exception; }
}
/// <summary>
/// Gets or sets the name of application in which this error occurred.
/// </summary>
public string ApplicationName
{
get { return _applicationName ?? string.Empty; }
set { _applicationName = value; }
}
/// <summary>
/// Gets or sets name of host machine where this error occurred.
/// </summary>
public string HostName
{
get { return _hostName ?? string.Empty; }
set { _hostName = value; }
}
/// <summary>
/// Gets or sets the type, class or category of the error.
/// </summary>
public string Type
{
get { return _typeName ?? string.Empty; }
set { _typeName = value; }
}
/// <summary>
/// Gets or sets the source that is the cause of the error.
/// </summary>
public string Source
{
get { return _source ?? string.Empty; }
set { _source = value; }
}
/// <summary>
/// Gets or sets a brief text describing the error.
/// </summary>
public string Message
{
get { return _message ?? string.Empty; }
set { _message = value; }
}
/// <summary>
/// Gets or sets a detailed text describing the error, such as a
/// stack trace.
/// </summary>
public string Detail
{
get { return _detail ?? string.Empty; }
set { _detail = value; }
}
/// <summary>
/// Gets or sets the user logged into the application at the time
/// of the error.
/// </summary>
public string User
{
get { return _user ?? string.Empty; }
set { _user = value; }
}
/// <summary>
/// Gets or sets the date and time (in local time) at which the
/// error occurred.
/// </summary>
public DateTime Time
{
get { return _time; }
set { _time = value; }
}
/// <summary>
/// Gets or sets the HTTP status code of the output returned to the
/// client for the error.
/// </summary>
/// <remarks>
/// For cases where this value cannot always be reliably determined,
/// the value may be reported as zero.
/// </remarks>
public int StatusCode
{
get { return _statusCode; }
set { _statusCode = value; }
}
/// <summary>
/// Gets or sets the HTML message generated by the web host (ASP.NET)
/// for the given error.
/// </summary>
public string WebHostHtmlMessage
{
get { return _webHostHtmlMessage ?? string.Empty; }
set { _webHostHtmlMessage = value; }
}
/// <summary>
/// Gets a collection representing the Web server variables
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection ServerVariables
{
get { return FaultIn(ref _serverVariables); }
}
/// <summary>
/// Gets a collection representing the Web query string variables
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection QueryString
{
get { return FaultIn(ref _queryString); }
}
/// <summary>
/// Gets a collection representing the form variables captured as
/// part of diagnostic data for the error.
/// </summary>
public NameValueCollection Form
{
get { return FaultIn(ref _form); }
}
/// <summary>
/// Gets a collection representing the client cookies
/// captured as part of diagnostic data for the error.
/// </summary>
public NameValueCollection Cookies
{
get { return FaultIn(ref _cookies); }
}
/// <summary>
/// Returns the value of the <see cref="Message"/> property.
/// </summary>
public override string ToString()
{
return this.Message;
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
object ICloneable.Clone()
{
//
// Make a base shallow copy of all the members.
//
Error copy = (Error) MemberwiseClone();
//
// Now make a deep copy of items that are mutable.
//
copy._serverVariables = CopyCollection(_serverVariables);
copy._queryString = CopyCollection(_queryString);
copy._form = CopyCollection(_form);
copy._cookies = CopyCollection(_cookies);
return copy;
}
private static NameValueCollection CopyCollection(NameValueCollection collection)
{
if (collection == null || collection.Count == 0)
return null;
return new NameValueCollection(collection);
}
private static NameValueCollection CopyCollection(HttpCookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return null;
NameValueCollection copy = new NameValueCollection(cookies.Count);
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies[i];
//
// NOTE: We drop the Path and Domain properties of the
// cookie for sake of simplicity.
//
copy.Add(cookie.Name, cookie.Value);
}
return copy;
}
private static NameValueCollection FaultIn(ref NameValueCollection collection)
{
if (collection == null)
collection = new NameValueCollection();
return collection;
}
}
}
| |
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 FinishLinePicsAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using BTDB.IL;
using BTDB.StreamLayer;
namespace BTDB.FieldHandler;
public class ListFieldHandler : IFieldHandler, IFieldHandlerWithNestedFieldHandlers
{
readonly IFieldHandlerFactory _fieldHandlerFactory;
readonly ITypeConvertorGenerator _typeConvertGenerator;
readonly IFieldHandler _itemsHandler;
Type? _type;
readonly bool _isSet;
public ListFieldHandler(IFieldHandlerFactory fieldHandlerFactory, ITypeConvertorGenerator typeConvertGenerator, Type type)
{
_fieldHandlerFactory = fieldHandlerFactory;
_typeConvertGenerator = typeConvertGenerator;
_type = type;
_isSet = type.InheritsOrImplements(typeof(ISet<>));
_itemsHandler = _fieldHandlerFactory.CreateFromType(type.GetGenericArguments()[0], FieldHandlerOptions.None);
var writer = new SpanWriter();
writer.WriteFieldHandler(_itemsHandler);
Configuration = writer.GetSpan().ToArray();
}
public ListFieldHandler(IFieldHandlerFactory fieldHandlerFactory, ITypeConvertorGenerator typeConvertGenerator, byte[] configuration)
{
_fieldHandlerFactory = fieldHandlerFactory;
_typeConvertGenerator = typeConvertGenerator;
Configuration = configuration;
var reader = new SpanReader(configuration);
_itemsHandler = _fieldHandlerFactory.CreateFromReader(ref reader, FieldHandlerOptions.None);
}
ListFieldHandler(IFieldHandlerFactory fieldHandlerFactory, ITypeConvertorGenerator typeConvertGenerator, Type type, IFieldHandler itemSpecialized)
{
_fieldHandlerFactory = fieldHandlerFactory;
_typeConvertGenerator = typeConvertGenerator;
_type = type;
_isSet = type.InheritsOrImplements(typeof(ISet<>));
_itemsHandler = itemSpecialized;
Configuration = Array.Empty<byte>();
}
public static string HandlerName => "List";
public string Name => HandlerName;
public byte[] Configuration { get; }
public static bool IsCompatibleWith(Type type)
{
if (!type.IsGenericType) return false;
return type.InheritsOrImplements(typeof(IList<>)) || type.InheritsOrImplements(typeof(ISet<>));
}
public bool IsCompatibleWith(Type type, FieldHandlerOptions options)
{
return IsCompatibleWith(type);
}
public Type HandledType()
{
if (_isSet)
return _type ??= typeof(ISet<>).MakeGenericType(_itemsHandler.HandledType());
return _type ??= typeof(IList<>).MakeGenericType(_itemsHandler.HandledType());
}
public bool NeedsCtx()
{
return true;
}
public void Load(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
{
var localCount = ilGenerator.DeclareLocal(typeof(uint));
var localResultOfObject = ilGenerator.DeclareLocal(typeof(object));
var localResult = ilGenerator.DeclareLocal(HandledType());
var loadSkipped = ilGenerator.DefineLabel();
var loadFinished = ilGenerator.DefineLabel();
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
var collectionInterface = _type!.SpecializationOf(typeof(ICollection<>));
var itemType = collectionInterface!.GetGenericArguments()[0];
ilGenerator
.Do(pushCtx)
.Do(pushReader)
.Ldloca(localResultOfObject)
.Callvirt(typeof(IReaderCtx).GetMethod(nameof(IReaderCtx.ReadObject))!)
.Brfalse(loadSkipped)
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!)
.Stloc(localCount)
.Ldloc(localCount)
.Newobj((_isSet ? typeof(HashSet<>) : typeof(List<>)).MakeGenericType(itemType).GetConstructor(new[] { typeof(int) })!)
.Stloc(localResult)
.Do(pushCtx)
.Ldloc(localResult)
.Castclass(typeof(object))
.Callvirt(() => default(IReaderCtx).RegisterObject(null))
.Mark(next)
.Ldloc(localCount)
.Brfalse(loadFinished)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.ConvU4()
.Stloc(localCount)
.Ldloc(localResult)
.GenerateLoad(_itemsHandler, itemType, pushReader, pushCtx, _typeConvertGenerator)
.Callvirt(collectionInterface!.GetMethod("Add")!)
.Br(next)
.Mark(loadFinished)
.Do(pushCtx)
.Do(pushReader)
.Callvirt(typeof(IReaderCtx).GetMethod(nameof(IReaderCtx.ReadObjectDone))!)
.Br(finish)
.Mark(loadSkipped)
.Ldloc(localResultOfObject)
.Isinst(_type)
.Stloc(localResult)
.Mark(finish)
.Ldloc(localResult);
}
public void Skip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
{
var localCount = ilGenerator.DeclareLocal(typeof(uint));
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
ilGenerator
.Do(pushCtx)
.Do(pushReader)
.Callvirt(typeof(IReaderCtx).GetMethod(nameof(IReaderCtx.SkipObject))!)
.Brfalse(finish)
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!)
.Stloc(localCount)
.Mark(next)
.Ldloc(localCount)
.Brfalse(finish)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.ConvU4()
.Stloc(localCount)
.GenerateSkip(_itemsHandler, pushReader, pushCtx)
.Br(next)
.Mark(finish);
}
public void Save(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue)
{
var realFinish = ilGenerator.DefineLabel();
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
var localValue = ilGenerator.DeclareLocal(_type!);
var typeAsICollection = _type.GetInterface("ICollection`1");
var typeAsIEnumerable = _type.GetInterface("IEnumerable`1");
var getEnumeratorMethod = typeAsIEnumerable!.GetMethod("GetEnumerator");
var typeAsIEnumerator = getEnumeratorMethod!.ReturnType;
var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator);
ilGenerator
.Do(pushValue)
.Stloc(localValue)
.Do(pushCtx)
.Do(pushWriter)
.Ldloc(localValue)
.Castclass(typeof(object))
.Callvirt(typeof(IWriterCtx).GetMethod(nameof(IWriterCtx.WriteObject))!)
.Brfalse(realFinish)
.Do(pushWriter)
.Ldloc(localValue)
.Callvirt(typeAsICollection!.GetProperty("Count")!.GetGetMethod()!)
.ConvU4()
.Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteVUInt32))!)
.Ldloc(localValue)
.Callvirt(getEnumeratorMethod)
.Stloc(localEnumerator)
.Try()
.Mark(next)
.Ldloc(localEnumerator)
.Callvirt(() => default(IEnumerator).MoveNext())
.Brfalse(finish);
_itemsHandler.Save(ilGenerator, pushWriter, pushCtx, il => il
.Ldloc(localEnumerator)
.Callvirt(typeAsIEnumerator.GetProperty("Current")!.GetGetMethod()!)
.Do(_typeConvertGenerator.GenerateConversion(_type.GetGenericArguments()[0], _itemsHandler.HandledType())!));
ilGenerator
.Br(next)
.Mark(finish)
.Finally()
.Ldloc(localEnumerator)
.Callvirt(() => default(IDisposable).Dispose())
.EndTry()
.Mark(realFinish);
}
public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler, IFieldHandlerLogger? logger)
{
if (_type == type) return this;
if (!IsCompatibleWith(type))
{
logger?.ReportTypeIncompatibility(_type, this, type, typeHandler);
return this;
}
var wantedItemType = type.GetGenericArguments()[0];
var wantedItemHandler = default(IFieldHandler);
if (typeHandler is ListFieldHandler listFieldHandler)
{
wantedItemHandler = listFieldHandler._itemsHandler;
}
var itemSpecialized = _itemsHandler.SpecializeLoadForType(wantedItemType, wantedItemHandler, logger);
if (itemSpecialized == wantedItemHandler)
{
return typeHandler;
}
if (_typeConvertGenerator.GenerateConversion(itemSpecialized.HandledType(), wantedItemType) == null)
{
logger?.ReportTypeIncompatibility(itemSpecialized.HandledType(), itemSpecialized, wantedItemType, null);
return this;
}
return new ListFieldHandler(_fieldHandlerFactory, _typeConvertGenerator, type, itemSpecialized);
}
public IFieldHandler SpecializeSaveForType(Type type)
{
if (_type == type) return this;
if (!IsCompatibleWith(type))
{
Debug.Fail("strange");
return this;
}
var wantedItemType = type.GetGenericArguments()[0];
var itemSpecialized = _itemsHandler.SpecializeSaveForType(wantedItemType);
if (_typeConvertGenerator.GenerateConversion(wantedItemType, itemSpecialized.HandledType()) == null)
{
Debug.Fail("even more strange");
return this;
}
return new ListFieldHandler(_fieldHandlerFactory, _typeConvertGenerator, type, itemSpecialized);
}
public IEnumerable<IFieldHandler> EnumerateNestedFieldHandlers()
{
yield return _itemsHandler;
}
public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx)
{
var localCount = ilGenerator.DeclareLocal(typeof(uint));
var finish = ilGenerator.DefineLabel();
var next = ilGenerator.DefineLabel();
var needsFreeContent = NeedsFreeContent.No;
ilGenerator
.Do(pushCtx)
.Do(pushReader)
.Callvirt(typeof(IReaderCtx).GetMethod(nameof(IReaderCtx.SkipObject))!)
.Brfalse(finish)
.Do(pushReader)
.Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!)
.Stloc(localCount)
.Mark(next)
.Ldloc(localCount)
.Brfalse(finish)
.Ldloc(localCount)
.LdcI4(1)
.Sub()
.ConvU4()
.Stloc(localCount)
.GenerateFreeContent(_itemsHandler, pushReader, pushCtx, ref needsFreeContent)
.Br(next)
.Mark(finish);
return needsFreeContent;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: The boolean class serves as a wrapper for the primitive
** type boolean.
**
**
===========================================================*/
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean>
{
//
// Member Variables
//
private bool m_value; // Do not rename (binary serialization)
// The true value.
//
internal const int True = 1;
// The false value.
//
internal const int False = 0;
//
// Internal Constants are real consts for performance.
//
// The internal string representation of true.
//
internal const String TrueLiteral = "True";
// The internal string representation of false.
//
internal const String FalseLiteral = "False";
//
// Public Constants
//
// The public string representation of true.
//
public static readonly String TrueString = TrueLiteral;
// The public string representation of false.
//
public static readonly String FalseString = FalseLiteral;
//
// Overriden Instance Methods
//
/*=================================GetHashCode==================================
**Args: None
**Returns: 1 or 0 depending on whether this instance represents true or false.
**Exceptions: None
**Overriden From: Value
==============================================================================*/
// Provides a hash code for this instance.
public override int GetHashCode()
{
return (m_value) ? True : False;
}
/*===================================ToString===================================
**Args: None
**Returns: "True" or "False" depending on the state of the boolean.
**Exceptions: None.
==============================================================================*/
// Converts the boolean value of this instance to a String.
public override String ToString()
{
if (false == m_value)
{
return FalseLiteral;
}
return TrueLiteral;
}
public String ToString(IFormatProvider provider)
{
return ToString();
}
public bool TryFormat(Span<char> destination, out int charsWritten)
{
string s = m_value ? TrueLiteral : FalseLiteral;
if (s.Length <= destination.Length)
{
bool copied = s.AsReadOnlySpan().TryCopyTo(destination);
Debug.Assert(copied);
charsWritten = s.Length;
return true;
}
else
{
charsWritten = 0;
return false;
}
}
// Determines whether two Boolean objects are equal.
public override bool Equals(Object obj)
{
//If it's not a boolean, we're definitely not equal
if (!(obj is Boolean))
{
return false;
}
return (m_value == ((Boolean)obj).m_value);
}
[NonVersionable]
public bool Equals(Boolean obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship. For booleans, false sorts before true.
// null is considered to be less than any instance.
// If object is not of type boolean, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is Boolean))
{
throw new ArgumentException(SR.Arg_MustBeBoolean);
}
if (m_value == ((Boolean)obj).m_value)
{
return 0;
}
else if (m_value == false)
{
return -1;
}
return 1;
}
public int CompareTo(Boolean value)
{
if (m_value == value)
{
return 0;
}
else if (m_value == false)
{
return -1;
}
return 1;
}
//
// Static Methods
//
// Determines whether a String represents true or false.
//
public static Boolean Parse(String value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
return Parse(value.AsReadOnlySpan());
}
public static bool Parse(ReadOnlySpan<char> value) =>
TryParse(value, out bool result) ? result : throw new FormatException(SR.Format_BadBoolean);
// Determines whether a String represents true or false.
//
public static Boolean TryParse(String value, out Boolean result)
{
if (value == null)
{
result = false;
return false;
}
return TryParse(value.AsReadOnlySpan(), out result);
}
public static bool TryParse(ReadOnlySpan<char> value, out bool result)
{
ReadOnlySpan<char> trueSpan = TrueLiteral.AsReadOnlySpan();
if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
ReadOnlySpan<char> falseSpan = FalseLiteral.AsReadOnlySpan();
if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
result = false;
return false;
}
private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value)
{
const char nullChar = (char)0x0000;
int start = 0;
while (start < value.Length)
{
if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar)
{
break;
}
start++;
}
int end = value.Length - 1;
while (end >= start)
{
if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar)
{
break;
}
end--;
}
return value.Slice(start, end - start + 1);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Boolean;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return m_value;
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
namespace Ocelot.UnitTests.Configuration
{
using Microsoft.AspNetCore.Hosting;
using Moq;
using Newtonsoft.Json;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Shouldly;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using TestStack.BDDfy;
using Xunit;
public class DiskFileConfigurationRepositoryTests : IDisposable
{
private readonly Mock<IWebHostEnvironment> _hostingEnvironment;
private IFileConfigurationRepository _repo;
private string _environmentSpecificPath;
private string _ocelotJsonPath;
private FileConfiguration _result;
private FileConfiguration _fileConfiguration;
// This is a bit dirty and it is dev.dev so that the ConfigurationBuilderExtensionsTests
// cant pick it up if they run in parralel..and the semaphore stops them running at the same time...sigh
// these are not really unit tests but whatever...
private string _environmentName = "DEV.DEV";
private static SemaphoreSlim _semaphore;
public DiskFileConfigurationRepositoryTests()
{
_semaphore = new SemaphoreSlim(1, 1);
_semaphore.Wait();
_hostingEnvironment = new Mock<IWebHostEnvironment>();
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new DiskFileConfigurationRepository(_hostingEnvironment.Object);
}
[Fact]
public void should_return_file_configuration()
{
var config = FakeFileConfigurationForGet();
this.Given(_ => GivenTheConfigurationIs(config))
.When(_ => WhenIGetTheReRoutes())
.Then(_ => ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_return_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForGet();
this.Given(_ => GivenTheEnvironmentNameIsUnavailable())
.And(_ => GivenTheConfigurationIs(config))
.When(_ => WhenIGetTheReRoutes())
.Then(_ => ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration()
{
var config = FakeFileConfigurationForSet();
this.Given(_ => GivenIHaveAConfiguration(config))
.When(_ => WhenISetTheConfiguration())
.Then(_ => ThenTheConfigurationIsStoredAs(config))
.And(_ => ThenTheConfigurationJsonIsIndented(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForSet();
this.Given(_ => GivenIHaveAConfiguration(config))
.And(_ => GivenTheEnvironmentNameIsUnavailable())
.When(_ => WhenISetTheConfiguration())
.Then(_ => ThenTheConfigurationIsStoredAs(config))
.And(_ => ThenTheConfigurationJsonIsIndented(config))
.BDDfy();
}
[Fact]
public void should_set_environment_file_configuration_and_ocelot_file_configuration()
{
var config = FakeFileConfigurationForSet();
this.Given(_ => GivenIHaveAConfiguration(config))
.And(_ => GivenTheConfigurationIs(config))
.And(_ => GivenTheUserAddedOcelotJson())
.When(_ => WhenISetTheConfiguration())
.Then(_ => ThenTheConfigurationIsStoredAs(config))
.And(_ => ThenTheConfigurationJsonIsIndented(config))
.Then(_ => ThenTheOcelotJsonIsStoredAs(config))
.BDDfy();
}
private void GivenTheUserAddedOcelotJson()
{
_ocelotJsonPath = $"{AppContext.BaseDirectory}/ocelot.json";
if (File.Exists(_ocelotJsonPath))
{
File.Delete(_ocelotJsonPath);
}
File.WriteAllText(_ocelotJsonPath, "Doesnt matter");
}
private void GivenTheEnvironmentNameIsUnavailable()
{
_environmentName = null;
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new DiskFileConfigurationRepository(_hostingEnvironment.Object);
}
private void GivenIHaveAConfiguration(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
}
private void WhenISetTheConfiguration()
{
_repo.Set(_fileConfiguration);
_result = _repo.Get().Result.Data;
}
private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for (var i = 0; i < _result.ReRoutes.Count; i++)
{
for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++)
{
var result = _result.ReRoutes[i].DownstreamHostAndPorts[j];
var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme);
}
}
private void ThenTheOcelotJsonIsStoredAs(FileConfiguration expecteds)
{
var resultText = File.ReadAllText(_ocelotJsonPath);
var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented);
resultText.ShouldBe(expectedText);
}
private void GivenTheConfigurationIs(FileConfiguration fileConfiguration)
{
_environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json";
var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented);
if (File.Exists(_environmentSpecificPath))
{
File.Delete(_environmentSpecificPath);
}
File.WriteAllText(_environmentSpecificPath, jsonConfiguration);
}
private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds)
{
var path = !string.IsNullOrEmpty(_environmentSpecificPath) ? _environmentSpecificPath : _environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json";
var resultText = File.ReadAllText(path);
var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented);
resultText.ShouldBe(expectedText);
}
private void WhenIGetTheReRoutes()
{
_result = _repo.Get().Result.Data;
}
private void ThenTheFollowingIsReturned(FileConfiguration expecteds)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for (var i = 0; i < _result.ReRoutes.Count; i++)
{
for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++)
{
var result = _result.ReRoutes[i].DownstreamHostAndPorts[j];
var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme);
}
}
private FileConfiguration FakeFileConfigurationForSet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "123.12.12.12",
Port = 80,
}
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/asdfs/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
private FileConfiguration FakeFileConfigurationForGet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 80,
}
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/test/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
public void Dispose()
{
_semaphore.Release();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Timers;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.Framework.Scenes.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using Timer = System.Timers.Timer;
using log4net;
namespace OpenSim.Region.Framework.Scenes
{
public class KeyframeTimer
{
private static Dictionary<Scene, KeyframeTimer> m_timers =
new Dictionary<Scene, KeyframeTimer>();
private Timer m_timer;
private Dictionary<KeyframeMotion, object> m_motions = new Dictionary<KeyframeMotion, object>();
private object m_lockObject = new object();
private object m_timerLock = new object();
private const double m_tickDuration = 50.0;
public double TickDuration
{
get { return m_tickDuration; }
}
public KeyframeTimer(Scene scene)
{
m_timer = new Timer();
m_timer.Interval = TickDuration;
m_timer.AutoReset = true;
m_timer.Elapsed += OnTimer;
}
public void Start()
{
lock (m_timer)
{
if (!m_timer.Enabled)
m_timer.Start();
}
}
private void OnTimer(object sender, ElapsedEventArgs ea)
{
if (!Monitor.TryEnter(m_timerLock))
return;
try
{
List<KeyframeMotion> motions;
lock (m_lockObject)
{
motions = new List<KeyframeMotion>(m_motions.Keys);
}
foreach (KeyframeMotion m in motions)
{
try
{
m.OnTimer(TickDuration);
}
catch (Exception)
{
// Don't stop processing
}
}
}
catch (Exception)
{
// Keep running no matter what
}
finally
{
Monitor.Exit(m_timerLock);
}
}
public static void Add(KeyframeMotion motion)
{
KeyframeTimer timer;
if (motion.Scene == null)
return;
lock (m_timers)
{
if (!m_timers.TryGetValue(motion.Scene, out timer))
{
timer = new KeyframeTimer(motion.Scene);
m_timers[motion.Scene] = timer;
if (!SceneManager.Instance.AllRegionsReady)
{
// Start the timers only once all the regions are ready. This is required
// when using megaregions, because the megaregion is correctly configured
// only after all the regions have been loaded. (If we don't do this then
// when the prim moves it might think that it crossed into a region.)
SceneManager.Instance.OnRegionsReadyStatusChange += delegate(SceneManager sm)
{
if (sm.AllRegionsReady)
timer.Start();
};
}
// Check again, in case the regions were started while we were adding the event handler
if (SceneManager.Instance.AllRegionsReady)
{
timer.Start();
}
}
}
lock (timer.m_lockObject)
{
timer.m_motions[motion] = null;
}
}
public static void Remove(KeyframeMotion motion)
{
KeyframeTimer timer;
if (motion.Scene == null)
return;
lock (m_timers)
{
if (!m_timers.TryGetValue(motion.Scene, out timer))
{
return;
}
}
lock (timer.m_lockObject)
{
timer.m_motions.Remove(motion);
}
}
}
[Serializable]
public class KeyframeMotion
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public enum PlayMode : int
{
Forward = 0,
Reverse = 1,
Loop = 2,
PingPong = 3
};
[Flags]
public enum DataFormat : int
{
Translation = 2,
Rotation = 1
}
[Serializable]
public struct Keyframe
{
public Vector3? Position;
public Quaternion? Rotation;
public Quaternion StartRotation;
public int TimeMS;
public int TimeTotal;
public Vector3 AngularVelocity;
public Vector3 StartPosition;
};
private Vector3 m_serializedPosition;
private Vector3 m_basePosition;
private Quaternion m_baseRotation;
private Keyframe m_currentFrame;
private List<Keyframe> m_frames = new List<Keyframe>();
private Keyframe[] m_keyframes;
// skip timer events.
//timer.stop doesn't assure there aren't event threads still being fired
[NonSerialized()]
private bool m_timerStopped;
[NonSerialized()]
private bool m_isCrossing;
[NonSerialized()]
private bool m_waitingCrossing;
// retry position for cross fail
[NonSerialized()]
private Vector3 m_nextPosition;
[NonSerialized()]
private SceneObjectGroup m_group;
private PlayMode m_mode = PlayMode.Forward;
private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation;
private bool m_running = false;
[NonSerialized()]
private bool m_selected = false;
private int m_iterations = 0;
private int m_skipLoops = 0;
[NonSerialized()]
private Scene m_scene;
public Scene Scene
{
get { return m_scene; }
}
public DataFormat Data
{
get { return m_data; }
}
public bool Selected
{
set
{
if (m_group != null)
{
if (!value)
{
// Once we're let go, recompute positions
if (m_selected)
UpdateSceneObject(m_group);
}
else
{
// Save selection position in case we get moved
if (!m_selected)
{
StopTimer();
m_serializedPosition = m_group.AbsolutePosition;
}
}
}
m_isCrossing = false;
m_waitingCrossing = false;
m_selected = value;
}
}
private void StartTimer()
{
lock (m_frames)
{
KeyframeTimer.Add(this);
m_timerStopped = false;
}
}
private void StopTimer()
{
lock (m_frames)
m_timerStopped = true;
}
public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data)
{
KeyframeMotion newMotion = null;
try
{
using (MemoryStream ms = new MemoryStream(data))
{
BinaryFormatter fmt = new BinaryFormatter();
newMotion = (KeyframeMotion)fmt.Deserialize(ms);
}
newMotion.m_group = grp;
if (grp != null)
{
newMotion.m_scene = grp.Scene;
if (grp.IsSelected)
newMotion.m_selected = true;
}
newMotion.m_timerStopped = false;
newMotion.m_running = true;
newMotion.m_isCrossing = false;
newMotion.m_waitingCrossing = false;
}
catch
{
newMotion = null;
}
return newMotion;
}
public void UpdateSceneObject(SceneObjectGroup grp)
{
m_isCrossing = false;
m_waitingCrossing = false;
StopTimer();
if (grp == null)
return;
m_group = grp;
m_scene = grp.Scene;
lock (m_frames)
{
Vector3 grppos = grp.AbsolutePosition;
Vector3 offset = grppos - m_serializedPosition;
// avoid doing it more than once
// current this will happen draging a prim to other region
m_serializedPosition = grppos;
m_basePosition += offset;
m_currentFrame.Position += offset;
m_nextPosition += offset;
for (int i = 0; i < m_frames.Count; i++)
{
Keyframe k = m_frames[i];
k.Position += offset;
m_frames[i] = k;
}
}
if (m_running)
Start();
}
public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data)
{
m_mode = mode;
m_data = data;
m_group = grp;
if (grp != null)
{
m_basePosition = grp.AbsolutePosition;
m_baseRotation = grp.GroupRotation;
m_scene = grp.Scene;
}
m_timerStopped = true;
m_isCrossing = false;
m_waitingCrossing = false;
}
public void SetKeyframes(Keyframe[] frames)
{
m_keyframes = frames;
}
public KeyframeMotion Copy(SceneObjectGroup newgrp)
{
StopTimer();
KeyframeMotion newmotion = new KeyframeMotion(null, m_mode, m_data);
newmotion.m_group = newgrp;
newmotion.m_scene = newgrp.Scene;
if (m_keyframes != null)
{
newmotion.m_keyframes = new Keyframe[m_keyframes.Length];
m_keyframes.CopyTo(newmotion.m_keyframes, 0);
}
lock (m_frames)
{
newmotion.m_frames = new List<Keyframe>(m_frames);
newmotion.m_basePosition = m_basePosition;
newmotion.m_baseRotation = m_baseRotation;
if (m_selected)
newmotion.m_serializedPosition = m_serializedPosition;
else
{
if (m_group != null)
newmotion.m_serializedPosition = m_group.AbsolutePosition;
else
newmotion.m_serializedPosition = m_serializedPosition;
}
newmotion.m_currentFrame = m_currentFrame;
newmotion.m_iterations = m_iterations;
newmotion.m_running = m_running;
}
if (m_running && !m_waitingCrossing)
StartTimer();
return newmotion;
}
public void Delete()
{
m_running = false;
StopTimer();
m_isCrossing = false;
m_waitingCrossing = false;
m_frames.Clear();
m_keyframes = null;
}
public void Start()
{
m_isCrossing = false;
m_waitingCrossing = false;
if (m_keyframes != null && m_group != null && m_keyframes.Length > 0)
{
StartTimer();
m_running = true;
m_group.Scene.EventManager.TriggerMovingStartEvent(m_group.RootPart.LocalId);
}
else
{
StopTimer();
m_running = false;
}
}
public void Stop()
{
StopTimer();
m_running = false;
m_isCrossing = false;
m_waitingCrossing = false;
m_basePosition = m_group.AbsolutePosition;
m_baseRotation = m_group.GroupRotation;
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
m_frames.Clear();
}
public void Pause()
{
StopTimer();
m_running = false;
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_skippedUpdates = 1000;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
}
public void Suspend()
{
lock (m_frames)
{
if (m_timerStopped)
return;
m_timerStopped = true;
}
}
public void Resume()
{
lock (m_frames)
{
if (!m_timerStopped)
return;
if (m_running && !m_waitingCrossing)
StartTimer();
m_skippedUpdates = 1000;
}
}
private void GetNextList()
{
m_frames.Clear();
Vector3 pos = m_basePosition;
Quaternion rot = m_baseRotation;
if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
{
int direction = 1;
if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
direction = -1;
int start = 0;
int end = m_keyframes.Length;
if (direction < 0)
{
start = m_keyframes.Length - 1;
end = -1;
}
for (int i = start; i != end ; i += direction)
{
Keyframe k = m_keyframes[i];
k.StartPosition = pos;
if (k.Position.HasValue)
{
k.Position = (k.Position * direction);
// k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f);
k.Position += pos;
}
else
{
k.Position = pos;
// k.Velocity = Vector3.Zero;
}
k.StartRotation = rot;
if (k.Rotation.HasValue)
{
if (direction == -1)
k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
k.Rotation = rot * k.Rotation;
}
else
{
k.Rotation = rot;
}
/* ang vel not in use for now
float angle = 0;
float aa = k.StartRotation.X * k.StartRotation.X + k.StartRotation.Y * k.StartRotation.Y + k.StartRotation.Z * k.StartRotation.Z + k.StartRotation.W * k.StartRotation.W;
float bb = ((Quaternion)k.Rotation).X * ((Quaternion)k.Rotation).X + ((Quaternion)k.Rotation).Y * ((Quaternion)k.Rotation).Y + ((Quaternion)k.Rotation).Z * ((Quaternion)k.Rotation).Z + ((Quaternion)k.Rotation).W * ((Quaternion)k.Rotation).W;
float aa_bb = aa * bb;
if (aa_bb == 0)
{
angle = 0;
}
else
{
float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
k.StartRotation.W * ((Quaternion)k.Rotation).W;
float q = (ab * ab) / aa_bb;
if (q > 1.0f)
{
angle = 0;
}
else
{
angle = (float)Math.Acos(2 * q - 1);
}
}
k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
*/
k.TimeTotal = k.TimeMS;
m_frames.Add(k);
pos = (Vector3)k.Position;
rot = (Quaternion)k.Rotation;
}
m_basePosition = pos;
m_baseRotation = rot;
m_iterations++;
}
}
public void OnTimer(double tickDuration)
{
if (!Monitor.TryEnter(m_frames))
return;
if (m_timerStopped)
KeyframeTimer.Remove(this);
else
DoOnTimer(tickDuration);
Monitor.Exit(m_frames);
}
private void Done()
{
KeyframeTimer.Remove(this);
m_timerStopped = true;
m_running = false;
m_isCrossing = false;
m_waitingCrossing = false;
m_basePosition = m_group.AbsolutePosition;
m_baseRotation = m_group.GroupRotation;
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
m_frames.Clear();
}
Vector3 m_lastPosUpdate;
Quaternion m_lastRotationUpdate;
Vector3 m_currentVel;
int m_skippedUpdates;
private void DoOnTimer(double tickDuration)
{
if (m_skipLoops > 0)
{
m_skipLoops--;
return;
}
if (m_group == null)
return;
bool update = false;
if (m_selected)
{
if (m_group.RootPart.Velocity != Vector3.Zero)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_skippedUpdates = 1000;
m_group.SendGroupRootTerseUpdate();
}
return;
}
if (m_isCrossing)
{
// if crossing and timer running then cross failed
// wait some time then
// retry to set the position that evtually caused the outbound
// if still outside region this will call startCrossing below
m_isCrossing = false;
m_skippedUpdates = 1000;
m_group.AbsolutePosition = m_nextPosition;
if (!m_isCrossing)
{
StopTimer();
StartTimer();
}
return;
}
if (m_frames.Count == 0)
{
lock (m_frames)
{
GetNextList();
if (m_frames.Count == 0)
{
Done();
m_group.Scene.EventManager.TriggerMovingEndEvent(m_group.RootPart.LocalId);
return;
}
m_currentFrame = m_frames[0];
}
m_nextPosition = m_group.AbsolutePosition;
m_currentVel = (Vector3)m_currentFrame.Position - m_nextPosition;
m_currentVel /= (m_currentFrame.TimeMS * 0.001f);
m_currentFrame.TimeMS += (int)tickDuration;
update = true;
}
m_currentFrame.TimeMS -= (int)tickDuration;
// Do the frame processing
double remainingSteps = (double)m_currentFrame.TimeMS / tickDuration;
if (remainingSteps <= 1.0)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_nextPosition = (Vector3)m_currentFrame.Position;
m_group.AbsolutePosition = m_nextPosition;
m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation;
lock (m_frames)
{
m_frames.RemoveAt(0);
if (m_frames.Count > 0)
{
m_currentFrame = m_frames[0];
m_currentVel = (Vector3)m_currentFrame.Position - m_nextPosition;
m_currentVel /= (m_currentFrame.TimeMS * 0.001f);
m_group.RootPart.Velocity = m_currentVel;
m_currentFrame.TimeMS += (int)tickDuration;
}
else
m_group.RootPart.Velocity = Vector3.Zero;
}
update = true;
}
else
{
bool lastSteps = remainingSteps < 4;
Vector3 currentPosition = m_group.AbsolutePosition;
Vector3 motionThisFrame = (Vector3)m_currentFrame.Position - currentPosition;
motionThisFrame /= (float)remainingSteps;
m_nextPosition = currentPosition + motionThisFrame;
Quaternion currentRotation = m_group.GroupRotation;
if ((Quaternion)m_currentFrame.Rotation != currentRotation)
{
float completed = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, completed);
step.Normalize();
m_group.RootPart.RotationOffset = step;
if (Math.Abs(step.X - m_lastRotationUpdate.X) > 0.001f
|| Math.Abs(step.Y - m_lastRotationUpdate.Y) > 0.001f
|| Math.Abs(step.Z - m_lastRotationUpdate.Z) > 0.001f)
update = true;
}
m_group.AbsolutePosition = m_nextPosition;
if(lastSteps)
m_group.RootPart.Velocity = Vector3.Zero;
else
m_group.RootPart.Velocity = m_currentVel;
if(!update && (
lastSteps ||
m_skippedUpdates * tickDuration > 0.5 ||
Math.Abs(m_nextPosition.X - currentPosition.X) > 5f ||
Math.Abs(m_nextPosition.Y - currentPosition.Y) > 5f ||
Math.Abs(m_nextPosition.Z - currentPosition.Z) > 5f
))
{
update = true;
}
else
m_skippedUpdates++;
}
if(update)
{
m_lastPosUpdate = m_nextPosition;
m_lastRotationUpdate = m_group.GroupRotation;
m_skippedUpdates = 0;
m_group.SendGroupRootTerseUpdate();
}
}
public Byte[] Serialize()
{
bool timerWasStopped;
lock (m_frames)
{
timerWasStopped = m_timerStopped;
}
StopTimer();
SceneObjectGroup tmp = m_group;
m_group = null;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter fmt = new BinaryFormatter();
if (!m_selected && tmp != null)
m_serializedPosition = tmp.AbsolutePosition;
fmt.Serialize(ms, this);
m_group = tmp;
if (!timerWasStopped && m_running && !m_waitingCrossing)
StartTimer();
return ms.ToArray();
}
}
public void StartCrossingCheck()
{
// timer will be restart by crossingFailure
// or never since crossing worked and this
// should be deleted
StopTimer();
m_isCrossing = true;
m_waitingCrossing = true;
// to remove / retune to smoth crossings
if (m_group.RootPart.Velocity != Vector3.Zero)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_skippedUpdates = 1000;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
}
}
public void CrossingFailure()
{
m_waitingCrossing = false;
if (m_group != null)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_skippedUpdates = 1000;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
if (m_running)
{
StopTimer();
m_skipLoops = 1200; // 60 seconds
StartTimer();
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DataSourceProvider.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: common base class and contract for data source provider objects
//
// Specs: http://avalon/connecteddata/Specs/Avalon%20DataProviders.mht
//
//---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using System.Windows.Threading; // Dispatcher*
using MS.Internal; // Invariant
namespace System.Windows.Data
{
/// <summary>
/// Common base class and contract for data source providers.
/// A DataProvider in Avalon is the factory that executes some query
/// to produce a single object or a list of objects that can be used
/// as sources for Avalon data bindings.
/// It is a convenience wrapper around existing data model, it does not replace any data model.
/// A data provider does not attempt to condense the complexity and versatility of a data model
/// like ADO into one single object with a few properties.
/// </summary>
/// <remarks>
/// DataSourceProvider is an abstract class and cannot directly be used as a data provider.
/// Use one of the derived concrete provider, e.g. XmlDataProvider, ObjectDataProvider.
/// The DataProvider aware of Avalon's threading and dispatcher model. The data provider assumes
/// the thread at creation time to be the UI thread. Events will get marshalled from a worker thread
/// to the app's UI thread.
/// </remarks>
public abstract class DataSourceProvider : INotifyPropertyChanged, ISupportInitialize
{
/// <summary>
/// constructor captures the Dispatcher associated with the current thread
/// </summary>
protected DataSourceProvider()
{
_dispatcher = Dispatcher.CurrentDispatcher;
}
/// <summary>
/// Start the initial query to the underlying data model.
/// The result will be returned on the Data property.
/// This method is typically called by the binding engine when
/// dependent data bindings are activated.
/// Set IsInitialLoadEnabled = false to prevent or delay the automatic loading of data.
/// </summary>
/// <remarks>
/// The InitialLoad method can be called multiple times.
/// The provider is expected to ignore subsequent calls once the provider
/// is busy executing the initial query, i.e. the provider shall not restart
/// an already running query when InitialLoad is called again.
/// When the query finishes successfully, any InitialLoad call will still not re-query data.
/// The InitialLoad operation is typically asynchronous, a DataChanged event will
/// be raised when the Data property assumed a new value.
/// The application should call Refresh to cause a refresh of data.
/// </remarks>
public void InitialLoad()
{
// ignore call if IsInitialLoadEnabled == false or already started initialization
if (!IsInitialLoadEnabled || _initialLoadCalled)
return;
_initialLoadCalled = true;
BeginQuery();
}
/// <summary>
/// Initiates a Refresh Operation to the underlying data model.
/// The result will be returned on the Data property.
/// </summary>
/// <remarks>
/// A refresh operation is typically asynchronous, a DataChanged event will
/// be raised when the Data property assumed a new value.
/// If the refresh operation fails, the Data property will be set to null;
/// the Error property will be set with the error exception.
/// The app can call Refresh while a previous refresh is still underway.
/// Calling Refresh twice will cause the DataChanged event to raise twice.
/// </remarks>
public void Refresh()
{
_initialLoadCalled = true;
BeginQuery();
}
/// <summary>
/// Set IsInitialLoadEnabled = false to prevent or delay the automatic loading of data.
/// </summary>
[DefaultValue(true)]
public bool IsInitialLoadEnabled
{
get { return _isInitialLoadEnabled; }
set
{
_isInitialLoadEnabled = value;
OnPropertyChanged(new PropertyChangedEventArgs("IsInitialLoadEnabled"));
}
}
/// <summary>
/// Get the underlying data object.
/// This is the resulting data source the data provider
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public object Data
{
get { return _data; }
}
/// <summary>
/// Raise this event when a new data object becomes available
/// on the Data property.
/// </summary>
public event EventHandler DataChanged;
/// <summary>
/// Return the error of the last query operation.
/// To indicate there was no error, it will return null
/// </summary>
public Exception Error
{
get { return _error; }
}
/// <summary>
/// Enter a Defer Cycle.
/// Defer cycles are used to coalesce property changes, any automatic
/// Refresh is delayed until the Defer Cycle is exited.
/// </summary>
/// <remarks>
/// most typical usage is with a using block to set multiple proporties
/// without the automatic Refresh to occur
/// <code>
/// XmlDataProvider xdv = new XmlDataProvider();
/// using(xdv.DeferRefresh()) {
/// xdv.Source = "http://foo.com/bar.xml";
/// xdv.XPath = "/Bla/Baz[@Boo='xyz']";
/// }
/// </code>
/// </remarks>
public virtual IDisposable DeferRefresh()
{
++_deferLevel;
return new DeferHelper(this);
}
#region ISupportInitialize
/// <summary>
/// Initialization of this element is about to begin
/// </summary>
void ISupportInitialize.BeginInit()
{
BeginInit();
}
/// <summary>
/// Initialization of this element has completed
/// </summary>
void ISupportInitialize.EndInit()
{
EndInit();
}
#endregion
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
PropertyChanged += value;
}
remove
{
PropertyChanged -= value;
}
}
//------------------------------------------------------
//
// Protected Properties
//
//------------------------------------------------------
/// <summary>
/// IsRefreshDeferred returns true if there is still an
/// outstanding DeferRefresh in use. To get the best use
/// out of refresh deferral, derived classes should try
/// not to call Refresh when IsRefreshDeferred is true.
/// </summary>
protected bool IsRefreshDeferred
{
get
{
return ( (_deferLevel > 0)
|| (!IsInitialLoadEnabled && !_initialLoadCalled));
}
}
/// <summary>
/// The current Dispatcher to the Avalon UI thread to use.
/// </summary>
/// <remarks>
/// By default, this is the Dispatcher associated with the thread
/// on which this DataProvider instance was created.
/// </remarks>
protected Dispatcher Dispatcher
{
get { return _dispatcher; }
set
{
if (_dispatcher != value)
{
_dispatcher = value;
}
}
}
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Overridden by concrete data provider class.
/// the base class will call this method when InitialLoad or Refresh
/// has been called and will delay this call if refresh is deferred ot
/// initial load is disabled.
/// </summary>
/// <remarks>
/// The implementor can choose to execute the query on the same thread or
/// on a background thread or using asynchronous API.
/// When the query is complete, call OnQueryFinished to have the public properties updated.
/// </remarks>
protected virtual void BeginQuery()
{
}
/// <summary>
/// A concrete data provider will call this method
/// to indicate that a query has finished.
/// </summary>
/// <remarks>
/// This callback can be called from any thread, this implementation
/// will marshal back the result to the UI thread
/// before setting any of the public properties and before raising any events.
/// <param name="newData">resulting data from query</param>
/// </remarks>
protected void OnQueryFinished(object newData)
{
OnQueryFinished(newData, null, null, null);
}
/// <summary>
/// A concrete data provider will call this method
/// to indicate that a query has finished.
/// </summary>
/// <remarks>
/// This callback can be called from any thread, this implementation
/// will marshal back the result to the UI thread
/// before setting any of the public properties and before raising any events.
/// <param name="newData">resulting data from query</param>
/// <param name="error">error that occured while running query; null signals no error</param>
/// <param name="completionWork">optional delegate to execute completion work on UI thread, e.g. setting additional properties</param>
/// <param name="callbackArguments">optional arguments to send as parameter with the completionWork delegate</param>
/// </remarks>
protected virtual void OnQueryFinished(object newData, Exception error,
DispatcherOperationCallback completionWork, object callbackArguments)
{
Invariant.Assert(Dispatcher != null);
// check if we're already on the dispatcher thread
if (Dispatcher.CheckAccess())
{
// already on UI thread
UpdateWithNewResult(error, newData, completionWork, callbackArguments);
}
else
{
// marshal the result back to the main thread
Dispatcher.BeginInvoke(
DispatcherPriority.Normal, UpdateWithNewResultCallback,
new object[] { this, error, newData, completionWork, callbackArguments });
}
}
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
/// <summary>
/// Initialization of this element is about to begin;
/// no implicit Refresh occurs until the matched EndInit is called
/// </summary>
protected virtual void BeginInit()
{
++_deferLevel;
}
/// <summary>
/// Initialization of this element has completed;
/// this causes a Refresh if no other deferred refresh is outstanding
/// </summary>
protected virtual void EndInit()
{
EndDefer();
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
private void EndDefer()
{
Debug.Assert(_deferLevel > 0);
--_deferLevel;
if (_deferLevel == 0)
{
Refresh();
}
}
private static object UpdateWithNewResult(object arg)
{
object[] args = (object[]) arg;
Invariant.Assert(args.Length == 5);
DataSourceProvider provider = (DataSourceProvider) args[0];
Exception error = (Exception) args[1];
object newData = args[2];
DispatcherOperationCallback completionWork
= (DispatcherOperationCallback) args[3];
object callbackArgs = args[4];
provider.UpdateWithNewResult(error, newData, completionWork, callbackArgs);
return null;
}
private void UpdateWithNewResult(Exception error, object newData, DispatcherOperationCallback completionWork, object callbackArgs)
{
bool errorChanged = (_error != error);
_error = error;
if (error != null)
{
newData = null;
_initialLoadCalled = false; // allow again InitialLoad after an error
}
_data = newData;
if (completionWork != null)
completionWork(callbackArgs);
// notify any listeners
OnPropertyChanged(new PropertyChangedEventArgs("Data"));
if (DataChanged != null)
{
DataChanged(this, EventArgs.Empty);
}
if (errorChanged)
OnPropertyChanged(new PropertyChangedEventArgs("Error"));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
private class DeferHelper : IDisposable
{
public DeferHelper(DataSourceProvider provider)
{
_provider = provider;
}
public void Dispose()
{
GC.SuppressFinalize(this);
if (_provider != null)
{
_provider.EndDefer();
_provider = null;
}
}
private DataSourceProvider _provider;
}
#endregion
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
private bool _isInitialLoadEnabled = true;
private bool _initialLoadCalled;
private int _deferLevel;
private object _data;
private Exception _error;
private Dispatcher _dispatcher;
static readonly DispatcherOperationCallback UpdateWithNewResultCallback = new DispatcherOperationCallback(UpdateWithNewResult);
}
}
| |
/* ****************************************************************************
*
* 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
* vspython@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.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using VSLangProj;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents the automation object for the equivalent ReferenceContainerNode object
/// </summary>
[ComVisible(true)]
public class OAReferences : ConnectionPointContainer,
IEventSource<_dispReferencesEvents>,
References,
ReferencesEvents
{
private readonly ProjectNode _project;
private ReferenceContainerNode _container;
/// <summary>
/// Creates a new automation references object. If the project type doesn't
/// support references containerNode is null.
/// </summary>
/// <param name="containerNode"></param>
/// <param name="project"></param>
internal OAReferences(ReferenceContainerNode containerNode, ProjectNode project)
{
_container = containerNode;
_project = project;
AddEventSource<_dispReferencesEvents>(this as IEventSource<_dispReferencesEvents>);
if (_container != null) {
_container.OnChildAdded += new EventHandler<HierarchyNodeEventArgs>(OnReferenceAdded);
_container.OnChildRemoved += new EventHandler<HierarchyNodeEventArgs>(OnReferenceRemoved);
}
}
#region Private Members
private Reference AddFromSelectorData(VSCOMPONENTSELECTORDATA selector)
{
if (_container == null) {
return null;
}
ReferenceNode refNode = _container.AddReferenceFromSelectorData(selector);
if (null == refNode)
{
return null;
}
return refNode.Object as Reference;
}
private Reference FindByName(string stringIndex)
{
foreach (Reference refNode in this)
{
if (0 == string.Compare(refNode.Name, stringIndex, StringComparison.Ordinal))
{
return refNode;
}
}
return null;
}
#endregion
#region References Members
public Reference Add(string bstrPath)
{
// ignore requests from the designer which are framework assemblies and start w/ a *.
if (string.IsNullOrEmpty(bstrPath) || bstrPath.StartsWith("*"))
{
return null;
}
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_File;
selector.bstrFile = bstrPath;
return AddFromSelectorData(selector);
}
public Reference AddActiveX(string bstrTypeLibGuid, int lMajorVer, int lMinorVer, int lLocaleId, string bstrWrapperTool)
{
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Com2;
selector.guidTypeLibrary = new Guid(bstrTypeLibGuid);
selector.lcidTypeLibrary = (uint)lLocaleId;
selector.wTypeLibraryMajorVersion = (ushort)lMajorVer;
selector.wTypeLibraryMinorVersion = (ushort)lMinorVer;
return AddFromSelectorData(selector);
}
public Reference AddProject(EnvDTE.Project project)
{
if (null == project || _container == null)
{
return null;
}
// Get the soulution.
IVsSolution solution = _container.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution;
if (null == solution)
{
return null;
}
// Get the hierarchy for this project.
IVsHierarchy projectHierarchy;
ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy));
// Create the selector data.
VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA();
selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project;
// Get the project reference string.
ErrorHandler.ThrowOnFailure(solution.GetProjrefOfProject(projectHierarchy, out selector.bstrProjRef));
selector.bstrTitle = project.Name;
selector.bstrFile = System.IO.Path.GetDirectoryName(project.FullName);
return AddFromSelectorData(selector);
}
public EnvDTE.Project ContainingProject
{
get
{
return _project.GetAutomationObject() as EnvDTE.Project;
}
}
public int Count
{
get
{
if (_container == null)
{
return 0;
}
return _container.EnumReferences().Count;
}
}
public EnvDTE.DTE DTE
{
get
{
return _project.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
public Reference Find(string bstrIdentity)
{
if (string.IsNullOrEmpty(bstrIdentity))
{
return null;
}
foreach (Reference refNode in this)
{
if (null != refNode)
{
if (0 == string.Compare(bstrIdentity, refNode.Identity, StringComparison.Ordinal))
{
return refNode;
}
}
}
return null;
}
public IEnumerator GetEnumerator()
{
if (_container == null) {
return new List<Reference>().GetEnumerator();
}
List<Reference> references = new List<Reference>();
IEnumerator baseEnum = _container.EnumReferences().GetEnumerator();
if (null == baseEnum)
{
return references.GetEnumerator();
}
while (baseEnum.MoveNext())
{
ReferenceNode refNode = baseEnum.Current as ReferenceNode;
if (null == refNode)
{
continue;
}
Reference reference = refNode.Object as Reference;
if (null != reference)
{
references.Add(reference);
}
}
return references.GetEnumerator();
}
public Reference Item(object index)
{
if (_container == null)
{
throw new ArgumentOutOfRangeException("index");
}
string stringIndex = index as string;
if (null != stringIndex)
{
return FindByName(stringIndex);
}
// Note that this cast will throw if the index is not convertible to int.
int intIndex = (int)index;
IList<ReferenceNode> refs = _container.EnumReferences();
if (null == refs)
{
throw new ArgumentOutOfRangeException("index");
}
if ((intIndex <= 0) || (intIndex > refs.Count))
{
throw new ArgumentOutOfRangeException("index");
}
// Let the implementation of IList<> throw in case of index not correct.
return refs[intIndex - 1].Object as Reference;
}
public object Parent
{
get
{
if (_container == null)
{
return _project.Object;
}
return _container.Parent.Object;
}
}
#endregion
#region _dispReferencesEvents_Event Members
public event _dispReferencesEvents_ReferenceAddedEventHandler ReferenceAdded;
public event _dispReferencesEvents_ReferenceChangedEventHandler ReferenceChanged {
add { }
remove { }
}
public event _dispReferencesEvents_ReferenceRemovedEventHandler ReferenceRemoved;
#endregion
#region Callbacks for the HierarchyNode events
private void OnReferenceAdded(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((_container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceAdded)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceAdded(reference);
}
}
private void OnReferenceRemoved(object sender, HierarchyNodeEventArgs args)
{
// Validate the parameters.
if ((_container != sender as ReferenceContainerNode) ||
(null == args) || (null == args.Child))
{
return;
}
// Check if there is any sink for this event.
if (null == ReferenceRemoved)
{
return;
}
// Check that the removed item implements the Reference interface.
Reference reference = args.Child.Object as Reference;
if (null != reference)
{
ReferenceRemoved(reference);
}
}
#endregion
#region IEventSource<_dispReferencesEvents> Members
void IEventSource<_dispReferencesEvents>.OnSinkAdded(_dispReferencesEvents sink)
{
ReferenceAdded += new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged += new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved += new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
void IEventSource<_dispReferencesEvents>.OnSinkRemoved(_dispReferencesEvents sink)
{
ReferenceAdded -= new _dispReferencesEvents_ReferenceAddedEventHandler(sink.ReferenceAdded);
ReferenceChanged -= new _dispReferencesEvents_ReferenceChangedEventHandler(sink.ReferenceChanged);
ReferenceRemoved -= new _dispReferencesEvents_ReferenceRemovedEventHandler(sink.ReferenceRemoved);
}
#endregion
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Dite.CoreApi.Models;
namespace Dite.CoreApi.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Dite.CoreApi.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("Dite.Model.DiteUser", b =>
{
b.Property<Guid>("DiteUserId")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("GivenName");
b.Property<string>("Name");
b.Property<string>("NameIdentifier");
b.HasKey("DiteUserId");
});
modelBuilder.Entity("Dite.Model.TimerCounter", b =>
{
b.Property<Guid>("TimerCounterId")
.ValueGeneratedOnAdd();
b.Property<Guid>("DiteUserId");
b.Property<bool>("IsRunning");
b.Property<double>("Seconds");
b.Property<DateTime>("TimerEnd");
b.Property<DateTimeOffset>("TimerEndLocal");
b.Property<TimeSpan>("TimerEndLocalTime");
b.Property<DateTimeOffset>("TimerEndUtc");
b.Property<Guid>("TimerHandlerId");
b.Property<DateTime>("TimerStart");
b.Property<DateTimeOffset>("TimerStartLocal");
b.Property<TimeSpan>("TimerStartLocalTime");
b.Property<DateTimeOffset>("TimerStartUtc");
b.HasKey("TimerCounterId");
});
modelBuilder.Entity("Dite.Model.TimerHandler", b =>
{
b.Property<Guid>("TimerHandlerId")
.ValueGeneratedOnAdd();
b.Property<Guid>("DiteUserId");
b.Property<bool>("IsRunning");
b.Property<string>("Name");
b.HasKey("TimerHandlerId");
});
modelBuilder.Entity("Dite.Model.TimerResult", b =>
{
b.Property<Guid>("TimerResultId")
.ValueGeneratedOnAdd();
b.Property<int>("DayOfMonth");
b.Property<string>("DayOfWeek");
b.Property<int>("DayOfYear");
b.Property<Guid>("DiteUserId");
b.Property<int>("HourOfDay");
b.Property<int>("MinuteOfHour");
b.Property<int>("MonthOfYear");
b.Property<string>("Name");
b.Property<double>("Seconds");
b.Property<Guid>("TimerCounterId");
b.Property<Guid>("TimerHandlerId");
b.Property<int>("WeekOfMonth");
b.Property<int>("WeekOfYear");
b.Property<int>("Year");
b.HasKey("TimerResultId");
});
modelBuilder.Entity("Dite.Model.TimerTarget", b =>
{
b.Property<Guid>("TimerTargetId")
.ValueGeneratedOnAdd();
b.Property<int>("DayTargetHours");
b.Property<int>("DayTargetMinutes");
b.Property<Guid>("DiteUserId");
b.Property<int>("MonthTargetHours");
b.Property<int>("MonthTargetMinutes");
b.Property<string>("Name");
b.Property<double>("Seconds");
b.Property<int>("SecondsPerDay");
b.Property<int>("SecondsPerMonth");
b.Property<int>("SecondsPerWeek");
b.Property<int>("SecondsPerYear");
b.Property<int>("SecondsTotal");
b.Property<Guid>("TimerHandlerId");
b.Property<int>("TotalTargetHours");
b.Property<int>("TotalTargetMinutes");
b.Property<int>("WeekTargetHours");
b.Property<int>("WeekTargetMinutes");
b.Property<int>("YearTargetHours");
b.Property<int>("YearTargetMinutes");
b.HasKey("TimerTargetId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("Dite.Model.TimerCounter", b =>
{
b.HasOne("Dite.Model.TimerHandler")
.WithMany()
.HasForeignKey("TimerHandlerId");
});
modelBuilder.Entity("Dite.Model.TimerResult", b =>
{
b.HasOne("Dite.Model.TimerCounter")
.WithMany()
.HasForeignKey("TimerCounterId");
});
modelBuilder.Entity("Dite.Model.TimerTarget", b =>
{
b.HasOne("Dite.Model.TimerHandler")
.WithMany()
.HasForeignKey("TimerHandlerId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("Dite.CoreApi.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Billing.Budgets.V1Beta1
{
/// <summary>Settings for <see cref="BudgetServiceClient"/> instances.</summary>
public sealed partial class BudgetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="BudgetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="BudgetServiceSettings"/>.</returns>
public static BudgetServiceSettings GetDefault() => new BudgetServiceSettings();
/// <summary>Constructs a new <see cref="BudgetServiceSettings"/> object with default settings.</summary>
public BudgetServiceSettings()
{
}
private BudgetServiceSettings(BudgetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateBudgetSettings = existing.CreateBudgetSettings;
UpdateBudgetSettings = existing.UpdateBudgetSettings;
GetBudgetSettings = existing.GetBudgetSettings;
ListBudgetsSettings = existing.ListBudgetsSettings;
DeleteBudgetSettings = existing.DeleteBudgetSettings;
OnCopy(existing);
}
partial void OnCopy(BudgetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BudgetServiceClient.CreateBudget</c> and <c>BudgetServiceClient.CreateBudgetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateBudgetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BudgetServiceClient.UpdateBudget</c> and <c>BudgetServiceClient.UpdateBudgetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>,
/// <see cref="grpccore::StatusCode.Unavailable"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateBudgetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BudgetServiceClient.GetBudget</c> and <c>BudgetServiceClient.GetBudgetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>,
/// <see cref="grpccore::StatusCode.Unavailable"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetBudgetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BudgetServiceClient.ListBudgets</c> and <c>BudgetServiceClient.ListBudgetsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>,
/// <see cref="grpccore::StatusCode.Unavailable"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListBudgetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BudgetServiceClient.DeleteBudget</c> and <c>BudgetServiceClient.DeleteBudgetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: 5</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.DeadlineExceeded"/>,
/// <see cref="grpccore::StatusCode.Unavailable"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteBudgetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Unavailable)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="BudgetServiceSettings"/> object.</returns>
public BudgetServiceSettings Clone() => new BudgetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="BudgetServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class BudgetServiceClientBuilder : gaxgrpc::ClientBuilderBase<BudgetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public BudgetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public BudgetServiceClientBuilder()
{
UseJwtAccessWithScopes = BudgetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref BudgetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BudgetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override BudgetServiceClient Build()
{
BudgetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<BudgetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<BudgetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private BudgetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return BudgetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<BudgetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return BudgetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => BudgetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => BudgetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => BudgetServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>BudgetService client wrapper, for convenient use.</summary>
/// <remarks>
/// BudgetService stores Cloud Billing budgets, which define a
/// budget plan and rules to execute as we track spend against that plan.
/// </remarks>
public abstract partial class BudgetServiceClient
{
/// <summary>
/// The default endpoint for the BudgetService service, which is a host of "billingbudgets.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "billingbudgets.googleapis.com:443";
/// <summary>The default BudgetService scopes.</summary>
/// <remarks>
/// The default BudgetService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-billing</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-billing",
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="BudgetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="BudgetServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="BudgetServiceClient"/>.</returns>
public static stt::Task<BudgetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new BudgetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="BudgetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="BudgetServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="BudgetServiceClient"/>.</returns>
public static BudgetServiceClient Create() => new BudgetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="BudgetServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="BudgetServiceSettings"/>.</param>
/// <returns>The created <see cref="BudgetServiceClient"/>.</returns>
internal static BudgetServiceClient Create(grpccore::CallInvoker callInvoker, BudgetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
BudgetService.BudgetServiceClient grpcClient = new BudgetService.BudgetServiceClient(callInvoker);
return new BudgetServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC BudgetService client</summary>
public virtual BudgetService.BudgetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates a new budget. See
/// [Quotas and limits](https://cloud.google.com/billing/quotas)
/// for more information on the limits of the number of budgets you can create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Budget CreateBudget(CreateBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new budget. See
/// [Quotas and limits](https://cloud.google.com/billing/quotas)
/// for more information on the limits of the number of budgets you can create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Budget> CreateBudgetAsync(CreateBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new budget. See
/// [Quotas and limits](https://cloud.google.com/billing/quotas)
/// for more information on the limits of the number of budgets you can create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Budget> CreateBudgetAsync(CreateBudgetRequest request, st::CancellationToken cancellationToken) =>
CreateBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates a budget and returns the updated budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. Budget fields that are not exposed in
/// this API will not be changed by this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Budget UpdateBudget(UpdateBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a budget and returns the updated budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. Budget fields that are not exposed in
/// this API will not be changed by this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Budget> UpdateBudgetAsync(UpdateBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates a budget and returns the updated budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. Budget fields that are not exposed in
/// this API will not be changed by this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Budget> UpdateBudgetAsync(UpdateBudgetRequest request, st::CancellationToken cancellationToken) =>
UpdateBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns a budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Budget GetBudget(GetBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Budget> GetBudgetAsync(GetBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Budget> GetBudgetAsync(GetBudgetRequest request, st::CancellationToken cancellationToken) =>
GetBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns a list of budgets for a billing account.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Budget"/> resources.</returns>
public virtual gax::PagedEnumerable<ListBudgetsResponse, Budget> ListBudgets(ListBudgetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns a list of budgets for a billing account.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Budget"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListBudgetsResponse, Budget> ListBudgetsAsync(ListBudgetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a budget. Returns successfully if already deleted.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteBudget(DeleteBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a budget. Returns successfully if already deleted.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteBudgetAsync(DeleteBudgetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes a budget. Returns successfully if already deleted.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteBudgetAsync(DeleteBudgetRequest request, st::CancellationToken cancellationToken) =>
DeleteBudgetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>BudgetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// BudgetService stores Cloud Billing budgets, which define a
/// budget plan and rules to execute as we track spend against that plan.
/// </remarks>
public sealed partial class BudgetServiceClientImpl : BudgetServiceClient
{
private readonly gaxgrpc::ApiCall<CreateBudgetRequest, Budget> _callCreateBudget;
private readonly gaxgrpc::ApiCall<UpdateBudgetRequest, Budget> _callUpdateBudget;
private readonly gaxgrpc::ApiCall<GetBudgetRequest, Budget> _callGetBudget;
private readonly gaxgrpc::ApiCall<ListBudgetsRequest, ListBudgetsResponse> _callListBudgets;
private readonly gaxgrpc::ApiCall<DeleteBudgetRequest, wkt::Empty> _callDeleteBudget;
/// <summary>
/// Constructs a client wrapper for the BudgetService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="BudgetServiceSettings"/> used within this client.</param>
public BudgetServiceClientImpl(BudgetService.BudgetServiceClient grpcClient, BudgetServiceSettings settings)
{
GrpcClient = grpcClient;
BudgetServiceSettings effectiveSettings = settings ?? BudgetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateBudget = clientHelper.BuildApiCall<CreateBudgetRequest, Budget>(grpcClient.CreateBudgetAsync, grpcClient.CreateBudget, effectiveSettings.CreateBudgetSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateBudget);
Modify_CreateBudgetApiCall(ref _callCreateBudget);
_callUpdateBudget = clientHelper.BuildApiCall<UpdateBudgetRequest, Budget>(grpcClient.UpdateBudgetAsync, grpcClient.UpdateBudget, effectiveSettings.UpdateBudgetSettings).WithGoogleRequestParam("budget.name", request => request.Budget?.Name);
Modify_ApiCall(ref _callUpdateBudget);
Modify_UpdateBudgetApiCall(ref _callUpdateBudget);
_callGetBudget = clientHelper.BuildApiCall<GetBudgetRequest, Budget>(grpcClient.GetBudgetAsync, grpcClient.GetBudget, effectiveSettings.GetBudgetSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetBudget);
Modify_GetBudgetApiCall(ref _callGetBudget);
_callListBudgets = clientHelper.BuildApiCall<ListBudgetsRequest, ListBudgetsResponse>(grpcClient.ListBudgetsAsync, grpcClient.ListBudgets, effectiveSettings.ListBudgetsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListBudgets);
Modify_ListBudgetsApiCall(ref _callListBudgets);
_callDeleteBudget = clientHelper.BuildApiCall<DeleteBudgetRequest, wkt::Empty>(grpcClient.DeleteBudgetAsync, grpcClient.DeleteBudget, effectiveSettings.DeleteBudgetSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteBudget);
Modify_DeleteBudgetApiCall(ref _callDeleteBudget);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_CreateBudgetApiCall(ref gaxgrpc::ApiCall<CreateBudgetRequest, Budget> call);
partial void Modify_UpdateBudgetApiCall(ref gaxgrpc::ApiCall<UpdateBudgetRequest, Budget> call);
partial void Modify_GetBudgetApiCall(ref gaxgrpc::ApiCall<GetBudgetRequest, Budget> call);
partial void Modify_ListBudgetsApiCall(ref gaxgrpc::ApiCall<ListBudgetsRequest, ListBudgetsResponse> call);
partial void Modify_DeleteBudgetApiCall(ref gaxgrpc::ApiCall<DeleteBudgetRequest, wkt::Empty> call);
partial void OnConstruction(BudgetService.BudgetServiceClient grpcClient, BudgetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC BudgetService client</summary>
public override BudgetService.BudgetServiceClient GrpcClient { get; }
partial void Modify_CreateBudgetRequest(ref CreateBudgetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateBudgetRequest(ref UpdateBudgetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetBudgetRequest(ref GetBudgetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListBudgetsRequest(ref ListBudgetsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteBudgetRequest(ref DeleteBudgetRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates a new budget. See
/// [Quotas and limits](https://cloud.google.com/billing/quotas)
/// for more information on the limits of the number of budgets you can create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Budget CreateBudget(CreateBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateBudgetRequest(ref request, ref callSettings);
return _callCreateBudget.Sync(request, callSettings);
}
/// <summary>
/// Creates a new budget. See
/// [Quotas and limits](https://cloud.google.com/billing/quotas)
/// for more information on the limits of the number of budgets you can create.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Budget> CreateBudgetAsync(CreateBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateBudgetRequest(ref request, ref callSettings);
return _callCreateBudget.Async(request, callSettings);
}
/// <summary>
/// Updates a budget and returns the updated budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. Budget fields that are not exposed in
/// this API will not be changed by this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Budget UpdateBudget(UpdateBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateBudgetRequest(ref request, ref callSettings);
return _callUpdateBudget.Sync(request, callSettings);
}
/// <summary>
/// Updates a budget and returns the updated budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. Budget fields that are not exposed in
/// this API will not be changed by this method.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Budget> UpdateBudgetAsync(UpdateBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateBudgetRequest(ref request, ref callSettings);
return _callUpdateBudget.Async(request, callSettings);
}
/// <summary>
/// Returns a budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Budget GetBudget(GetBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetBudgetRequest(ref request, ref callSettings);
return _callGetBudget.Sync(request, callSettings);
}
/// <summary>
/// Returns a budget.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Budget> GetBudgetAsync(GetBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetBudgetRequest(ref request, ref callSettings);
return _callGetBudget.Async(request, callSettings);
}
/// <summary>
/// Returns a list of budgets for a billing account.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Budget"/> resources.</returns>
public override gax::PagedEnumerable<ListBudgetsResponse, Budget> ListBudgets(ListBudgetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListBudgetsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListBudgetsRequest, ListBudgetsResponse, Budget>(_callListBudgets, request, callSettings);
}
/// <summary>
/// Returns a list of budgets for a billing account.
///
/// WARNING: There are some fields exposed on the Google Cloud Console that
/// aren't available on this API. When reading from the API, you will not
/// see these fields in the return value, though they may have been set
/// in the Cloud Console.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Budget"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListBudgetsResponse, Budget> ListBudgetsAsync(ListBudgetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListBudgetsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListBudgetsRequest, ListBudgetsResponse, Budget>(_callListBudgets, request, callSettings);
}
/// <summary>
/// Deletes a budget. Returns successfully if already deleted.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override void DeleteBudget(DeleteBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteBudgetRequest(ref request, ref callSettings);
_callDeleteBudget.Sync(request, callSettings);
}
/// <summary>
/// Deletes a budget. Returns successfully if already deleted.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task DeleteBudgetAsync(DeleteBudgetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteBudgetRequest(ref request, ref callSettings);
return _callDeleteBudget.Async(request, callSettings);
}
}
public partial class ListBudgetsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListBudgetsResponse : gaxgrpc::IPageResponse<Budget>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Budget> GetEnumerator() => Budgets.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
/* ****************************************************************************
*
* 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
* dlr@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.
*
*
* ***************************************************************************/
#if FEATURE_NATIVE
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
using System.Numerics;
#else
using Microsoft.Scripting.Math;
#endif
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Modules {
/// <summary>
/// Provides support for interop with native code from Python code.
/// </summary>
public static partial class CTypes {
[PythonType("CFuncPtr")]
public abstract class _CFuncPtr : CData, IDynamicMetaObjectProvider, ICodeFormattable {
private readonly Delegate _delegate;
private readonly int _comInterfaceIndex = -1;
private object _errcheck, _restype = _noResType;
private IList<object> _argtypes;
private int _id;
private static int _curId = 0;
internal static object _noResType = new object();
// __bool__
/// <summary>
/// Creates a new CFuncPtr object from a tuple. The 1st element of the
/// tuple is the ordinal or function name. The second is an object with
/// a _handle property. The _handle property is the handle of the module
/// from which the function will be loaded.
/// </summary>
public _CFuncPtr(PythonTuple args) {
if (args == null) {
throw PythonOps.TypeError("expected sequence, got None");
} else if (args.Count != 2) {
throw PythonOps.TypeError("argument 1 must be a sequence of length 2, not {0}", args.Count);
}
object nameOrOrdinal = args[0];
object dll = args[1];
IntPtr intPtrHandle = GetHandleFromObject(dll, "the _handle attribute of the second element must be an integer");
IntPtr tmpAddr;
string funcName = args[0] as string;
if (funcName != null) {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, funcName);
} else {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, new IntPtr((int)nameOrOrdinal));
}
if (tmpAddr == IntPtr.Zero) {
if (CallingConvention == CallingConvention.StdCall && funcName != null) {
// apply std call name mangling - prepend a _, append @bytes where
// bytes is the number of bytes of the argument list.
string mangled = "_" + funcName + "@";
for (int i = 0; i < 128 && tmpAddr == IntPtr.Zero; i += 4) {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, mangled + i);
}
}
if (tmpAddr == IntPtr.Zero) {
throw PythonOps.AttributeError("function {0} is not defined", args[0]);
}
}
_memHolder = new MemoryHolder(IntPtr.Size);
addr = tmpAddr;
_id = Interlocked.Increment(ref _curId);
}
public _CFuncPtr() {
_id = Interlocked.Increment(ref _curId);
_memHolder = new MemoryHolder(IntPtr.Size);
}
public _CFuncPtr(CodeContext context, object function) {
_memHolder = new MemoryHolder(IntPtr.Size);
if (function != null) {
if (!PythonOps.IsCallable(context, function)) {
throw PythonOps.TypeError("argument must be called or address of function");
}
_delegate = ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).MakeReverseDelegate(context, function);
addr = Marshal.GetFunctionPointerForDelegate(_delegate);
CFuncPtrType myType = (CFuncPtrType)NativeType;
PythonType resType = myType._restype;
if (resType != null) {
if (!(resType is INativeType) || resType is PointerType) {
throw PythonOps.TypeError("invalid result type {0} for callback function", ((PythonType)resType).Name);
}
}
}
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr which calls a COM method.
/// </summary>
public _CFuncPtr(int index, string name) {
_memHolder = new MemoryHolder(IntPtr.Size);
_comInterfaceIndex = index;
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr with the specfied address.
/// </summary>
public _CFuncPtr(int handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = new IntPtr(handle);
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr with the specfied address.
/// </summary>
public _CFuncPtr([NotNull]BigInteger handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = new IntPtr((long)handle);
_id = Interlocked.Increment(ref _curId);
}
public _CFuncPtr(IntPtr handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = handle;
_id = Interlocked.Increment(ref _curId);
}
public bool __bool__() {
return addr != IntPtr.Zero;
}
#region Public APIs
[SpecialName, PropertyMethod]
public object Geterrcheck() {
return _errcheck;
}
[SpecialName, PropertyMethod]
public void Seterrcheck(object value) {
_errcheck = value;
}
[SpecialName, PropertyMethod]
public void Deleteerrcheck() {
_errcheck = null;
_id = Interlocked.Increment(ref _curId);
}
[PropertyMethod, SpecialName]
public object Getrestype() {
if (_restype == _noResType) {
return ((CFuncPtrType)NativeType)._restype;
}
return _restype;
}
[PropertyMethod, SpecialName]
public void Setrestype(object value) {
INativeType nt = value as INativeType;
if (nt != null || value == null || PythonOps.IsCallable(((PythonType)NativeType).Context.SharedContext, value)) {
_restype = value;
_id = Interlocked.Increment(ref _curId);
} else {
throw PythonOps.TypeError("restype must be a type, a callable, or None");
}
}
[SpecialName, PropertyMethod]
public void Deleterestype() {
_restype = _noResType;
_id = Interlocked.Increment(ref _curId);
}
public object argtypes {
get {
if (_argtypes != null) {
return _argtypes;
}
if (((CFuncPtrType)NativeType)._argtypes != null) {
return PythonTuple.MakeTuple(((CFuncPtrType)NativeType)._argtypes);
}
return null;
}
set {
if (value != null) {
IList<object> argValues = value as IList<object>;
if (argValues == null) {
throw PythonOps.TypeErrorForTypeMismatch("sequence", value);
}
foreach (object o in argValues) {
if (!(o is INativeType)) {
if (!PythonOps.HasAttr(DefaultContext.Default, o, "from_param")) {
throw PythonOps.TypeErrorForTypeMismatch("ctype or object with from_param", o);
}
}
}
_argtypes = argValues;
} else {
_argtypes = null;
}
_id = Interlocked.Increment(ref _curId);
}
}
#endregion
#region Internal APIs
internal CallingConvention CallingConvention {
get {
return ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).CallingConvention;
}
}
// TODO: access via PythonOps
public IntPtr addr {
[PythonHidden]
get {
return _memHolder.ReadIntPtr(0);
}
[PythonHidden]
set {
_memHolder.WriteIntPtr(0, value);
}
}
internal int Id {
get {
return _id;
}
}
#endregion
#region IDynamicObject Members
// needs to be public so that derived base classes can call it.
[PythonHidden]
public DynamicMetaObject GetMetaObject(Expression parameter) {
return new Meta(parameter, this);
}
#endregion
#region MetaObject
private class Meta : MetaPythonObject {
public Meta(Expression parameter, _CFuncPtr func)
: base(parameter, BindingRestrictions.Empty, func) {
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) {
CodeContext context = PythonContext.GetPythonContext(binder).SharedContext;
ArgumentMarshaller[] signature = GetArgumentMarshallers(args);
BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction(
Expression,
Value.GetType()
).Merge(
BindingRestrictions.GetExpressionRestriction(
Expression.Call(
typeof(ModuleOps).GetMethod("CheckFunctionId"),
Expression.Convert(Expression, typeof(_CFuncPtr)),
Expression.Constant(Value.Id)
)
)
);
foreach (var arg in signature) {
restrictions = restrictions.Merge(arg.GetRestrictions());
}
int argCount = args.Length;
if (Value._comInterfaceIndex != -1) {
argCount--;
}
// need to verify we have the correct # of args
if (Value._argtypes != null) {
if (argCount < Value._argtypes.Count || (Value.CallingConvention != CallingConvention.Cdecl && argCount > Value._argtypes.Count)) {
return IncorrectArgCount(binder, restrictions, Value._argtypes.Count, argCount);
}
} else {
CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType);
if (funcType._argtypes != null &&
(argCount < funcType._argtypes.Length || (Value.CallingConvention != CallingConvention.Cdecl && argCount > funcType._argtypes.Length))) {
return IncorrectArgCount(binder, restrictions, funcType._argtypes.Length, argCount);
}
}
if (Value._comInterfaceIndex != -1 && args.Length == 0) {
return NoThisParam(binder, restrictions);
}
Expression call = MakeCall(signature, GetNativeReturnType(), Value.Getrestype() == null, GetFunctionAddress(args));
List<Expression> block = new List<Expression>();
Expression res;
if (call.Type != typeof(void)) {
ParameterExpression tmp = Expression.Parameter(call.Type, "ret");
block.Add(Expression.Assign(tmp, call));
AddKeepAlives(signature, block);
block.Add(tmp);
res = Expression.Block(new[] { tmp }, block);
} else {
block.Add(call);
AddKeepAlives(signature, block);
res = Expression.Block(block);
}
res = AddReturnChecks(context, args, res);
return new DynamicMetaObject(Utils.Convert(res, typeof(object)), restrictions);
}
private Expression AddReturnChecks(CodeContext context, DynamicMetaObject[] args, Expression res) {
PythonContext ctx = PythonContext.GetContext(context);
object resType = Value.Getrestype();
if (resType != null) {
// res type can be callable, a type with _check_retval_, or
// it can be just be a type which doesn't require post-processing.
INativeType nativeResType = resType as INativeType;
object checkRetVal = null;
if (nativeResType == null) {
checkRetVal = resType;
} else if (!PythonOps.TryGetBoundAttr(context, nativeResType, "_check_retval_", out checkRetVal)) {
// we just wanted to try and get the value, don't need to do anything here.
checkRetVal = null;
}
if (checkRetVal != null) {
res = Expression.Dynamic(
ctx.CompatInvoke(new CallInfo(1)),
typeof(object),
Expression.Constant(checkRetVal),
res
);
}
}
object errCheck = Value.Geterrcheck();
if (errCheck != null) {
res = Expression.Dynamic(
ctx.CompatInvoke(new CallInfo(3)),
typeof(object),
Expression.Constant(errCheck),
res,
Expression,
Expression.Call(
typeof(PythonOps).GetMethod("MakeTuple"),
Expression.NewArrayInit(
typeof(object),
ArrayUtils.ConvertAll(args, x => Utils.Convert(x.Expression, typeof(object)))
)
)
);
}
return res;
}
private static DynamicMetaObject IncorrectArgCount(DynamicMetaObjectBinder binder, BindingRestrictions restrictions, int expected, int got) {
return new DynamicMetaObject(
binder.Throw(
Expression.Call(
typeof(PythonOps).GetMethod("TypeError"),
Expression.Constant(String.Format("this function takes {0} arguments ({1} given)", expected, got)),
Expression.NewArrayInit(typeof(object))
),
typeof(object)
),
restrictions
);
}
private static DynamicMetaObject NoThisParam(DynamicMetaObjectBinder binder, BindingRestrictions restrictions) {
return new DynamicMetaObject(
binder.Throw(
Expression.Call(
typeof(PythonOps).GetMethod("ValueError"),
Expression.Constant("native com method call without 'this' parameter"),
Expression.NewArrayInit(typeof(object))
),
typeof(object)
),
restrictions
);
}
/// <summary>
/// we need to keep alive any methods which have arguments for the duration of the
/// call. Otherwise they could be collected on the finalizer thread before we come back.
/// </summary>
private void AddKeepAlives(ArgumentMarshaller[] signature, List<Expression> block) {
foreach (ArgumentMarshaller marshaller in signature) {
Expression keepAlive = marshaller.GetKeepAlive();
if (keepAlive != null) {
block.Add(keepAlive);
}
}
}
private Expression MakeCall(ArgumentMarshaller[] signature, INativeType nativeRetType, bool retVoid, Expression address) {
List<object> constantPool = new List<object>();
MethodInfo interopInvoker = CreateInteropInvoker(
GetCallingConvention(),
signature,
nativeRetType,
retVoid,
constantPool
);
// build the args - IntPtr, user Args, constant pool
Expression[] callArgs = new Expression[signature.Length + 2];
callArgs[0] = address;
for (int i = 0; i < signature.Length; i++) {
callArgs[i + 1] = signature[i].ArgumentExpression;
}
callArgs[callArgs.Length - 1] = Expression.Constant(constantPool.ToArray());
return Expression.Call(interopInvoker, callArgs);
}
private Expression GetFunctionAddress(DynamicMetaObject[] args) {
Expression address;
if (Value._comInterfaceIndex != -1) {
Debug.Assert(args.Length != 0); // checked earlier
address = Expression.Call(
typeof(ModuleOps).GetMethod("GetInterfacePointer"),
Expression.Call(
typeof(ModuleOps).GetMethod("GetPointer"),
args[0].Expression
),
Expression.Constant(Value._comInterfaceIndex)
);
} else {
address = Expression.Property(
Expression.Convert(Expression, typeof(_CFuncPtr)),
"addr"
);
}
return address;
}
private CallingConvention GetCallingConvention() {
return Value.CallingConvention;
}
private INativeType GetNativeReturnType() {
return Value.Getrestype() as INativeType;
}
private ArgumentMarshaller/*!*/[]/*!*/ GetArgumentMarshallers(DynamicMetaObject/*!*/[]/*!*/ args) {
CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType);
ArgumentMarshaller[] res = new ArgumentMarshaller[args.Length];
// first arg is taken by self if we're a com method
for (int i = 0; i < args.Length; i++) {
DynamicMetaObject mo = args[i];
object argType = null;
if (Value._comInterfaceIndex == -1 || i != 0) {
int argtypeIndex = Value._comInterfaceIndex == -1 ? i : i - 1;
if (Value._argtypes != null && argtypeIndex < Value._argtypes.Count) {
argType = Value._argtypes[argtypeIndex];
} else if (funcType._argtypes != null && argtypeIndex < funcType._argtypes.Length) {
argType = funcType._argtypes[argtypeIndex];
}
}
res[i] = GetMarshaller(mo.Expression, mo.Value, i, argType);
}
return res;
}
private ArgumentMarshaller/*!*/ GetMarshaller(Expression/*!*/ expr, object value, int index, object nativeType) {
if (nativeType != null) {
INativeType nt = nativeType as INativeType;
if (nt != null) {
return new CDataMarshaller(expr, CompilerHelpers.GetType(value), nt);
}
return new FromParamMarshaller(expr);
}
CData data = value as CData;
if (data != null) {
return new CDataMarshaller(expr, CompilerHelpers.GetType(value), data.NativeType);
}
NativeArgument arg = value as NativeArgument;
if (arg != null) {
return new NativeArgumentMarshaller(expr);
}
object val;
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out val)) {
throw new NotImplementedException("_as_parameter");
//return new UserDefinedMarshaller(GetMarshaller(..., value, index));
}
// Marshalling primitive or an object
return new PrimitiveMarshaller(expr, CompilerHelpers.GetType(value));
}
public new _CFuncPtr/*!*/ Value {
get {
return (_CFuncPtr)base.Value;
}
}
/// <summary>
/// Creates a method for calling with the specified signature. The returned method has a signature
/// of the form:
///
/// (IntPtr funcAddress, arg0, arg1, ..., object[] constantPool)
///
/// where IntPtr is the address of the function to be called. The arguments types are based upon
/// the types that the ArgumentMarshaller requires.
/// </summary>
private static MethodInfo/*!*/ CreateInteropInvoker(CallingConvention convention, ArgumentMarshaller/*!*/[]/*!*/ sig, INativeType nativeRetType, bool retVoid, List<object> constantPool) {
Type[] sigTypes = new Type[sig.Length + 2];
sigTypes[0] = typeof(IntPtr);
for (int i = 0; i < sig.Length; i++) {
sigTypes[i + 1] = sig[i].ArgumentExpression.Type;
}
sigTypes[sigTypes.Length - 1] = typeof(object[]);
Type retType = retVoid ? typeof(void) :
nativeRetType != null ? nativeRetType.GetPythonType() : typeof(int);
Type calliRetType = retVoid ? typeof(void) :
nativeRetType != null ? nativeRetType.GetNativeType() : typeof(int);
#if !CTYPES_USE_SNIPPETS
DynamicMethod dm = new DynamicMethod("InteropInvoker", retType, sigTypes, DynamicModule);
#else
TypeGen tg = Snippets.Shared.DefineType("InteropInvoker", typeof(object), false, false);
MethodBuilder dm = tg.TypeBuilder.DefineMethod("InteropInvoker", CompilerHelpers.PublicStatic, retType, sigTypes);
#endif
ILGenerator method = dm.GetILGenerator();
LocalBuilder calliRetTmp = null, finalRetValue = null;
if (dm.ReturnType != typeof(void)) {
calliRetTmp = method.DeclareLocal(calliRetType);
finalRetValue = method.DeclareLocal(dm.ReturnType);
}
// try {
// emit all of the arguments, save their cleanups
method.BeginExceptionBlock();
List<MarshalCleanup> cleanups = null;
for (int i = 0; i < sig.Length; i++) {
#if DEBUG
method.Emit(OpCodes.Ldstr, String.Format("Argument #{0}, Marshaller: {1}, Native Type: {2}", i, sig[i], sig[i].NativeType));
method.Emit(OpCodes.Pop);
#endif
MarshalCleanup cleanup = sig[i].EmitCallStubArgument(method, i + 1, constantPool, sigTypes.Length - 1);
if (cleanup != null) {
if (cleanups == null) {
cleanups = new List<MarshalCleanup>();
}
cleanups.Add(cleanup);
}
}
// emit the target function pointer and the calli
#if DEBUG
method.Emit(OpCodes.Ldstr, "!!! CALLI !!!");
method.Emit(OpCodes.Pop);
#endif
method.Emit(OpCodes.Ldarg_0);
method.Emit(OpCodes.Calli, GetCalliSignature(convention, sig, calliRetType));
// if we have a return value we need to store it and marshal to Python
// before we run any cleanup code.
if (retType != typeof(void)) {
#if DEBUG
method.Emit(OpCodes.Ldstr, "!!! Return !!!");
method.Emit(OpCodes.Pop);
#endif
if (nativeRetType != null) {
method.Emit(OpCodes.Stloc, calliRetTmp);
nativeRetType.EmitReverseMarshalling(method, new Local(calliRetTmp), constantPool, sig.Length + 1);
method.Emit(OpCodes.Stloc, finalRetValue);
} else {
Debug.Assert(retType == typeof(int));
// no marshalling necessary
method.Emit(OpCodes.Stloc, finalRetValue);
}
}
// } finally {
// emit the cleanup code
method.BeginFinallyBlock();
if (cleanups != null) {
foreach (MarshalCleanup mc in cleanups) {
mc.Cleanup(method);
}
}
method.EndExceptionBlock();
// }
// load the temporary value and return it.
if (retType != typeof(void)) {
method.Emit(OpCodes.Ldloc, finalRetValue);
}
method.Emit(OpCodes.Ret);
#if CTYPES_USE_SNIPPETS
return tg.TypeBuilder.CreateType().GetMethod("InteropInvoker");
#else
return dm;
#endif
}
private static SignatureHelper GetCalliSignature(CallingConvention convention, ArgumentMarshaller/*!*/[] sig, Type calliRetType) {
SignatureHelper signature = SignatureHelper.GetMethodSigHelper(convention, calliRetType);
foreach (ArgumentMarshaller argMarshaller in sig) {
signature.AddArgument(argMarshaller.NativeType);
}
return signature;
}
#region Argument Marshalling
/// <summary>
/// Base class for marshalling arguments from the user provided value to the
/// call stub. This class provides the logic for creating the call stub and
/// calling it.
/// </summary>
abstract class ArgumentMarshaller {
private readonly Expression/*!*/ _argExpr;
public ArgumentMarshaller(Expression/*!*/ container) {
_argExpr = container;
}
/// <summary>
/// Emits the IL to get the argument for the call stub generated into
/// a dynamic method.
/// </summary>
public abstract MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument);
public abstract Type/*!*/ NativeType {
get;
}
/// <summary>
/// Gets the expression used to provide the argument. This is the expression
/// from an incoming DynamicMetaObject.
/// </summary>
public Expression/*!*/ ArgumentExpression {
get {
return _argExpr;
}
}
/// <summary>
/// Gets an expression which keeps alive the argument for the duration of the call.
///
/// Returns null if a keep alive is not necessary.
/// </summary>
public virtual Expression GetKeepAlive() {
return null;
}
public virtual BindingRestrictions GetRestrictions() {
return BindingRestrictions.Empty;
}
}
/// <summary>
/// Provides marshalling of primitive values when the function type
/// has no type information or when the user has provided us with
/// an explicit cdata instance.
/// </summary>
class PrimitiveMarshaller : ArgumentMarshaller {
private readonly Type/*!*/ _type;
private static MethodInfo _bigIntToInt32;
private static MethodInfo BigIntToInt32 {
get {
if (_bigIntToInt32 == null) {
#if CLR2
_bigIntToInt32 = typeof(BigInteger).GetMethod("ToInt32", ReflectionUtils.EmptyTypes);
#else
MemberInfo[] mis = typeof(BigInteger).GetMember(
"op_Explicit",
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static
);
foreach (MethodInfo mi in mis) {
if (mi.ReturnType == typeof(int)) {
_bigIntToInt32 = mi;
break;
}
}
Debug.Assert(_bigIntToInt32 != null);
#endif
}
return _bigIntToInt32;
}
}
public PrimitiveMarshaller(Expression/*!*/ container, Type/*!*/ type)
: base(container) {
_type = type;
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
if (_type == typeof(DynamicNull)) {
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Conv_I);
return null;
}
generator.Emit(OpCodes.Ldarg, argIndex);
if (ArgumentExpression.Type != _type) {
generator.Emit(OpCodes.Unbox_Any, _type);
}
if (_type == typeof(string)) {
// pin the string and convert to a wchar*. We could let the CLR do this
// but we need the string to be pinned longer than the duration of the the CLR's
// p/invoke. This is because the function could return the same pointer back
// to us and we need to create a new string from it.
LocalBuilder lb = generator.DeclareLocal(typeof(string), true);
generator.Emit(OpCodes.Stloc, lb);
generator.Emit(OpCodes.Ldloc, lb);
generator.Emit(OpCodes.Conv_I);
generator.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData);
generator.Emit(OpCodes.Add);
} else if (_type == typeof(Bytes)) {
LocalBuilder lb = generator.DeclareLocal(typeof(byte).MakeByRefType(), true);
generator.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("GetBytes"));
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Ldelema, typeof(Byte));
generator.Emit(OpCodes.Stloc, lb);
generator.Emit(OpCodes.Ldloc, lb);
} else if (_type == typeof(BigInteger)) {
generator.Emit(OpCodes.Call, BigIntToInt32);
} else if (!_type.IsValueType) {
generator.Emit(OpCodes.Call, typeof(CTypes).GetMethod("PyObj_ToPtr"));
}
return null;
}
public override Type NativeType {
get {
if (_type == typeof(BigInteger)) {
return typeof(int);
} else if (!_type.IsValueType) {
return typeof(IntPtr);
}
return _type;
}
}
public override BindingRestrictions GetRestrictions() {
if (_type == typeof(DynamicNull)) {
return BindingRestrictions.GetExpressionRestriction(Expression.Equal(ArgumentExpression, Expression.Constant(null)));
}
return BindingRestrictions.GetTypeRestriction(ArgumentExpression, _type);
}
}
class FromParamMarshaller : ArgumentMarshaller {
public FromParamMarshaller(Expression/*!*/ container)
: base(container) {
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator generator, int argIndex, List<object> constantPool, int constantPoolArgument) {
throw new NotImplementedException();
}
public override Type NativeType {
get { throw new NotImplementedException(); }
}
}
/// <summary>
/// Provides marshalling for when the function type provide argument information.
/// </summary>
class CDataMarshaller : ArgumentMarshaller {
private readonly Type/*!*/ _type;
private readonly INativeType/*!*/ _cdataType;
public CDataMarshaller(Expression/*!*/ container, Type/*!*/ type, INativeType/*!*/cdataType)
: base(container) {
_type = type;
_cdataType = cdataType;
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
return _cdataType.EmitMarshalling(generator, new Arg(argIndex, ArgumentExpression.Type), constantPool, constantPoolArgument);
}
public override Type NativeType {
get {
return _cdataType.GetNativeType();
}
}
public override Expression GetKeepAlive() {
// Future possible optimization - we could just keep alive the MemoryHolder
if (_type.IsValueType) {
return null;
}
return Expression.Call(
typeof(GC).GetMethod("KeepAlive"),
ArgumentExpression
);
}
public override BindingRestrictions GetRestrictions() {
// we base this off of the type marshalling which can handle anything.
return BindingRestrictions.Empty;
}
}
/// <summary>
/// Provides marshalling for when the user provides a native argument object
/// (usually gotten by byref or pointer) and the function type has no type information.
/// </summary>
class NativeArgumentMarshaller : ArgumentMarshaller {
public NativeArgumentMarshaller(Expression/*!*/ container)
: base(container) {
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
// We access UnsafeAddress here but ensure the object is kept
// alive via the expression returned in GetKeepAlive.
generator.Emit(OpCodes.Ldarg, argIndex);
generator.Emit(OpCodes.Castclass, typeof(NativeArgument));
generator.Emit(OpCodes.Call, typeof(NativeArgument).GetMethod("get__obj"));
generator.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress"));
return null;
}
public override Type/*!*/ NativeType {
get {
return typeof(IntPtr);
}
}
public override Expression GetKeepAlive() {
// Future possible optimization - we could just keep alive the MemoryHolder
return Expression.Call(
typeof(GC).GetMethod("KeepAlive"),
ArgumentExpression
);
}
public override BindingRestrictions GetRestrictions() {
return BindingRestrictions.GetTypeRestriction(ArgumentExpression, typeof(NativeArgument));
}
}
#if FALSE // TODO: not implemented yet
/// <summary>
/// Provides the marshalling for a user defined object which has an _as_parameter_
/// value.
/// </summary>
class UserDefinedMarshaller : ArgumentMarshaller {
private readonly ArgumentMarshaller/*!*/ _marshaller;
public UserDefinedMarshaller(Expression/*!*/ container, ArgumentMarshaller/*!*/ marshaller)
: base(container) {
_marshaller = marshaller;
}
public override Type NativeType {
get { throw new NotImplementedException("user defined marshaller sig type"); }
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
throw new NotImplementedException("user defined marshaller");
}
}
#endif
#endregion
}
#endregion
public string __repr__(CodeContext context) {
if (_comInterfaceIndex != -1) {
return string.Format("<COM method offset {0}: {1} at {2}>", _comInterfaceIndex, DynamicHelpers.GetPythonType(this).Name, _id);
}
return ObjectOps.__repr__(this);
}
}
}
}
#endif
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Xml;
#endregion
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only
/// way of generating streams or files containing JSON Text according
/// to the grammar rules laid out in
/// <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>.
/// </summary>
/// <remarks>
/// This class supports ELMAH and is not intended to be used directly
/// from your code. It may be modified or removed in the future without
/// notice. It has public accessibility for testing purposes. If you
/// need a general-purpose JSON Text encoder, consult
/// <a href="http://www.json.org/">JSON.org</a> for implementations
/// or use classes available from the Microsoft .NET Framework.
/// </remarks>
public sealed class JsonTextWriter
{
private readonly TextWriter _writer;
private readonly int[] _counters;
private readonly char[] _terminators;
private int _depth;
private string _memberName;
public JsonTextWriter(TextWriter writer)
{
Debug.Assert(writer != null);
_writer = writer;
const int levels = 10 + /* root */ 1;
_counters = new int[levels];
_terminators = new char[levels];
}
public int Depth
{
get { return _depth; }
}
private int ItemCount
{
get { return _counters[Depth]; }
set { _counters[Depth] = value; }
}
private char Terminator
{
get { return _terminators[Depth]; }
set { _terminators[Depth] = value; }
}
public JsonTextWriter Object()
{
return StartStructured("{", "}");
}
public JsonTextWriter EndObject()
{
return Pop();
}
public JsonTextWriter Array()
{
return StartStructured("[", "]");
}
public JsonTextWriter EndArray()
{
return Pop();
}
public JsonTextWriter Pop()
{
return EndStructured();
}
public JsonTextWriter Member(string name)
{
if (name == null) throw new ArgumentNullException("name");
if (name.Length == 0) throw new ArgumentException(null, "name");
if (_memberName != null) throw new InvalidOperationException("Missing member value.");
_memberName = name;
return this;
}
private JsonTextWriter Write(string text)
{
return WriteImpl(text, /* raw */ false);
}
private JsonTextWriter WriteEnquoted(string text)
{
return WriteImpl(text, /* raw */ true);
}
private JsonTextWriter WriteImpl(string text, bool raw)
{
Debug.Assert(raw || (text != null && text.Length > 0));
if (Depth == 0 && (text.Length > 1 || (text[0] != '{' && text[0] != '[')))
throw new InvalidOperationException();
TextWriter writer = _writer;
if (ItemCount > 0)
writer.Write(',');
string name = _memberName;
_memberName = null;
if (name != null)
{
writer.Write(' ');
Enquote(name, writer);
writer.Write(':');
}
if (Depth > 0)
writer.Write(' ');
if (raw)
Enquote(text, writer);
else
writer.Write(text);
ItemCount = ItemCount + 1;
return this;
}
public JsonTextWriter Number(int value)
{
return Write(value.ToString(CultureInfo.InvariantCulture));
}
public JsonTextWriter String(string str)
{
return str == null ? Null() : WriteEnquoted(str);
}
public JsonTextWriter Null()
{
return Write("null");
}
public JsonTextWriter Boolean(bool value)
{
return Write(value ? "true" : "false");
}
private static readonly DateTime _epoch = /* ... */
#if NET_1_0 || NET_1_1
/* ... */ new DateTime(1970, 1, 1, 0, 0, 0);
#else
/* ... */ new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
#endif
public JsonTextWriter Number(DateTime time)
{
double seconds = time.ToUniversalTime().Subtract(_epoch).TotalSeconds;
return Write(seconds.ToString(CultureInfo.InvariantCulture));
}
public JsonTextWriter String(DateTime time)
{
string xmlTime;
#if NET_1_0 || NET_1_1
xmlTime = XmlConvert.ToString(time);
#else
xmlTime = XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc);
#endif
return String(xmlTime);
}
private JsonTextWriter StartStructured(string start, string end)
{
if (Depth + 1 == _counters.Length)
throw new Exception();
Write(start);
_depth++;
Terminator = end[0];
return this;
}
private JsonTextWriter EndStructured()
{
if (Depth - 1 < 0)
throw new Exception();
_writer.Write(' ');
_writer.Write(Terminator);
ItemCount = 0;
_depth--;
return this;
}
private static void Enquote(string s, TextWriter writer)
{
Debug.Assert(writer != null);
int length = Mask.NullString(s).Length;
writer.Write('"');
char last;
char ch = '\0';
for (int index = 0; index < length; index++)
{
last = ch;
ch = s[index];
switch (ch)
{
case '\\':
case '"':
{
writer.Write('\\');
writer.Write(ch);
break;
}
case '/':
{
if (last == '<')
writer.Write('\\');
writer.Write(ch);
break;
}
case '\b': writer.Write("\\b"); break;
case '\t': writer.Write("\\t"); break;
case '\n': writer.Write("\\n"); break;
case '\f': writer.Write("\\f"); break;
case '\r': writer.Write("\\r"); break;
default:
{
if (ch < ' ')
{
writer.Write("\\u");
writer.Write(((int)ch).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
writer.Write(ch);
}
break;
}
}
}
writer.Write('"');
}
}
}
| |
// 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 Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd;
namespace Microsoft.Protocols.TestSuites.FileSharing.RSVD.TestSuite
{
/// <summary>
/// Test Base for all RSVD test cases
/// </summary>
public abstract class RSVDTestBase : CommonTestBase
{
#region Variables
/// <summary>
/// Default Rsvd client
/// The instance is created when the test case is initialized
/// </summary>
protected RsvdClient client;
/// <summary>
/// Suffix of the .vhdx file name
/// </summary>
protected const string fileNameSuffix = ":SharedVirtualDisk";
#endregion
public RSVDTestConfig TestConfig
{
get
{
return testConfig as RSVDTestConfig;
}
}
protected override void TestInitialize()
{
base.TestInitialize();
testConfig = new RSVDTestConfig(BaseTestSite);
BaseTestSite.DefaultProtocolDocShortName = "MS-RSVD";
client = new RsvdClient(TestConfig.Timeout);
}
protected override void TestCleanup()
{
try
{
client.Disconnect();
}
catch (Exception ex)
{
BaseTestSite.Log.Add(LogEntryKind.Debug, "Unexpected exception when disconnect client: {0}", ex.ToString());
}
client.Dispose();
base.TestCleanup();
}
/// <summary>
/// Open the shared virtual disk file.
/// </summary>
/// <param name="fileName">The virtual disk file name to be used</param>
/// <param name="requestId">OpenRequestId, same with other operations' request id</param>
/// <param name="hasInitiatorId">If the SVHDX_OPEN_DEVICE_CONTEXT contains InitiatorId</param>
/// <param name="rsvdClient">The instance of rsvd client. NULL stands for the default client</param>
public void OpenSharedVHD(string fileName, ulong? requestId = null, bool hasInitiatorId = true, RsvdClient rsvdClient = null)
{
if (rsvdClient == null)
rsvdClient = this.client;
rsvdClient.Connect(
TestConfig.FileServerNameContainingSharedVHD,
TestConfig.FileServerIPContainingSharedVHD,
TestConfig.DomainName,
TestConfig.UserName,
TestConfig.UserPassword,
TestConfig.DefaultSecurityPackage,
TestConfig.UseServerGssToken,
TestConfig.ShareContainingSharedVHD);
Smb2CreateContextRequest[] contexts = null;
if (TestConfig.ServerServiceVersion == (uint)0x00000001)
{
contexts = new Smb2CreateContextRequest[]
{
new Smb2CreateSvhdxOpenDeviceContext
{
Version = TestConfig.ServerServiceVersion,
OriginatorFlags = (uint)OriginatorFlag.SVHDX_ORIGINATOR_PVHDPARSER,
InitiatorHostName = TestConfig.InitiatorHostName,
InitiatorHostNameLength = (ushort)(TestConfig.InitiatorHostName.Length * 2),
OpenRequestId = requestId == null ? ((ulong)new System.Random().Next()) : requestId.Value,
InitiatorId = hasInitiatorId ? Guid.NewGuid():Guid.Empty,
HasInitiatorId = hasInitiatorId
}
};
}
else if(TestConfig.ServerServiceVersion == (uint)0x00000002)
{
contexts = new Smb2CreateContextRequest[]
{
new Smb2CreateSvhdxOpenDeviceContextV2
{
Version = TestConfig.ServerServiceVersion,
OriginatorFlags = (uint)OriginatorFlag.SVHDX_ORIGINATOR_PVHDPARSER,
InitiatorHostName = TestConfig.InitiatorHostName,
InitiatorHostNameLength = (ushort)(TestConfig.InitiatorHostName.Length * 2),
OpenRequestId = requestId == null ? ((ulong)new System.Random().Next()) : requestId.Value,
InitiatorId = hasInitiatorId ? Guid.NewGuid():Guid.Empty,
HasInitiatorId = hasInitiatorId,
VirtualDiskPropertiesInitialized = 0,
ServerServiceVersion = 0,
VirtualSize = 0,
PhysicalSectorSize = 0,
VirtualSectorSize = 0
}
};
}
else
{
throw new ArgumentException("The ServerServiceVersion {0} is not supported.", "Version");
}
CREATE_Response response;
Smb2CreateContextResponse[] serverContextResponse;
uint status = rsvdClient.OpenSharedVirtualDisk(
fileName + fileNameSuffix,
FsCreateOption.FILE_NO_INTERMEDIATE_BUFFERING,
contexts,
out serverContextResponse,
out response);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Open shared virtual disk file should succeed, actual status: {0}",
GetStatus(status));
}
/// <summary>
/// Create snapshot for the VHD set file
/// </summary>
/// <param name="requestId">Tunnel operation request id</param>
/// <param name="rsvdClient">The instance of rsvd client. NULL stands for the default client</param>
/// <returns>Return a snapshot id</returns>
public Guid CreateSnapshot(ref ulong requestId, RsvdClient rsvdClient = null)
{
if (rsvdClient == null)
{
rsvdClient = this.client;
}
SVHDX_META_OPERATION_START_REQUEST startRequest = new SVHDX_META_OPERATION_START_REQUEST();
startRequest.TransactionId = System.Guid.NewGuid();
startRequest.OperationType = Operation_Type.SvhdxMetaOperationTypeCreateSnapshot;
startRequest.Padding = new byte[4];
SVHDX_META_OPERATION_CREATE_SNAPSHOT createsnapshot = new SVHDX_META_OPERATION_CREATE_SNAPSHOT();
createsnapshot.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM;
createsnapshot.Flags = Snapshot_Flags.SVHDX_SNAPSHOT_DISK_FLAG_ENABLE_CHANGE_TRACKING;
createsnapshot.Stage1 = Stage_Values.SvhdxSnapshotStageInitialize;
createsnapshot.Stage2 = Stage_Values.SvhdxSnapshotStageInvalid;
createsnapshot.Stage3 = Stage_Values.SvhdxSnapshotStageInvalid;
createsnapshot.Stage4 = Stage_Values.SvhdxSnapshotStageInvalid;
createsnapshot.Stage5 = Stage_Values.SvhdxSnapshotStageInvalid;
createsnapshot.Stage6 = Stage_Values.SvhdxSnapshotStageInvalid;
createsnapshot.SnapshotId = System.Guid.NewGuid();
createsnapshot.ParametersPayloadSize = (uint)0x00000000;
createsnapshot.Padding = new byte[24];
byte[] payload = rsvdClient.CreateTunnelMetaOperationStartCreateSnapshotRequest(
startRequest,
createsnapshot);
SVHDX_TUNNEL_OPERATION_HEADER? header;
SVHDX_TUNNEL_OPERATION_HEADER? response;
//For RSVD_TUNNEL_META_OPERATION_START operation code, the IOCTL code should be FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST
uint status = rsvdClient.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>(
true,
RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START,
requestId++,
payload,
out header,
out response);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Ioctl should succeed, actual status: {0}",
GetStatus(status));
createsnapshot.Flags = Snapshot_Flags.SVHDX_SNAPSHOT_FLAG_ZERO;
createsnapshot.Stage1 = Stage_Values.SvhdxSnapshotStageBlockIO;
createsnapshot.Stage2 = Stage_Values.SvhdxSnapshotStageSwitchObjectStore;
createsnapshot.Stage3 = Stage_Values.SvhdxSnapshotStageUnblockIO;
createsnapshot.Stage4 = Stage_Values.SvhdxSnapshotStageFinalize;
createsnapshot.Stage5 = Stage_Values.SvhdxSnapshotStageInvalid;
createsnapshot.Stage6 = Stage_Values.SvhdxSnapshotStageInvalid;
payload = rsvdClient.CreateTunnelMetaOperationStartCreateSnapshotRequest(
startRequest,
createsnapshot);
//For RSVD_TUNNEL_META_OPERATION_START operation code, the IOCTL code should be FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST
status = rsvdClient.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>(
true,
RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START,
requestId++,
payload,
out header,
out response);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Ioctl should succeed, actual status: {0}",
GetStatus(status));
SetFile_InformationType setFileInforType = SetFile_InformationType.SvhdxSetFileInformationTypeSnapshotEntry;
Snapshot_Type snapshotType = Snapshot_Type.SvhdxSnapshotTypeVM;
SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_SNAPSHOT_ENTRY_RESPONSE? snapshotEntryResponse;
payload = client.CreateTunnelGetVHDSetFileInfoRequest(
setFileInforType,
snapshotType,
createsnapshot.SnapshotId);
status = client.TunnelOperation<SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_SNAPSHOT_ENTRY_RESPONSE>(
false,//true for Async operation, false for non-async operation
RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_VHDSET_QUERY_INFORMATION,
requestId++,
payload,
out header,
out snapshotEntryResponse);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Ioctl should succeed, actual status: {0}",
GetStatus(status));
return createsnapshot.SnapshotId;
}
/// <summary>
/// Delete the existing snapshots for the VHD set file
/// </summary>
/// <param name="requestId">Tunnel operation request id</param>
/// <param name="snapshotId">The snapshot id to be deleted</param>
/// <param name="rsvdClient">The instance of rsvd client. NULL stands for the default client</param>
public void DeleteSnapshot(ref ulong requestId, Guid snapshotId, RsvdClient rsvdClient = null)
{
if (rsvdClient == null)
{
rsvdClient = this.client;
}
SVHDX_TUNNEL_OPERATION_HEADER? header;
SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST deleteRequest = new SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST();
deleteRequest.SnapshotId = snapshotId;
deleteRequest.PersistReference = PersistReference_Flags.PersistReferenceFalse;
deleteRequest.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM;
byte[] payload = rsvdClient.CreateTunnelMetaOperationDeleteSnapshotRequest(deleteRequest);
SVHDX_TUNNEL_OPERATION_HEADER? deleteResponse;
uint status = rsvdClient.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>(
false,
RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_DELETE_SNAPSHOT,
requestId,
payload,
out header,
out deleteResponse);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Ioctl should succeed, actual status: {0}",
GetStatus(status));
VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_DELETE_SNAPSHOT, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, requestId++);
}
public SVHDX_TUNNEL_DISK_INFO_RESPONSE? GetVirtualDiskInfo(ref ulong requestId, RsvdClient rsvdClient = null)
{
if (rsvdClient == null)
{
rsvdClient = this.client;
}
byte[] payload = client.CreateTunnelDiskInfoRequest();
SVHDX_TUNNEL_OPERATION_HEADER? header;
SVHDX_TUNNEL_DISK_INFO_RESPONSE? response;
uint status = client.TunnelOperation<SVHDX_TUNNEL_DISK_INFO_RESPONSE>(
false,//true for Async operation, false for non-async operation
RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_GET_DISK_INFO_OPERATION,
requestId,
payload,
out header,
out response);
BaseTestSite.Assert.AreEqual(
(uint)Smb2Status.STATUS_SUCCESS,
status,
"Ioctl should succeed, actual status: {0}",
GetStatus(status));
VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_GET_DISK_INFO_OPERATION, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, requestId++);
return response;
}
/// <summary>
/// Verify the Tunnel Operation Header
/// </summary>
/// <param name="header">The received Tunnel Operation Header</param>
/// <param name="code">The operation code</param>
/// <param name="status">The received status</param>
/// <param name="requestId">The request ID</param>
public void VerifyTunnelOperationHeader(SVHDX_TUNNEL_OPERATION_HEADER header, RSVD_TUNNEL_OPERATION_CODE code, uint status, ulong requestId)
{
BaseTestSite.Assert.AreEqual(
code,
header.OperationCode,
"Operation code should be {0}, actual is {1}", code, header.OperationCode);
BaseTestSite.Assert.AreEqual(
status,
header.Status,
"Status should be {0}, actual is {1}", GetStatus(status), GetStatus(header.Status));
BaseTestSite.Assert.AreEqual(
requestId,
header.RequestId,
"The RequestId should be {0}, actual is {1}", requestId, header.RequestId);
}
/// <summary>
/// Verify the specific field of response
/// </summary>
/// <typeparam name="T">The response type</typeparam>
/// <param name="fieldName">The field name in response</param>
/// <param name="expected">The expected value of the specific field</param>
/// <param name="actual">The actual value of the specific field</param>
public void VerifyFieldInResponse<T>(string fieldName, T expected, T actual)
{
BaseTestSite.Assert.AreEqual(
expected,
actual,
fieldName + " should be {0}, actual is {1}", expected, actual);
}
/// <summary>
/// Convert the status from uint to string
/// </summary>
/// <param name="status">The status in uint</param>
/// <returns>The status in string format</returns>
public string GetStatus(uint status)
{
if (Enum.IsDefined(typeof(RsvdStatus), status))
{
return ((RsvdStatus)status).ToString();
}
return Smb2Status.GetStatusCode(status);
}
}
}
| |
//! \file AudioMV.cs
//! \date Fri Jun 24 05:29:29 2016
//! \brief PVNS engine audio format.
//
// Copyright (C) 2016 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
namespace GameRes.Formats.Purple
{
[Export(typeof(AudioFormat))]
public class MvAudio : AudioFormat
{
public override string Tag { get { return "MV"; } }
public override string Description { get { return "PVNS engine compressed audio format"; } }
public override uint Signature { get { return 0x53564B4D; } } // 'MKVS'
public override SoundInput TryOpen (IBinaryStream file)
{
using (var reader = new MvDecoder (file))
{
reader.Unpack();
var input = new MemoryStream (reader.Data);
var sound = new RawPcmInput (input, reader.Format);
file.Dispose();
return sound;
}
}
}
internal class MvDecoderBase : IDisposable
{
private IBinaryStream m_input;
private int m_bits;
private int m_bits_count = 0;
protected WaveFormat m_format;
protected byte[] m_output;
protected int m_channel_size;
public byte[] Data { get { return m_output; } }
public WaveFormat Format { get { return m_format; } }
protected MvDecoderBase (IBinaryStream input)
{
m_input = input;
}
internal void SetPosition (long pos)
{
m_input.Position = pos;
m_bits_count = 0;
}
internal int GetBits (int count)
{
int v = 0;
while (count --> 0)
{
if (0 == m_bits_count)
{
m_bits = m_input.ReadInt32();
m_bits_count = 32;
}
v = (v << 1) | (m_bits & 1);
m_bits >>= 1;
--m_bits_count;
}
return v;
}
internal int GetCount ()
{
int n = 0;
while (GetBits (1) > 0)
++n;
return n;
}
internal static short Clamp (int sample)
{
if (sample > 0x7FFF)
return 0x7FFF;
else if (sample < -0x7FFF)
return -0x7FFF;
else
return (short)sample;
}
#region IDisposable Members
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
}
#endregion
}
internal sealed class MvDecoder : MvDecoderBase
{
int m_samples;
public MvDecoder (IBinaryStream input) : base (input)
{
var header = input.ReadHeader (0x12);
m_channel_size = header.ToInt32 (4);
m_format.FormatTag = 1;
m_format.BitsPerSample = 16;
m_format.Channels = header[0xC];
m_format.SamplesPerSecond = header.ToUInt16 (0xA);
m_format.BlockAlign = (ushort)(m_format.Channels*m_format.BitsPerSample/8);
m_format.AverageBytesPerSecond = m_format.BlockAlign * m_format.SamplesPerSecond;
m_output = new byte[m_format.BlockAlign * m_channel_size];
m_samples = header.ToInt32 (0xE);
}
public void Unpack ()
{
SetPosition (0x12);
var pre_sample1 = new int[0x400];
var pre_sample2 = new int[0x400];
var pre_sample3 = new int[0x140 * m_format.Channels];
int pre2_idx = 0;
int dst = 0;
for (int i = 0; i < m_samples; ++i)
{
for (int c = 0; c < m_format.Channels; ++c)
{
int count = GetBits (10);
int v32 = (int)SampleTable[GetBits (10)];
for (int j = 0; j < pre_sample1.Length; ++j)
pre_sample1[j] = 0;
for (int j = 0; j < count; ++j)
{
int bit_count = GetCount();
if (bit_count != 0)
{
int coef = GetBits (bit_count);
if (coef < (1 << (bit_count - 1)))
coef += 1 - (1 << bit_count);
pre_sample1[j] = v32 * coef;
}
else
{
j += GetBits (3);
}
}
int pre3_idx = 0;
for (int n = 0; n < 10; ++n)
{
int coef1_idx = 0;
for (int j = 0; j < 64; ++j)
{
int pre1_idx = pre3_idx;
int sample = 0;
for (int k = 0; k < 8; ++k)
{
for (int m = 0; m < 4; ++m)
{
sample += Coef1Table[coef1_idx] * pre_sample1[pre1_idx++] >> 10;
++coef1_idx;
}
}
pre_sample2[pre2_idx + j] = sample;
}
int coef2_idx = 0;
for (int j = 0; j < 0x20; ++j)
{
int x = 0;
int m = pre2_idx + j;
for (int k = 0; k < 0x10; ++k)
{
int coef = Coef2Table[coef2_idx++] * pre_sample2[m & 0x3FF] >> 10;
x += ((~k & 2) - 1) * coef;
m += ~(k << 6) & 0x40 | 0x20;
}
pre_sample3[pre3_idx++] = x;
}
pre2_idx = ((ushort)pre2_idx - 0x40) & 0x3FF;
}
for (int j = 0; j < 0x140; ++j)
{
short sample = Clamp (pre_sample3[j] >> 1);
LittleEndian.Pack (sample, m_output, dst);
dst += 2; // ??? shouldn't channel interleaving be taken into account?
}
}
}
}
static MvDecoder ()
{
var table = new uint[0x400];
Array.Copy (SampleTable, 0, table, 0x192, SampleTable.Length);
SampleTable = table;
}
static readonly uint[] SampleTable = {
1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9,
0x0A, 0x0B, 0x0D, 0x0F, 0x11, 0x13, 0x15, 0x18, 0x1C, 0x1F, 0x24, 0x29, 0x2E, 0x34, 0x3B, 0x43,
0x4C, 0x57, 0x62, 0x6F, 0x7E, 0x8F, 0x0A2, 0x0B8, 0x0D1, 0x0ED, 0x10C, 0x130, 0x159, 0x187, 0x1BB,
0x1F6, 0x23A, 0x286, 0x2DC, 0x33E, 0x3AC, 0x42A, 0x4B8, 0x55A, 0x611, 0x6E0, 0x7CB, 0x8D5, 0x0A03,
0x0B59, 0x0CDD, 0x0E95, 0x1087, 0x12BC, 0x153C, 0x1812, 0x1B48, 0x1EED, 0x230D, 0x27BB, 0x2D09,
0x330B, 0x39DC, 0x4195, 0x4A56, 0x5442, 0x5F81, 0x6C40, 0x7AB3, 0x8B13, 0x9DA4, 0x0B2AE, 0x0CA87,
0x0E590, 0x10434, 0x126EF, 0x14E4C, 0x17AEB, 0x1AD7E, 0x1E6D2, 0x227CC, 0x27173, 0x2C4EE, 0x3238D,
0x38ECE, 0x4085F, 0x4922B, 0x52E5A, 0x5DF62, 0x6A80C, 0x78B7D, 0x88D4B, 0x9B181, 0x0AFCB8,
0x0C7424, 0x0E1DAC, 0x100000, 0x1222B4, 0x148E61, 0x174CC4, 0x1A68E6, 0x1DEF4C, 0x021EE24,
0x0267582, 0x02B979E, 0x0316920, 0x0380171, 0x03F7B1A, 0x047F42F, 0x0518EC8,
0x005C7189, 0x0068C83E, 0x0076C48E, 0x00869EBE, 0x00989697, 0x00ACF464, 0x00C40A17, 0x00DE3494,
0x00FBDD22, 0x011D7B16, 0x014395B5, 0x016EC64D, 0x019FBAA7, 0x01D737BC, 0x02161CD0, 0x025D66F3,
0x02AE34FC, 0x0309CC0D, 0x03719CA9, 0x03E74889, 0x046CA921, 0x0503D71B, 0x05AF32C0, 0x06716D8A,
0x074D94FB, 0x08471EE1, 0x0961F74A, 0x0AA29043, 0x0C0DF3C3, 0x0DA9D7EB, 0x0F7CB605, 0x118DE48F,
0x13E5B4C1, 0x168D9405, 0x199031E4, 0x1CF9AB08, 0x20D7B9F2, 0x2539EE3E, 0x2A31EB3C, 0x2FD3AEE5,
0x3635E252, 0x3D7234E4, 0x45A5C3A0, 0x4EF18E50, 0x597AFC4E, 0x656C72FE, 0x72F60068, 0x824E1C92,
0x93B284A6, 0xA7693360, 0xBDC17A9E, 0xD7154285, 0xF3CA7345, 0x14548F1D, 0x39368323, 0x6304B60B,
0x92675D44, 0xC81D21C8, 0x04FE1F40, 0x49FF4989, 0x98364650, 0xF0DDCA35, 0x555A8B0B, 0xC740DB1A,
0x485B03F6, 0xDAB07A77, 0x808E08CC, 0x3C8F0F8E, 0x11A80301, 0x03324EC0, 0x14F9CFAE, 0x4B4C1A53,
0xAB09CB36, 0x39BA26C6, 0xFDA157D3, 0xFDD9A61D, 0x42700A59, 0xD48492BE, 0xBE6F1A63, 0x0BE8E730,
0xCA3BD5C8, 0x0877D150, 0xD7AF6E22, 0x4B3C9B45, 0x790E7F24, 0x7A01B8AE, 0x6A446813, 0x69C79196,
0x9CBFA29E, 0x2C361E40, 0x46AEBB45, 0x20E28C1F, 0xF69421D6, 0x0B7FFF6C, 0xAC6D2545, 0x3061FD29,
0xFA0281CC, 0x791D22E1, 0x2C6CA27E, 0xA395FE02, 0x816A6624, 0x7E765BA6, 0x6BE83C9E, 0x36D9EE16,
0xEC0ADC7A, 0xBC19516B, 0x004C1DC9, 0x3FFFDB91, 0x36CD9D5F, 0xDB83CB83, 0x680D3C3A, 0x62665333,
0xA6C432FE, 0x7316DA81, 0x74147C83, 0xD4028D70, 0x4B7804F0, 0x345C419E, 0x9F6EFD39, 0x6CAFF339,
0x67086BEA, 0x63A5F955, 0x65848E7B, 0xC5B6EFEF, 0x610F9314, 0xCBE1A360, 0x8CAA6A87, 0x5E8F23A2,
0x7CBAC282, 0xF7CAEDB8, 0x16A3E37E, 0xC430E23C, 0x0BCAAD8E, 0xA638B9A5, 0x998455D9, 0xEE20E8F1,
0x7C4226CE, 0xD49A7152, 0x4829DC77, 0x13434BF5, 0xB07ACE02, 0x58D0ECCF, 0xB724B5AC, 0xD5C48581,
0x4DDF847F, 0xC1A2CBDE, 0xAAF9A261, 0x8A3CC828, 0x819ECA65, 0x6BD8DCBC, 0x7E8BA111, 0x8AF96278,
0xF23C6AD9, 0x64EE47B6, 0x896763F7, 0xA75E2F54, 0x7BC8B5BB, 0x5C8B914C, 0xD8C8442D, 0x0898814F,
0xC5CBCE4B, 0x0EEC7CF0, 0xDE872E53, 0xCA8FEFF0, 0xCAF14963, 0x9301470C, 0xF7F9BE55, 0xEEDD91D7,
0xBEAE2B5F, 0x18C51C24, 0xE0E2027C, 0x89641700, 0x06A53454, 0x7EFCA69E, 0x041D80AE, 0xCEEC5354,
0xA93DA54C, 0x69FBCBF4, 0xA8DD9914, 0x18239314, 0x45E66D10, 0xE4AD08E8, 0x25BDE2A0, 0x289C3F50,
0x0C445120, 0xCA29BE38, 0xB32BDF40, 0x2E668E30, 0x3C220C80, 0x3FB63840, 0xB605D1A0, 0xC7D85340,
0x1CF90F40, 0xFC81FE00, 0xA6BDAA80, 0xF523F640, 0xB5AB4A80, 0xF1AFFA40, 0x6906E880, 0x0BE74AC0,
0x384A5880, 0x0133C880, 0xE2293C00, 0x0B819180, 0x0475A980, 0xD05D4700, 0x333C9700, 0x409BF280,
0x3515DE00, 0xE29F7D00, 0xE2C72400, 0x88E93700, 0x703D4500, 0xC6771000, 0x6D335200, 0x16D6F000,
0x07D2F200, 0x9A0BEA00, 0x8C1F4A00, 0x22092C00, 0xD5107C00, 0x8A20AC00, 0xDDBFC000, 0x07CE7800,
};
internal static readonly short[] Coef1Table = {
724, -724, -724, 724, 724, -724, -724, 724, 724, -724, -724, 724, 724, -724, -724, 724,
724, -724, -724, 724, 724, -724, -724, 724, 724, -724, -724, 724, 724, -724, -724, 724,
687, -822, -526, 925, 344, -993, -150, 1022, -50, -1012, 248, 964, -437, -878, 609, 758,
-758, -609, 878, 437, -964, -248, 1012, 50, -1022, 150, 993, -344, -925, 526, 822, -687,
649, -903, -297, 1019, -100, -979, 482, 791, -791, -482, 979, 100, -1019, 297, 903, -649,
-649, 903, 297, -1019, 100, 979, -482, -791, 791, 482, -979, -100, 1019, -297, -903, 649,
609, -964, -50, 993, -526, -687, 925, 150, -1012, 437, 758, -878, -248, 1022, -344, -822,
822, 344, -1022, 248, 878, -758, -437, 1012, -150, -925, 687, 526, -993, 50, 964, -609,
568, -1004, 199, 851, -851, -199, 1004, -568, -568, 1004, -199, -851, 851, 199, -1004, 568,
568, -1004, 199, 851, -851, -199, 1004, -568, -568, 1004, -199, -851, 851, 199, -1004, 568,
526, -1022, 437, 609, -1012, 344, 687, -993, 248, 758, -964, 150, 822, -925, 50, 878,
-878, -50, 925, -822, -150, 964, -758, -248, 993, -687, -344, 1012, -609, -437, 1022, -526,
482, -1019, 649, 297, -979, 791, 100, -903, 903, -100, -791, 979, -297, -649, 1019, -482,
-482, 1019, -649, -297, 979, -791, -100, 903, -903, 100, 791, -979, 297, 649, -1019, 482,
437, -993, 822, -50, -758, 1012, -526, -344, 964, -878, 150, 687, -1022, 609, 248, -925,
925, -248, -609, 1022, -687, -150, 878, -964, 344, 526, -1012, 758, 50, -822, 993, -437,
391, -946, 946, -391, -391, 946, -946, 391, 391, -946, 946, -391, -391, 946, -946, 391,
391, -946, 946, -391, -391, 946, -946, 391, 391, -946, 946, -391, -391, 946, -946, 391,
344, -878, 1012, -687, 50, 609, -993, 925, -437, -248, 822, -1022, 758, -150, -526, 964,
-964, 526, 150, -758, 1022, -822, 248, 437, -925, 993, -609, -50, 687, -1012, 878, -344,
297, -791, 1019, -903, 482, 100, -649, 979, -979, 649, -100, -482, 903, -1019, 791, -297,
-297, 791, -1019, 903, -482, -100, 649, -979, 979, -649, 100, 482, -903, 1019, -791, 297,
248, -687, 964, -1012, 822, -437, -50, 526, -878, 1022, -925, 609, -150, -344, 758, -993,
993, -758, 344, 150, -609, 925, -1022, 878, -526, 50, 437, -822, 1012, -964, 687, -248,
199, -568, 851, -1004, 1004, -851, 568, -199, -199, 568, -851, 1004, -1004, 851, -568, 199,
199, -568, 851, -1004, 1004, -851, 568, -199, -199, 568, -851, 1004, -1004, 851, -568, 199,
150, -437, 687, -878, 993, -1022, 964, -822, 609, -344, 50, 248, -526, 758, -925, 1012,
-1012, 925, -758, 526, -248, -50, 344, -609, 822, -964, 1022, -993, 878, -687, 437, -150,
100, -297, 482, -649, 791, -903, 979, -1019, 1019, -979, 903, -791, 649, -482, 297, -100,
-100, 297, -482, 649, -791, 903, -979, 1019, -1019, 979, -903, 791, -649, 482, -297, 100,
50, -150, 248, -344, 437, -526, 609, -687, 758, -822, 878, -925, 964, -993, 1012, -1022,
1022, -1012, 993, -964, 925, -878, 822, -758, 687, -609, 526, -437, 344, -248, 150, -50,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-50, 150, -248, 344, -437, 526, -609, 687, -758, 822, -878, 925, -964, 993, -1012, 1022,
-1022, 1012, -993, 964, -925, 878, -822, 758, -687, 609, -526, 437, -344, 248, -150, 50,
-100, 297, -482, 649, -791, 903, -979, 1019, -1019, 979, -903, 791, -649, 482, -297, 100,
100, -297, 482, -649, 791, -903, 979, -1019, 1019, -979, 903, -791, 649, -482, 297, -100,
-150, 437, -687, 878, -993, 1022, -964, 822, -609, 344, -50, -248, 526, -758, 925, -1012,
1012, -925, 758, -526, 248, 50, -344, 609, -822, 964, -1022, 993, -878, 687, -437, 150,
-199, 568, -851, 1004, -1004, 851, -568, 199, 199, -568, 851, -1004, 1004, -851, 568, -199,
-199, 568, -851, 1004, -1004, 851, -568, 199, 199, -568, 851, -1004, 1004, -851, 568, -199,
-248, 687, -964, 1012, -822, 437, 50, -526, 878, -1022, 925, -609, 150, 344, -758, 993,
-993, 758, -344, -150, 609, -925, 1022, -878, 526, -50, -437, 822, -1012, 964, -687, 248,
-297, 791, -1019, 903, -482, -100, 649, -979, 979, -649, 100, 482, -903, 1019, -791, 297,
297, -791, 1019, -903, 482, 100, -649, 979, -979, 649, -100, -482, 903, -1019, 791, -297,
-344, 878, -1012, 687, -50, -609, 993, -925, 437, 248, -822, 1022, -758, 150, 526, -964,
964, -526, -150, 758, -1022, 822, -248, -437, 925, -993, 609, 50, -687, 1012, -878, 344,
-391, 946, -946, 391, 391, -946, 946, -391, -391, 946, -946, 391, 391, -946, 946, -391,
-391, 946, -946, 391, 391, -946, 946, -391, -391, 946, -946, 391, 391, -946, 946, -391,
-437, 993, -822, 50, 758, -1012, 526, 344, -964, 878, -150, -687, 1022, -609, -248, 925,
-925, 248, 609, -1022, 687, 150, -878, 964, -344, -526, 1012, -758, -50, 822, -993, 437,
-482, 1019, -649, -297, 979, -791, -100, 903, -903, 100, 791, -979, 297, 649, -1019, 482,
482, -1019, 649, 297, -979, 791, 100, -903, 903, -100, -791, 979, -297, -649, 1019, -482,
-526, 1022, -437, -609, 1012, -344, -687, 993, -248, -758, 964, -150, -822, 925, -50, -878,
878, 50, -925, 822, 150, -964, 758, 248, -993, 687, 344, -1012, 609, 437, -1022, 526,
-568, 1004, -199, -851, 851, 199, -1004, 568, 568, -1004, 199, 851, -851, -199, 1004, -568,
-568, 1004, -199, -851, 851, 199, -1004, 568, 568, -1004, 199, 851, -851, -199, 1004, -568,
-609, 964, 50, -993, 526, 687, -925, -150, 1012, -437, -758, 878, 248, -1022, 344, 822,
-822, -344, 1022, -248, -878, 758, 437, -1012, 150, 925, -687, -526, 993, -50, -964, 609,
-649, 903, 297, -1019, 100, 979, -482, -791, 791, 482, -979, -100, 1019, -297, -903, 649,
649, -903, -297, 1019, -100, -979, 482, 791, -791, -482, 979, 100, -1019, 297, 903, -649,
-687, 822, 526, -925, -344, 993, 150, -1022, 50, 1012, -248, -964, 437, 878, -609, -758,
758, 609, -878, -437, 964, 248, -1012, -50, 1022, -150, -993, 344, 925, -526, -822, 687,
-724, 724, 724, -724, -724, 724, 724, -724, -724, 724, 724, -724, -724, 724, 724, -724,
-724, 724, 724, -724, -724, 724, 724, -724, -724, 724, 724, -724, -724, 724, 724, -724,
-758, 609, 878, -437, -964, 248, 1012, -50, -1022, -150, 993, 344, -925, -526, 822, 687,
-687, -822, 526, 925, -344, -993, 150, 1022, 50, -1012, -248, 964, 437, -878, -609, 758,
-791, 482, 979, -100, -1019, -297, 903, 649, -649, -903, 297, 1019, 100, -979, -482, 791,
791, -482, -979, 100, 1019, 297, -903, -649, 649, 903, -297, -1019, -100, 979, 482, -791,
-822, 344, 1022, 248, -878, -758, 437, 1012, 150, -925, -687, 526, 993, 50, -964, -609,
609, 964, -50, -993, -526, 687, 925, -150, -1012, -437, 758, 878, -248, -1022, -344, 822,
-851, 199, 1004, 568, -568, -1004, -199, 851, 851, -199, -1004, -568, 568, 1004, 199, -851,
-851, 199, 1004, 568, -568, -1004, -199, 851, 851, -199, -1004, -568, 568, 1004, 199, -851,
-878, 50, 925, 822, -150, -964, -758, 248, 993, 687, -344, -1012, -609, 437, 1022, 526,
-526, -1022, -437, 609, 1012, 344, -687, -993, -248, 758, 964, 150, -822, -925, -50, 878,
-903, -100, 791, 979, 297, -649, -1019, -482, 482, 1019, 649, -297, -979, -791, 100, 903,
903, 100, -791, -979, -297, 649, 1019, 482, -482, -1019, -649, 297, 979, 791, -100, -903,
-925, -248, 609, 1022, 687, -150, -878, -964, -344, 526, 1012, 758, -50, -822, -993, -437,
437, 993, 822, 50, -758, -1012, -526, 344, 964, 878, 150, -687, -1022, -609, 248, 925,
-946, -391, 391, 946, 946, 391, -391, -946, -946, -391, 391, 946, 946, 391, -391, -946,
-946, -391, 391, 946, 946, 391, -391, -946, -946, -391, 391, 946, 946, 391, -391, -946,
-964, -526, 150, 758, 1022, 822, 248, -437, -925, -993, -609, 50, 687, 1012, 878, 344,
-344, -878, -1012, -687, -50, 609, 993, 925, 437, -248, -822, -1022, -758, -150, 526, 964,
-979, -649, -100, 482, 903, 1019, 791, 297, -297, -791, -1019, -903, -482, 100, 649, 979,
979, 649, 100, -482, -903, -1019, -791, -297, 297, 791, 1019, 903, 482, -100, -649, -979,
-993, -758, -344, 150, 609, 925, 1022, 878, 526, 50, -437, -822, -1012, -964, -687, -248,
248, 687, 964, 1012, 822, 437, -50, -526, -878, -1022, -925, -609, -150, 344, 758, 993,
-1004, -851, -568, -199, 199, 568, 851, 1004, 1004, 851, 568, 199, -199, -568, -851, -1004,
-1004, -851, -568, -199, 199, 568, 851, 1004, 1004, 851, 568, 199, -199, -568, -851, -1004,
-1012, -925, -758, -526, -248, 50, 344, 609, 822, 964, 1022, 993, 878, 687, 437, 150,
-150, -437, -687, -878, -993, -1022, -964, -822, -609, -344, -50, 248, 526, 758, 925, 1012,
-1019, -979, -903, -791, -649, -482, -297, -100, 100, 297, 482, 649, 791, 903, 979, 1019,
1019, 979, 903, 791, 649, 482, 297, 100, -100, -297, -482, -649, -791, -903, -979, -1019,
-1022, -1012, -993, -964, -925, -878, -822, -758, -687, -609, -526, -437, -344, -248, -150, -50,
50, 150, 248, 344, 437, 526, 609, 687, 758, 822, 878, 925, 964, 993, 1012, 1022,
-1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024,
-1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024, -1024,
-1022, -1012, -993, -964, -925, -878, -822, -758, -687, -609, -526, -437, -344, -248, -150, -50,
50, 150, 248, 344, 437, 526, 609, 687, 758, 822, 878, 925, 964, 993, 1012, 1022,
-1019, -979, -903, -791, -649, -482, -297, -100, 100, 297, 482, 649, 791, 903, 979, 1019,
1019, 979, 903, 791, 649, 482, 297, 100, -100, -297, -482, -649, -791, -903, -979, -1019,
-1012, -925, -758, -526, -248, 50, 344, 609, 822, 964, 1022, 993, 878, 687, 437, 150,
-150, -437, -687, -878, -993, -1022, -964, -822, -609, -344, -50, 248, 526, 758, 925, 1012,
-1004, -851, -568, -199, 199, 568, 851, 1004, 1004, 851, 568, 199, -199, -568, -851, -1004,
-1004, -851, -568, -199, 199, 568, 851, 1004, 1004, 851, 568, 199, -199, -568, -851, -1004,
-993, -758, -344, 150, 609, 925, 1022, 878, 526, 50, -437, -822, -1012, -964, -687, -248,
248, 687, 964, 1012, 822, 437, -50, -526, -878, -1022, -925, -609, -150, 344, 758, 993,
-979, -649, -100, 482, 903, 1019, 791, 297, -297, -791, -1019, -903, -482, 100, 649, 979,
979, 649, 100, -482, -903, -1019, -791, -297, 297, 791, 1019, 903, 482, -100, -649, -979,
-964, -526, 150, 758, 1022, 822, 248, -437, -925, -993, -609, 50, 687, 1012, 878, 344,
-344, -878, -1012, -687, -50, 609, 993, 925, 437, -248, -822, -1022, -758, -150, 526, 964,
-946, -391, 391, 946, 946, 391, -391, -946, -946, -391, 391, 946, 946, 391, -391, -946,
-946, -391, 391, 946, 946, 391, -391, -946, -946, -391, 391, 946, 946, 391, -391, -946,
-925, -248, 609, 1022, 687, -150, -878, -964, -344, 526, 1012, 758, -50, -822, -993, -437,
437, 993, 822, 50, -758, -1012, -526, 344, 964, 878, 150, -687, -1022, -609, 248, 925,
-903, -100, 791, 979, 297, -649, -1019, -482, 482, 1019, 649, -297, -979, -791, 100, 903,
903, 100, -791, -979, -297, 649, 1019, 482, -482, -1019, -649, 297, 979, 791, -100, -903,
-878, 50, 925, 822, -150, -964, -758, 248, 993, 687, -344, -1012, -609, 437, 1022, 526,
-526, -1022, -437, 609, 1012, 344, -687, -993, -248, 758, 964, 150, -822, -925, -50, 878,
-851, 199, 1004, 568, -568, -1004, -199, 851, 851, -199, -1004, -568, 568, 1004, 199, -851,
-851, 199, 1004, 568, -568, -1004, -199, 851, 851, -199, -1004, -568, 568, 1004, 199, -851,
-822, 344, 1022, 248, -878, -758, 437, 1012, 150, -925, -687, 526, 993, 50, -964, -609,
609, 964, -50, -993, -526, 687, 925, -150, -1012, -437, 758, 878, -248, -1022, -344, 822,
-791, 482, 979, -100, -1019, -297, 903, 649, -649, -903, 297, 1019, 100, -979, -482, 791,
791, -482, -979, 100, 1019, 297, -903, -649, 649, 903, -297, -1019, -100, 979, 482, -791,
-758, 609, 878, -437, -964, 248, 1012, -50, -1022, -150, 993, 344, -925, -526, 822, 687,
-687, -822, 526, 925, -344, -993, 150, 1022, 50, -1012, -248, 964, 437, -878, -609, 758,
};
static readonly short[] Coef2Table = {
0, 0, -3, 7, 31, -80, -102, 585, 1172, 585, -102, -80, 31, 7, -3, 0,
0, 0, -3, 8, 31, -86, -93, 614, 1171, 556, -111, -74, 32, 6, -3, 0,
0, 0, -3, 9, 30, -91, -82, 643, 1169, 527, -119, -69, 32, 5, -3, 0,
0, 0, -3, 10, 29, -97, -71, 671, 1166, 499, -126, -63, 32, 4, -3, 0,
0, 0, -3, 11, 28, -102, -58, 700, 1161, 470, -132, -57, 32, 3, -2, 0,
0, 0, -3, 12, 27, -108, -45, 728, 1154, 442, -138, -52, 32, 3, -2, 0,
0, 0, -3, 13, 25, -113, -31, 756, 1147, 413, -142, -46, 32, 2, -2, 0,
0, 0, -3, 14, 23, -118, -16, 783, 1138, 385, -146, -41, 31, 1, -2, 0,
0, 0, -3, 15, 22, -123, -1, 810, 1127, 358, -149, -36, 31, 1, -2, 0,
0, 0, -3, 16, 20, -128, 15, 836, 1115, 331, -152, -31, 30, 0, -2, 0,
0, -1, -3, 17, 17, -132, 33, 862, 1102, 304, -154, -26, 29, 0, -2, 0,
0, -1, -3, 18, 15, -136, 51, 887, 1088, 278, -155, -21, 29, 0, -2, 0,
0, -1, -3, 20, 12, -140, 70, 911, 1073, 252, -155, -17, 28, 0, -2, 0,
0, -1, -2, 21, 9, -144, 90, 934, 1056, 227, -155, -12, 27, -1, -1, 0,
0, -1, -2, 22, 6, -147, 111, 957, 1038, 202, -154, -8, 26, -1, -1, 0,
0, -1, -2, 23, 2, -149, 133, 979, 1020, 178, -153, -4, 25, -1, -1, 0,
0, -1, -2, 24, 0, -151, 155, 1000, 1000, 155, -151, 0, 24, -2, -1, 0,
0, -1, -1, 25, -4, -153, 178, 1020, 979, 133, -149, 2, 23, -2, -1, 0,
0, -1, -1, 26, -8, -154, 202, 1038, 957, 111, -147, 6, 22, -2, -1, 0,
0, -1, -1, 27, -12, -155, 227, 1056, 934, 90, -144, 9, 21, -2, -1, 0,
0, -2, 0, 28, -17, -155, 252, 1073, 911, 70, -140, 12, 20, -3, -1, 0,
0, -2, 0, 29, -21, -155, 278, 1088, 887, 51, -136, 15, 18, -3, -1, 0,
0, -2, 0, 29, -26, -154, 304, 1102, 862, 33, -132, 17, 17, -3, -1, 0,
0, -2, 0, 30, -31, -152, 331, 1115, 836, 15, -128, 20, 16, -3, 0, 0,
0, -2, 1, 31, -36, -149, 358, 1127, 810, -1, -123, 22, 15, -3, 0, 0,
0, -2, 1, 31, -41, -146, 385, 1138, 783, -16, -118, 23, 14, -3, 0, 0,
0, -2, 2, 32, -46, -142, 413, 1147, 756, -31, -113, 25, 13, -3, 0, 0,
0, -2, 3, 32, -52, -138, 442, 1154, 728, -45, -108, 27, 12, -3, 0, 0,
0, -2, 3, 32, -57, -132, 470, 1161, 700, -58, -102, 28, 11, -3, 0, 0,
0, -3, 4, 32, -63, -126, 499, 1166, 671, -71, -97, 29, 10, -3, 0, 0,
0, -3, 5, 32, -69, -119, 527, 1169, 643, -82, -91, 30, 9, -3, 0, 0,
0, -3, 6, 32, -74, -111, 556, 1171, 614, -93, -86, 31, 8, -3, 0, 0,
};
}
}
| |
using System;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
namespace Org.BouncyCastle.Crypto.Macs
{
/**
* CMAC - as specified at www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html
* <p>
* CMAC is analogous to OMAC1 - see also en.wikipedia.org/wiki/CMAC
* </p><p>
* CMAC is a NIST recomendation - see
* csrc.nist.gov/CryptoToolkit/modes/800-38_Series_Publications/SP800-38B.pdf
* </p><p>
* CMAC/OMAC1 is a blockcipher-based message authentication code designed and
* analyzed by Tetsu Iwata and Kaoru Kurosawa.
* </p><p>
* CMAC/OMAC1 is a simple variant of the CBC MAC (Cipher Block Chaining Message
* Authentication Code). OMAC stands for One-Key CBC MAC.
* </p><p>
* It supports 128- or 64-bits block ciphers, with any key size, and returns
* a MAC with dimension less or equal to the block size of the underlying
* cipher.
* </p>
*/
public class CMac
: IMac
{
private const byte CONSTANT_128 = (byte)0x87;
private const byte CONSTANT_64 = (byte)0x1b;
private byte[] ZEROES;
private byte[] mac;
private byte[] buf;
private int bufOff;
private IBlockCipher cipher;
private int macSize;
private byte[] L, Lu, Lu2;
/**
* create a standard MAC based on a CBC block cipher (64 or 128 bit block).
* This will produce an authentication code the length of the block size
* of the cipher.
*
* @param cipher the cipher to be used as the basis of the MAC generation.
*/
public CMac(
IBlockCipher cipher)
: this(cipher, cipher.GetBlockSize() * 8)
{
}
/**
* create a standard MAC based on a block cipher with the size of the
* MAC been given in bits.
* <p/>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
*
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128.
*/
public CMac(
IBlockCipher cipher,
int macSizeInBits)
{
if ((macSizeInBits % 8) != 0)
throw new ArgumentException("MAC size must be multiple of 8");
if (macSizeInBits > (cipher.GetBlockSize() * 8))
{
throw new ArgumentException(
"MAC size must be less or equal to "
+ (cipher.GetBlockSize() * 8));
}
if (cipher.GetBlockSize() != 8 && cipher.GetBlockSize() != 16)
{
throw new ArgumentException(
"Block size must be either 64 or 128 bits");
}
this.cipher = new CbcBlockCipher(cipher);
this.macSize = macSizeInBits / 8;
mac = new byte[cipher.GetBlockSize()];
buf = new byte[cipher.GetBlockSize()];
ZEROES = new byte[cipher.GetBlockSize()];
bufOff = 0;
}
public string AlgorithmName
{
get { return cipher.AlgorithmName; }
}
private static byte[] doubleLu(
byte[] inBytes)
{
int FirstBit = (inBytes[0] & 0xFF) >> 7;
byte[] ret = new byte[inBytes.Length];
for (int i = 0; i < inBytes.Length - 1; i++)
{
ret[i] = (byte)((inBytes[i] << 1) + ((inBytes[i + 1] & 0xFF) >> 7));
}
ret[inBytes.Length - 1] = (byte)(inBytes[inBytes.Length - 1] << 1);
if (FirstBit == 1)
{
ret[inBytes.Length - 1] ^= inBytes.Length == 16 ? CONSTANT_128 : CONSTANT_64;
}
return ret;
}
public void Init(
ICipherParameters parameters)
{
if (parameters != null)
{
cipher.Init(true, parameters);
//initializes the L, Lu, Lu2 numbers
L = new byte[ZEROES.Length];
cipher.ProcessBlock(ZEROES, 0, L, 0);
Lu = doubleLu(L);
Lu2 = doubleLu(Lu);
}
Reset();
}
public int GetMacSize()
{
return macSize;
}
public void Update(
byte input)
{
if (bufOff == buf.Length)
{
cipher.ProcessBlock(buf, 0, mac, 0);
bufOff = 0;
}
buf[bufOff++] = input;
}
public void BlockUpdate(
byte[] inBytes,
int inOff,
int len)
{
if (len < 0)
throw new ArgumentException("Can't have a negative input length!");
int blockSize = cipher.GetBlockSize();
int gapLen = blockSize - bufOff;
if (len > gapLen)
{
Array.Copy(inBytes, inOff, buf, bufOff, gapLen);
cipher.ProcessBlock(buf, 0, mac, 0);
bufOff = 0;
len -= gapLen;
inOff += gapLen;
while (len > blockSize)
{
cipher.ProcessBlock(inBytes, inOff, mac, 0);
len -= blockSize;
inOff += blockSize;
}
}
Array.Copy(inBytes, inOff, buf, bufOff, len);
bufOff += len;
}
public int DoFinal(
byte[] outBytes,
int outOff)
{
int blockSize = cipher.GetBlockSize();
byte[] lu;
if (bufOff == blockSize)
{
lu = Lu;
}
else
{
new ISO7816d4Padding().AddPadding(buf, bufOff);
lu = Lu2;
}
for (int i = 0; i < mac.Length; i++)
{
buf[i] ^= lu[i];
}
cipher.ProcessBlock(buf, 0, mac, 0);
Array.Copy(mac, 0, outBytes, outOff, macSize);
Reset();
return macSize;
}
/**
* Reset the mac generator.
*/
public void Reset()
{
/*
* clean the buffer.
*/
Array.Clear(buf, 0, buf.Length);
bufOff = 0;
/*
* Reset the underlying cipher.
*/
cipher.Reset();
}
}
}
| |
using System;
using Android.App;
using Android.Views;
using Android.Widget;
using Android.Content;
using System.Threading;
using System.Threading.Tasks;
namespace AndroidHUD
{
public class AndHUD
{
static AndHUD shared;
public static AndHUD Shared
{
get
{
if (shared == null)
shared = new AndHUD ();
return shared;
}
}
public AndHUD()
{
}
ManualResetEvent waitDismiss = new ManualResetEvent(false);
public Dialog CurrentDialog { get; private set; }
ProgressWheel progressWheel = null;
TextView statusText = null;
ImageView imageView = null;
object statusObj = null;
readonly object dialogLock = new object();
public void Show(Context context, string status = null, int progress = -1, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, bool centered = true, Action cancelCallback = null)
{
if (progress >= 0)
ShowProgress (context, progress, status, maskType, timeout, clickCallback, cancelCallback);
else
ShowStatus(context, true, status, maskType, timeout, clickCallback, centered, cancelCallback);
}
public void ShowSuccess(Context context, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
ShowImage(context, context.Resources.GetDrawable (Resource.Drawable.ic_successstatus), status, maskType, timeout, clickCallback, cancelCallback);
}
public void ShowError(Context context, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
ShowImage(context, context.Resources.GetDrawable (Resource.Drawable.ic_errorstatus), status, maskType, timeout, clickCallback, cancelCallback);
}
public void ShowSuccessWithStatus(Context context, string status, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
ShowImage(context, context.Resources.GetDrawable (Resource.Drawable.ic_successstatus), status, maskType, timeout, clickCallback, cancelCallback);
}
public void ShowErrorWithStatus(Context context, string status, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
ShowImage(context, context.Resources.GetDrawable (Resource.Drawable.ic_errorstatus), status, maskType, timeout, clickCallback, cancelCallback);
}
public void ShowImage(Context context, int drawableResourceId, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
ShowImage(context, context.Resources.GetDrawable(drawableResourceId), status, maskType, timeout, clickCallback, cancelCallback);
}
public void ShowImage(Context context, Android.Graphics.Drawables.Drawable drawable, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
ShowImage(context, drawable, status, maskType, timeout, clickCallback, cancelCallback);
}
public void ShowToast(Context context, string status, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, bool centered = true, Action clickCallback = null, Action cancelCallback = null)
{
ShowStatus(context, false, status, maskType, timeout, clickCallback, centered, cancelCallback);
}
public void Dismiss(Context context = null)
{
DismissCurrent (context);
}
void ShowStatus (Context context, bool spinner, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, bool centered = true, Action cancelCallback = null)
{
if (timeout == null)
timeout = TimeSpan.Zero;
DismissCurrent (context);
if (CurrentDialog != null && statusObj == null)
DismissCurrent (context);
lock (dialogLock)
{
if (CurrentDialog == null)
{
SetupDialog (context, maskType, cancelCallback, (a, d, m) => {
View view;
view = LayoutInflater.From (context).Inflate (Resource.Layout.loading, null);
if (clickCallback != null)
view.Click += (sender, e) => clickCallback();
statusObj = new object();
statusText = view.FindViewById<TextView>(Resource.Id.textViewStatus);
if (!spinner)
view.FindViewById<ProgressBar>(Resource.Id.loadingProgressBar).Visibility = ViewStates.Gone;
if (maskType != MaskType.Black)
view.SetBackgroundResource(Resource.Drawable.roundedbgdark);
if (statusText != null)
{
statusText.Text = status ?? "";
statusText.Visibility = string.IsNullOrEmpty(status) ? ViewStates.Gone : ViewStates.Visible;
}
if (!centered)
{
d.Window.SetGravity (GravityFlags.Bottom);
var p = d.Window.Attributes;
p.Y = DpToPx (context, 22);
d.Window.Attributes = p;
}
return view;
});
if (timeout > TimeSpan.Zero)
{
Task.Factory.StartNew(() => {
if (!waitDismiss.WaitOne (timeout.Value))
DismissCurrent (context);
}).ContinueWith(ct => {
var ex = ct.Exception;
if (ex != null)
Android.Util.Log.Error("AndHUD", ex.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
else
{
Application.SynchronizationContext.Send(state => {
if (statusText != null)
statusText.Text = status ?? "";
}, null);
}
}
}
int DpToPx(Context context, int dp)
{
var displayMetrics = context.Resources.DisplayMetrics;
int px = (int)Math.Round((double)dp * ((double)displayMetrics.Xdpi / (double)Android.Util.DisplayMetricsDensity.Default));
return px;
}
void ShowProgress(Context context, int progress, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
if (!timeout.HasValue || timeout == null)
timeout = TimeSpan.Zero;
if (CurrentDialog != null && progressWheel == null)
DismissCurrent (context);
lock (dialogLock)
{
if (CurrentDialog == null)
{
SetupDialog (context, maskType, cancelCallback, (a, d, m) => {
var inflater = LayoutInflater.FromContext(context);
var view = inflater.Inflate(Resource.Layout.loadingprogress, null);
if (clickCallback != null)
view.Click += (sender, e) => clickCallback();
progressWheel = view.FindViewById<ProgressWheel>(Resource.Id.loadingProgressWheel);
statusText = view.FindViewById<TextView>(Resource.Id.textViewStatus);
if (maskType != MaskType.Black)
view.SetBackgroundResource(Resource.Drawable.roundedbgdark);
progressWheel.SetProgress(0);
if (statusText != null)
{
statusText.Text = status ?? "";
statusText.Visibility = string.IsNullOrEmpty(status) ? ViewStates.Gone : ViewStates.Visible;
}
return view;
});
if (timeout.Value > TimeSpan.Zero)
{
Task.Factory.StartNew(() => {
if (!waitDismiss.WaitOne (timeout.Value))
DismissCurrent (context);
}).ContinueWith(ct => {
var ex = ct.Exception;
if (ex != null)
Android.Util.Log.Error("AndHUD", ex.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
else
{
Application.SynchronizationContext.Send(state => {
progressWheel.SetProgress (progress);
statusText.Text = status ?? "";
}, null);
}
}
}
void ShowImage(Context context, Android.Graphics.Drawables.Drawable image, string status = null, MaskType maskType = MaskType.Black, TimeSpan? timeout = null, Action clickCallback = null, Action cancelCallback = null)
{
if (timeout == null)
timeout = TimeSpan.Zero;
if (CurrentDialog != null && imageView == null)
DismissCurrent (context);
lock (dialogLock)
{
if (CurrentDialog == null)
{
SetupDialog (context, maskType, cancelCallback, (a, d, m) => {
var inflater = LayoutInflater.FromContext(context);
var view = inflater.Inflate(Resource.Layout.loadingimage, null);
if (clickCallback != null)
view.Click += (sender, e) => clickCallback();
imageView = view.FindViewById<ImageView>(Resource.Id.loadingImage);
statusText = view.FindViewById<TextView>(Resource.Id.textViewStatus);
if (maskType != MaskType.Black)
view.SetBackgroundResource(Resource.Drawable.roundedbgdark);
imageView.SetImageDrawable(image);
if (statusText != null)
{
statusText.Text = status ?? "";
statusText.Visibility = string.IsNullOrEmpty(status) ? ViewStates.Gone : ViewStates.Visible;
}
return view;
});
if (timeout > TimeSpan.Zero)
{
Task.Factory.StartNew(() => {
if (!waitDismiss.WaitOne (timeout.Value))
DismissCurrent (context);
}).ContinueWith(ct => {
var ex = ct.Exception;
if (ex != null)
Android.Util.Log.Error("AndHUD", ex.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
else
{
Application.SynchronizationContext.Send(state => {
imageView.SetImageDrawable(image);
statusText.Text = status ?? "";
}, null);
}
}
}
void SetupDialog(Context context, MaskType maskType, Action cancelCallback, Func<Context, Dialog, MaskType, View> customSetup)
{
Application.SynchronizationContext.Send(state => {
CurrentDialog = new Dialog(context);
CurrentDialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
if (maskType != MaskType.Black)
CurrentDialog.Window.ClearFlags(WindowManagerFlags.DimBehind);
if (maskType == MaskType.None)
CurrentDialog.Window.SetFlags(WindowManagerFlags.NotTouchModal, WindowManagerFlags.NotTouchModal);
CurrentDialog.Window.SetBackgroundDrawable(new Android.Graphics.Drawables.ColorDrawable(Android.Graphics.Color.Transparent));
var customView = customSetup(context, CurrentDialog, maskType);
CurrentDialog.SetContentView (customView);
CurrentDialog.SetCancelable (cancelCallback != null);
if (cancelCallback != null)
CurrentDialog.CancelEvent += (sender, e) => cancelCallback();
CurrentDialog.Show ();
}, null);
}
void DismissCurrent(Context context = null)
{
lock (dialogLock)
{
if (CurrentDialog != null)
{
waitDismiss.Set ();
Action actionDismiss = () =>
{
CurrentDialog.Hide ();
CurrentDialog.Dismiss ();
statusText = null;
statusObj = null;
imageView = null;
progressWheel = null;
CurrentDialog = null;
waitDismiss.Reset ();
};
//First try the SynchronizationContext
if (Application.SynchronizationContext != null)
{
Application.SynchronizationContext.Send (state => actionDismiss (), null);
return;
}
//Next let's try and get the Activity from the CurrentDialog
if (CurrentDialog != null && CurrentDialog.Window != null && CurrentDialog.Window.Context != null)
{
if (CurrentDialog.Window.Context is Activity activity)
{
activity.RunOnUiThread(actionDismiss);
return;
}
}
//Finally if all else fails, let's see if someone passed in a context to dismiss and it
// happens to also be an Activity
if (context != null)
{
if (context is Activity activity)
{
activity.RunOnUiThread(actionDismiss);
return;
}
}
}
}
}
}
public enum MaskType
{
None = 1,
Clear = 2,
Black = 3
}
}
| |
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace MonoDevelop.Android
{
[Flags]
public enum GenerationFlags : int
{
None = 0,
KeepIntermediateFiles = 1
}
public class MonoReflector
{
private string mOutputPath;
private static string mTemplate = new StreamReader(typeof(MonoReflector).Assembly.GetManifestResourceStream("JavaClassTemplate.java")).ReadToEnd();
/*
public MonoReflector(params string[] files)
{
foreach (string assem in files)
assems.Add(Assembly.LoadFile(assem));
}
public MonoReflector(params Assembly[] files)
{
assems.AddRange(assems);
}
*/
public MonoReflector()
{
}
public MonoReflector(string outputPath)
{
mOutputPath = outputPath;
}
public string[] Generate(GenerationFlags flags, string assemblyFile)
{
return Generate(flags, Assembly.LoadFile(assemblyFile));
}
private string[] Generate(GenerationFlags flags, params Assembly[] assemblies)
{
List<string> ret = new List<string>();
foreach (Assembly a in assemblies)
{
ret.AddRange(Generate(flags, a));
}
return ret.ToArray();
}
public string[] Generate(GenerationFlags flags, Assembly assembly)
{
List<string> ret = new List<string>();
foreach (Type t in assembly.GetTypes())
{
if (!t.IsInterface)
{
Dictionary<MethodInfo, MethodInfo> methods = new Dictionary<MethodInfo, MethodInfo>();
HashSet<Type> interfaces = new HashSet<Type>();
foreach (MethodInfo subm in t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.IsVirtual))
{
Console.WriteLine(subm);
if ((subm.MemberType & MemberTypes.Property) == MemberTypes.Property || (subm.MemberType & MemberTypes.Method) == MemberTypes.Method)
{
MethodInfo androidMethod = FindBaseForMethod(subm, null);
if (androidMethod != null)
{
methods.Add(subm, androidMethod);
}
else//must be implementing an interface
{
androidMethod = FindInterfaceForMethod(subm);
if (androidMethod != null)
{
if (!interfaces.Contains(androidMethod.DeclaringType))
interfaces.Add(androidMethod.DeclaringType);
methods.Add(subm, androidMethod);
}
}
}
}
if (methods.Count > 0)
{
StringBuilder linkMethods = new StringBuilder(), natives = new StringBuilder();
//get the link methods
KeyValuePair<MethodInfo, MethodInfo>? first = null;
foreach (KeyValuePair<MethodInfo, MethodInfo> pair in methods)
{
if (first == null)
first = pair;
StringBuilder args = new StringBuilder(), jniArgs = new StringBuilder();
ParameterInfo[] paramInfo = null;
foreach (ParameterInfo p in paramInfo = pair.Key.GetParameters())
jniArgs.Append(GetJType(p.ParameterType, true, true));
for (int i = 0; i < paramInfo.Length; i++)
{
args.Append(paramInfo[i].ParameterType.FullName);
if (i < paramInfo.Length - 1)
args.Append(",");
}
linkMethods.AppendLine(string.Format("\t\tMonoBridge.link({0}.class, \"{1}\", \"({2}){3}\", \"{4}\");",
t.Name, pair.Key.Name, jniArgs, GetJType(pair.Key.ReturnType, true, true), args));
args = new StringBuilder();//reuse var
for (int i = 0; i < paramInfo.Length; i++)
{
args.AppendFormat("{0} {1}", paramInfo[i].ParameterType.FullName, paramInfo[i].Name);
if (i < paramInfo.Length - 1)
args.Append(",");
}
natives.AppendLine("\t@Override");
natives.AppendLine(string.Format("\t{0} native {1} {2}({3});",
pair.Key.IsPublic ? "public" : "protected", GetJLangType(pair.Value.ReturnType), pair.Key.Name, args));
}
string basePath = mOutputPath ?? Path.GetDirectoryName(t.Assembly.Location);
basePath = Path.Combine(basePath, t.Namespace.Replace('.', Path.DirectorySeparatorChar));
Directory.CreateDirectory(basePath);
string outputFile = Path.Combine(basePath, t.Name + ".java");
ret.Add(outputFile);
StringBuilder interfacesText = new StringBuilder();
if (interfaces.Count > 0)
{
foreach (var iface in interfaces)
{
interfacesText.AppendFormat(", {0}", iface.FullName.Replace('+', '.'));
}
}
File.WriteAllText(outputFile,
string.Format(mTemplate, t.Namespace, t.Name, " extends ", t.BaseType, linkMethods, natives, interfacesText.ToString()));
}
}
}
return ret.ToArray();
}
private MethodInfo FindBaseForMethod(MethodInfo sub, Type currentSuper)
{
if (currentSuper == null)
return FindBaseForMethod(sub, sub.DeclaringType.BaseType);
MethodInfo sup = currentSuper.GetMethod(sub.Name, BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public,
null, sub.GetParameters().Select(x => x.ParameterType).ToArray(), null);
if (sup != null)
{
foreach (var attrib in currentSuper.GetCustomAttributes(false))
{
if (attrib.GetType().FullName == "net.sf.jni4net.attributes.JavaClassAttribute")
return sup;
}
}
return currentSuper.BaseType != null ? FindBaseForMethod(sub, currentSuper.BaseType) : null;
}
private MethodInfo FindInterfaceForMethod(MethodInfo sub)
{
foreach (Type t in sub.DeclaringType.GetInterfaces())
{
MethodInfo sup = t.GetMethod(sub.Name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public,
null, sub.GetParameters().Select(x => x.ParameterType).ToArray(), null);
if (sup != null)
{
foreach (var attrib in t.GetCustomAttributes(false))
{
if (attrib.GetType().FullName == "net.sf.jni4net.attributes.JavaInterfaceAttribute")
{
Console.WriteLine("Match: {0}", sup);
return sup;
}
}
}
}
return null;
}
private string GetJType(Type type, bool replace, bool jniClasses)
{
string value = string.Empty;
if (type == typeof(bool))
value = "Z";
else if (type == typeof(byte))
value = "B";
else if (type == typeof(char))
value = "C";
else if (type == typeof(short))
value = "S";
else if (type == typeof(int))
value = "I";
else if (type == typeof(long))
value = "J";
else if (type == typeof(float))
value = "F";
else if (type == typeof(double))
value = "D";
else if (type == typeof(void))
value = "V";
else
value = jniClasses ? "L" + type.FullName + ";" : type.FullName;
if (type.IsArray)
value = "[" + value;
return replace ? value.Replace('.', '/') : value;
}
private string GetJLangType(Type type)
{
switch (type.FullName)
{
case "System.Boolean":
return "bool";
case "System.Byte":
return "byte";
case "System.Char":
return "char";
case "System.Int16":
return "short";
case "System.Int32":
return "int";
case "System.Int64":
return "long";
case "System.Single":
return "float";
case "System.Double":
return "double";
case "System.Void":
return "void";
default:
return type.FullName;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.DataAnnotations
{
/// <summary>
/// An implementation of <see cref="IBindingMetadataProvider"/> and <see cref="IDisplayMetadataProvider"/> for
/// the System.ComponentModel.DataAnnotations attribute classes.
/// </summary>
internal class DataAnnotationsMetadataProvider :
IBindingMetadataProvider,
IDisplayMetadataProvider,
IValidationMetadataProvider
{
// The [Nullable] attribute is synthesized by the compiler. It's best to just compare the type name.
private const string NullableAttributeFullTypeName = "System.Runtime.CompilerServices.NullableAttribute";
private const string NullableFlagsFieldName = "NullableFlags";
private const string NullableContextAttributeFullName = "System.Runtime.CompilerServices.NullableContextAttribute";
private const string NullableContextFlagsFieldName = "Flag";
private readonly IStringLocalizerFactory? _stringLocalizerFactory;
private readonly MvcOptions _options;
private readonly MvcDataAnnotationsLocalizationOptions _localizationOptions;
public DataAnnotationsMetadataProvider(
MvcOptions options,
IOptions<MvcDataAnnotationsLocalizationOptions> localizationOptions,
IStringLocalizerFactory? stringLocalizerFactory)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (localizationOptions == null)
{
throw new ArgumentNullException(nameof(localizationOptions));
}
_options = options;
_localizationOptions = localizationOptions.Value;
_stringLocalizerFactory = stringLocalizerFactory;
}
/// <inheritdoc />
public void CreateBindingMetadata(BindingMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var editableAttribute = context.Attributes.OfType<EditableAttribute>().FirstOrDefault();
if (editableAttribute != null)
{
context.BindingMetadata.IsReadOnly = !editableAttribute.AllowEdit;
}
}
/// <inheritdoc />
public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var attributes = context.Attributes;
var dataTypeAttribute = attributes.OfType<DataTypeAttribute>().FirstOrDefault();
var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();
var displayColumnAttribute = attributes.OfType<DisplayColumnAttribute>().FirstOrDefault();
var displayFormatAttribute = attributes.OfType<DisplayFormatAttribute>().FirstOrDefault();
var displayNameAttribute = attributes.OfType<DisplayNameAttribute>().FirstOrDefault();
var hiddenInputAttribute = attributes.OfType<HiddenInputAttribute>().FirstOrDefault();
var scaffoldColumnAttribute = attributes.OfType<ScaffoldColumnAttribute>().FirstOrDefault();
var uiHintAttribute = attributes.OfType<UIHintAttribute>().FirstOrDefault();
// Special case the [DisplayFormat] attribute hanging off an applied [DataType] attribute. This property is
// non-null for DataType.Currency, DataType.Date, DataType.Time, and potentially custom [DataType]
// subclasses. The DataType.Currency, DataType.Date, and DataType.Time [DisplayFormat] attributes have a
// non-null DataFormatString and the DataType.Date and DataType.Time [DisplayFormat] attributes have
// ApplyFormatInEditMode==true.
if (displayFormatAttribute == null && dataTypeAttribute != null)
{
displayFormatAttribute = dataTypeAttribute.DisplayFormat;
}
var displayMetadata = context.DisplayMetadata;
// ConvertEmptyStringToNull
if (displayFormatAttribute != null)
{
displayMetadata.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull;
}
// DataTypeName
if (dataTypeAttribute != null)
{
displayMetadata.DataTypeName = dataTypeAttribute.GetDataTypeName();
}
else if (displayFormatAttribute != null && !displayFormatAttribute.HtmlEncode)
{
displayMetadata.DataTypeName = nameof(DataType.Html);
}
var containerType = context.Key.ContainerType ?? context.Key.ModelType;
IStringLocalizer? localizer = null;
if (_stringLocalizerFactory != null && _localizationOptions.DataAnnotationLocalizerProvider != null)
{
localizer = _localizationOptions.DataAnnotationLocalizerProvider(containerType, _stringLocalizerFactory);
}
// Description
if (displayAttribute != null)
{
if (localizer != null &&
!string.IsNullOrEmpty(displayAttribute.Description) &&
displayAttribute.ResourceType == null)
{
displayMetadata.Description = () => localizer[displayAttribute.Description];
}
else
{
displayMetadata.Description = () => displayAttribute.GetDescription();
}
}
// DisplayFormatString
if (displayFormatAttribute != null)
{
displayMetadata.DisplayFormatString = displayFormatAttribute.DataFormatString;
}
// DisplayName
// DisplayAttribute has precedence over DisplayNameAttribute.
if (displayAttribute?.GetName() != null)
{
if (localizer != null &&
!string.IsNullOrEmpty(displayAttribute.Name) &&
displayAttribute.ResourceType == null)
{
displayMetadata.DisplayName = () => localizer[displayAttribute.Name];
}
else
{
displayMetadata.DisplayName = () => displayAttribute.GetName();
}
}
else if (displayNameAttribute != null)
{
if (localizer != null &&
!string.IsNullOrEmpty(displayNameAttribute.DisplayName))
{
displayMetadata.DisplayName = () => localizer[displayNameAttribute.DisplayName];
}
else
{
displayMetadata.DisplayName = () => displayNameAttribute.DisplayName;
}
}
// EditFormatString
if (displayFormatAttribute != null && displayFormatAttribute.ApplyFormatInEditMode)
{
displayMetadata.EditFormatString = displayFormatAttribute.DataFormatString;
}
// IsEnum et cetera
var underlyingType = Nullable.GetUnderlyingType(context.Key.ModelType) ?? context.Key.ModelType;
if (underlyingType.IsEnum)
{
// IsEnum
displayMetadata.IsEnum = true;
// IsFlagsEnum
displayMetadata.IsFlagsEnum = underlyingType.IsDefined(typeof(FlagsAttribute), inherit: false);
// EnumDisplayNamesAndValues and EnumNamesAndValues
//
// Order EnumDisplayNamesAndValues by DisplayAttribute.Order, then by the order of Enum.GetNames().
// That method orders by absolute value, then its behavior is undefined (but hopefully stable).
// Add to EnumNamesAndValues in same order but Dictionary does not guarantee order will be preserved.
var groupedDisplayNamesAndValues = new List<KeyValuePair<EnumGroupAndName, string>>();
var namesAndValues = new Dictionary<string, string>();
IStringLocalizer? enumLocalizer = null;
if (_stringLocalizerFactory != null && _localizationOptions.DataAnnotationLocalizerProvider != null)
{
enumLocalizer = _localizationOptions.DataAnnotationLocalizerProvider(underlyingType, _stringLocalizerFactory);
}
var enumFields = Enum.GetNames(underlyingType)
.Select(name => underlyingType.GetField(name)!)
.OrderBy(field => field.GetCustomAttribute<DisplayAttribute>(inherit: false)?.GetOrder() ?? 1000);
foreach (var field in enumFields)
{
var groupName = GetDisplayGroup(field);
var value = ((Enum)field.GetValue(obj: null)!).ToString("d");
groupedDisplayNamesAndValues.Add(new KeyValuePair<EnumGroupAndName, string>(
new EnumGroupAndName(
groupName,
() => GetDisplayName(field, enumLocalizer)),
value));
namesAndValues.Add(field.Name, value);
}
displayMetadata.EnumGroupedDisplayNamesAndValues = groupedDisplayNamesAndValues;
displayMetadata.EnumNamesAndValues = namesAndValues;
}
// HasNonDefaultEditFormat
if (!string.IsNullOrEmpty(displayFormatAttribute?.DataFormatString) &&
displayFormatAttribute?.ApplyFormatInEditMode == true)
{
// Have a non-empty EditFormatString based on [DisplayFormat] from our cache.
if (dataTypeAttribute == null)
{
// Attributes include no [DataType]; [DisplayFormat] was applied directly.
displayMetadata.HasNonDefaultEditFormat = true;
}
else if (dataTypeAttribute.DisplayFormat != displayFormatAttribute)
{
// Attributes include separate [DataType] and [DisplayFormat]; [DisplayFormat] provided override.
displayMetadata.HasNonDefaultEditFormat = true;
}
else if (dataTypeAttribute.GetType() != typeof(DataTypeAttribute))
{
// Attributes include [DisplayFormat] copied from [DataType] and [DataType] was of a subclass.
// Assume the [DataType] constructor used the protected DisplayFormat setter to override its
// default. That is derived [DataType] provided override.
displayMetadata.HasNonDefaultEditFormat = true;
}
}
// HideSurroundingHtml
if (hiddenInputAttribute != null)
{
displayMetadata.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue;
}
// HtmlEncode
if (displayFormatAttribute != null)
{
displayMetadata.HtmlEncode = displayFormatAttribute.HtmlEncode;
}
// NullDisplayText
if (displayFormatAttribute != null)
{
displayMetadata.NullDisplayText = displayFormatAttribute.NullDisplayText;
}
// Order
if (displayAttribute?.GetOrder() is int order)
{
displayMetadata.Order = order;
}
// Placeholder
if (displayAttribute != null)
{
if (localizer != null &&
!string.IsNullOrEmpty(displayAttribute.Prompt) &&
displayAttribute.ResourceType == null)
{
displayMetadata.Placeholder = () => localizer[displayAttribute.Prompt];
}
else
{
displayMetadata.Placeholder = () => displayAttribute.GetPrompt();
}
}
// ShowForDisplay
if (scaffoldColumnAttribute != null)
{
displayMetadata.ShowForDisplay = scaffoldColumnAttribute.Scaffold;
}
// ShowForEdit
if (scaffoldColumnAttribute != null)
{
displayMetadata.ShowForEdit = scaffoldColumnAttribute.Scaffold;
}
// SimpleDisplayProperty
if (displayColumnAttribute != null)
{
displayMetadata.SimpleDisplayProperty = displayColumnAttribute.DisplayColumn;
}
// TemplateHint
if (uiHintAttribute != null)
{
displayMetadata.TemplateHint = uiHintAttribute.UIHint;
}
else if (hiddenInputAttribute != null)
{
displayMetadata.TemplateHint = "HiddenInput";
}
}
/// <inheritdoc />
public void CreateValidationMetadata(ValidationMetadataProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Read interface .Count once rather than per iteration
var contextAttributes = context.Attributes;
var contextAttributesCount = contextAttributes.Count;
var attributes = new List<object>(contextAttributesCount);
for (var i = 0; i < contextAttributesCount; i++)
{
var attribute = contextAttributes[i];
if (attribute is ValidationProviderAttribute validationProviderAttribute)
{
attributes.AddRange(validationProviderAttribute.GetValidationAttributes());
}
else
{
attributes.Add(attribute);
}
}
// RequiredAttribute marks a property as required by validation - this means that it
// must have a non-null value on the model during validation.
var requiredAttribute = attributes.OfType<RequiredAttribute>().FirstOrDefault();
// For non-nullable reference types, treat them as-if they had an implicit [Required].
// This allows the developer to specify [Required] to customize the error message, so
// if they already have [Required] then there's no need for us to do this check.
if (!_options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes &&
requiredAttribute == null &&
!context.Key.ModelType.IsValueType &&
context.Key.MetadataKind != ModelMetadataKind.Type)
{
var addInferredRequiredAttribute = false;
if (context.Key.MetadataKind == ModelMetadataKind.Type)
{
// Do nothing.
}
else if (context.Key.MetadataKind == ModelMetadataKind.Property)
{
var property = context.Key.PropertyInfo;
if (property is null)
{
// PropertyInfo was unavailable on ModelIdentity prior to 3.1.
// Making a cogent argument about the nullability of the property requires inspecting the declared type,
// since looking at the runtime type may result in false positives: https://github.com/dotnet/aspnetcore/issues/14812
// The only way we could arrive here is if the ModelMetadata was constructed using the non-default provider.
// We'll cursorily examine the attributes on the property, but not the ContainerType to make a decision about it's nullability.
if (HasNullableAttribute(context.PropertyAttributes!, out var propertyHasNullableAttribute))
{
addInferredRequiredAttribute = propertyHasNullableAttribute;
}
}
else
{
addInferredRequiredAttribute = IsNullableReferenceType(
property.DeclaringType!,
member: null,
context.PropertyAttributes!);
}
}
else if (context.Key.MetadataKind == ModelMetadataKind.Parameter)
{
addInferredRequiredAttribute = IsNullableReferenceType(
context.Key.ParameterInfo!.Member.ReflectedType,
context.Key.ParameterInfo.Member,
context.ParameterAttributes!);
}
else
{
throw new InvalidOperationException("Unsupported ModelMetadataKind: " + context.Key.MetadataKind);
}
if (addInferredRequiredAttribute)
{
// Since this behavior specifically relates to non-null-ness, we will use the non-default
// option to tolerate empty/whitespace strings. empty/whitespace INPUT will still result in
// a validation error by default because we convert empty/whitespace strings to null
// unless you say otherwise.
requiredAttribute = new RequiredAttribute()
{
AllowEmptyStrings = true,
};
attributes.Add(requiredAttribute);
}
}
if (requiredAttribute != null)
{
context.ValidationMetadata.IsRequired = true;
}
foreach (var attribute in attributes.OfType<ValidationAttribute>())
{
// If another provider has already added this attribute, do not repeat it.
// This will prevent attributes like RemoteAttribute (which implement ValidationAttribute and
// IClientModelValidator) to be added to the ValidationMetadata twice.
// This is to ensure we do not end up with duplication validation rules on the client side.
if (!context.ValidationMetadata.ValidatorMetadata.Contains(attribute))
{
context.ValidationMetadata.ValidatorMetadata.Add(attribute);
}
}
}
private static string GetDisplayName(FieldInfo field, IStringLocalizer? stringLocalizer)
{
var display = field.GetCustomAttribute<DisplayAttribute>(inherit: false);
if (display != null)
{
// Note [Display(Name = "")] is allowed but we will not attempt to localize the empty name.
var name = display.GetName();
if (stringLocalizer != null && !string.IsNullOrEmpty(name) && display.ResourceType == null)
{
name = stringLocalizer[name];
}
return name ?? field.Name;
}
return field.Name;
}
// Return non-empty group specified in a [Display] attribute for a field, if any; string.Empty otherwise.
private static string GetDisplayGroup(FieldInfo field)
{
var display = field.GetCustomAttribute<DisplayAttribute>(inherit: false);
if (display != null)
{
// Note [Display(Group = "")] is allowed.
var group = display.GetGroupName();
if (group != null)
{
return group;
}
}
return string.Empty;
}
internal static bool IsNullableReferenceType(Type? containingType, MemberInfo? member, IEnumerable<object> attributes)
{
if (HasNullableAttribute(attributes, out var result))
{
return result;
}
return IsNullableBasedOnContext(containingType, member);
}
// Internal for testing
internal static bool HasNullableAttribute(IEnumerable<object> attributes, out bool isNullable)
{
// [Nullable] is compiler synthesized, comparing by name.
var nullableAttribute = attributes
.FirstOrDefault(a => string.Equals(a.GetType().FullName, NullableAttributeFullTypeName, StringComparison.Ordinal));
if (nullableAttribute == null)
{
isNullable = false;
return false; // [Nullable] not found
}
// We don't handle cases where generics and NNRT are used. This runs into a
// fundamental limitation of ModelMetadata - we use a single Type and Property/Parameter
// to look up the metadata. However when generics are involved and NNRT is in use
// the distance between the [Nullable] and member we're looking at is potentially
// unbounded.
//
// See: https://github.com/dotnet/roslyn/blob/master/docs/features/nullable-reference-types.md#annotations
if (nullableAttribute.GetType().GetField(NullableFlagsFieldName) is FieldInfo field &&
field.GetValue(nullableAttribute) is byte[] flags &&
flags.Length > 0 &&
flags[0] == 1) // First element is the property/parameter type.
{
isNullable = true;
return true; // [Nullable] found and type is an NNRT
}
isNullable = false;
return true; // [Nullable] found but type is not an NNRT
}
internal static bool IsNullableBasedOnContext(Type? containingType, MemberInfo? member)
{
if (containingType is null)
{
return false;
}
// For generic types, inspecting the nullability requirement additionally requires
// inspecting the nullability constraint on generic type parameters. This is fairly non-triviial
// so we'll just avoid calculating it. Users should still be able to apply an explicit [Required]
// attribute on these members.
if (containingType.IsGenericType)
{
return false;
}
// The [Nullable] and [NullableContext] attributes are not inherited.
//
// The [NullableContext] attribute can appear on a method or on the module.
var attributes = member?.GetCustomAttributes(inherit: false) ?? Array.Empty<object>();
var isNullable = AttributesHasNullableContext(attributes);
if (isNullable != null)
{
return isNullable.Value;
}
// Check on the containing type
var type = containingType;
do
{
attributes = type.GetCustomAttributes(inherit: false);
isNullable = AttributesHasNullableContext(attributes);
if (isNullable != null)
{
return isNullable.Value;
}
type = type.DeclaringType;
}
while (type != null);
// If we don't find the attribute on the declaring type then repeat at the module level
attributes = containingType.Module.GetCustomAttributes(inherit: false);
isNullable = AttributesHasNullableContext(attributes);
return isNullable ?? false;
bool? AttributesHasNullableContext(object[] attributes)
{
var nullableContextAttribute = attributes
.FirstOrDefault(a => string.Equals(a.GetType().FullName, NullableContextAttributeFullName, StringComparison.Ordinal));
if (nullableContextAttribute != null)
{
if (nullableContextAttribute.GetType().GetField(NullableContextFlagsFieldName) is FieldInfo field &&
field.GetValue(nullableContextAttribute) is byte @byte)
{
return @byte == 1; // [NullableContext] found
}
}
return null;
}
}
}
}
| |
/*
* Copyright (c) 2007-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;
namespace OpenMetaverse
{
/// <summary>
/// The InternalDictionary class is used through the library for storing key/value pairs.
/// It is intended to be a replacement for the generic Dictionary class and should
/// be used in its place. It contains several methods for allowing access to the data from
/// outside the library that are read only and thread safe.
///
/// </summary>
/// <typeparam name="TKey">Key <see langword="Tkey"/></typeparam>
/// <typeparam name="TValue">Value <see langword="TValue"/></typeparam>
public class InternalDictionary<TKey, TValue>
{
/// <summary>Internal dictionary that this class wraps around. Do not
/// modify or enumerate the contents of this dictionary without locking</summary>
public Dictionary<TKey, TValue> Dictionary;
/// <summary>
/// Gets the number of Key/Value pairs contained in the <seealso cref="T:InternalDictionary"/>
/// </summary>
public int Count { get { return Dictionary.Count; } }
/// <summary>
/// Initializes a new instance of the <seealso cref="T:InternalDictionary"/> Class
/// with the specified key/value, has the default initial capacity.
/// </summary>
/// <example>
/// <code>
/// // initialize a new InternalDictionary named testDict with a string as the key and an int as the value.
/// public InternalDictionary<string, int> testDict = new InternalDictionary<string, int>();
/// </code>
/// </example>
public InternalDictionary()
{
Dictionary = new Dictionary<TKey, TValue>();
}
/// <summary>
/// Initializes a new instance of the <seealso cref="T:InternalDictionary"/> Class
/// with the specified key/value, has its initial valies copied from the specified
/// <seealso cref="T:System.Collections.Generic.Dictionary"/>
/// </summary>
/// <param name="dictionary"><seealso cref="T:System.Collections.Generic.Dictionary"/>
/// to copy initial values from</param>
/// <example>
/// <code>
/// // initialize a new InternalDictionary named testAvName with a UUID as the key and an string as the value.
/// // populates with copied values from example KeyNameCache Dictionary.
///
/// // create source dictionary
/// Dictionary<UUID, string> KeyNameCache = new Dictionary<UUID, string>();
/// KeyNameCache.Add("8300f94a-7970-7810-cf2c-fc9aa6cdda24", "Jack Avatar");
/// KeyNameCache.Add("27ba1e40-13f7-0708-3e98-5819d780bd62", "Jill Avatar");
///
/// // Initialize new dictionary.
/// public InternalDictionary<UUID, string> testAvName = new InternalDictionary<UUID, string>(KeyNameCache);
/// </code>
/// </example>
public InternalDictionary(IDictionary<TKey, TValue> dictionary)
{
Dictionary = new Dictionary<TKey, TValue>(dictionary);
}
/// <summary>
/// Initializes a new instance of the <seealso cref="T:OpenMetaverse.InternalDictionary"/> Class
/// with the specified key/value, With its initial capacity specified.
/// </summary>
/// <param name="capacity">Initial size of dictionary</param>
/// <example>
/// <code>
/// // initialize a new InternalDictionary named testDict with a string as the key and an int as the value,
/// // initially allocated room for 10 entries.
/// public InternalDictionary<string, int> testDict = new InternalDictionary<string, int>(10);
/// </code>
/// </example>
public InternalDictionary(int capacity)
{
Dictionary = new Dictionary<TKey, TValue>(capacity);
}
/// <summary>
/// Try to get entry from <seealso cref="T:OpenMetaverse.InternalDictionary"/> with specified key
/// </summary>
/// <param name="key">Key to use for lookup</param>
/// <param name="value">Value returned</param>
/// <returns><see langword="true"/> if specified key exists, <see langword="false"/> if not found</returns>
/// <example>
/// <code>
/// // find your avatar using the Simulator.ObjectsAvatars InternalDictionary:
/// Avatar av;
/// if (Client.Network.CurrentSim.ObjectsAvatars.TryGetValue(Client.Self.AgentID, out av))
/// Console.WriteLine("Found Avatar {0}", av.Name);
/// </code>
/// <seealso cref="Simulator.ObjectsAvatars"/>
/// </example>
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Finds the specified match.
/// </summary>
/// <param name="match">The match.</param>
/// <returns>Matched value</returns>
/// <example>
/// <code>
/// // use a delegate to find a prim in the ObjectsPrimitives InternalDictionary
/// // with the ID 95683496
/// uint findID = 95683496;
/// Primitive findPrim = sim.ObjectsPrimitives.Find(
/// delegate(Primitive prim) { return prim.ID == findID; });
/// </code>
/// </example>
public TValue Find(Predicate<TValue> match)
{
lock (Dictionary)
{
foreach (TValue value in Dictionary.Values)
{
if (match(value))
return value;
}
}
return default(TValue);
}
/// <summary>Find All items in an <seealso cref="T:InternalDictionary"/></summary>
/// <param name="match">return matching items.</param>
/// <returns>a <seealso cref="T:System.Collections.Generic.List"/> containing found items.</returns>
/// <example>
/// Find All prims within 20 meters and store them in a List
/// <code>
/// int radius = 20;
/// List<Primitive> prims = Client.Network.CurrentSim.ObjectsPrimitives.FindAll(
/// delegate(Primitive prim) {
/// Vector3 pos = prim.Position;
/// return ((prim.ParentID == 0) && (pos != Vector3.Zero) && (Vector3.Distance(pos, location) < radius));
/// }
/// );
///</code>
///</example>
public List<TValue> FindAll(Predicate<TValue> match)
{
List<TValue> found = new List<TValue>();
lock (Dictionary)
{
foreach (KeyValuePair<TKey, TValue> kvp in Dictionary)
{
if (match(kvp.Value))
found.Add(kvp.Value);
}
}
return found;
}
/// <summary>Perform an <seealso cref="T:System.Action"/> on each entry in an <seealso cref="T:OpenMetaverse.InternalDictionary"/></summary>
/// <param name="action"><seealso cref="T:System.Action"/> to perform</param>
/// <example>
/// <code>
/// // Iterates over the ObjectsPrimitives InternalDictionary and prints out some information.
/// Client.Network.CurrentSim.ObjectsPrimitives.ForEach(
/// delegate(Primitive prim)
/// {
/// if (prim.Text != null)
/// {
/// Console.WriteLine("NAME={0} ID = {1} TEXT = '{2}'",
/// prim.PropertiesFamily.Name, prim.ID, prim.Text);
/// }
/// });
///</code>
///</example>
public void ForEach(Action<TValue> action)
{
lock (Dictionary)
{
foreach (TValue value in Dictionary.Values)
{
action(value);
}
}
}
/// <summary>Perform an <seealso cref="T:System.Action"/> on each key of an <seealso cref="T:OpenMetaverse.InternalDictionary"/></summary>
/// <param name="action"><seealso cref="T:System.Action"/> to perform</param>
public void ForEach(Action<TKey> action)
{
lock (Dictionary)
{
foreach (TKey key in Dictionary.Keys)
{
action(key);
}
}
}
/// <summary>Check if Key exists in Dictionary</summary>
/// <param name="key">Key to check for</param>
/// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns>
public bool ContainsKey(TKey key)
{
lock(Dictionary)
return Dictionary.ContainsKey(key);
}
/// <summary>Check if Value exists in Dictionary</summary>
/// <param name="value">Value to check for</param>
/// <returns><see langword="true"/> if found, <see langword="false"/> otherwise</returns>
public bool ContainsValue(TValue value)
{
lock(Dictionary)
return Dictionary.ContainsValue(value);
}
/// <summary>
/// Adds the specified key to the dictionary, dictionary locking is not performed,
/// <see cref="SafeAdd"/>
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
internal void Add(TKey key, TValue value)
{
Dictionary.Add(key, value);
}
/// <summary>
/// Removes the specified key, dictionary locking is not performed
/// </summary>
/// <param name="key">The key.</param>
/// <returns><see langword="true"/> if successful, <see langword="false"/> otherwise</returns>
internal bool Remove(TKey key)
{
return Dictionary.Remove(key);
}
/// <summary>
/// Safely add a key/value pair to the dictionary
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
internal void SafeAdd(TKey key, TValue value)
{
lock (Dictionary)
Dictionary.Add(key, value);
}
/// <summary>
/// Safely Removes an item from the InternalDictionary
/// </summary>
/// <param name="key">The key</param>
/// <returns><see langword="true"/> if successful, <see langword="false"/> otherwise</returns>
internal bool SafeRemove(TKey key)
{
lock (Dictionary)
return Dictionary.Remove(key);
}
/// <summary>
/// Indexer for the dictionary
/// </summary>
/// <param name="key">The key</param>
/// <returns>The value</returns>
internal TValue this[TKey key]
{
get { return Dictionary[key]; }
set { Dictionary[key] = value; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Protocols
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
[Reader(typeof(SimpleJsonReader))]
public struct SimpleJsonWriter : IProtocolWriter
{
public const string NameAttribute = "JsonName";
readonly JsonTextWriter writer;
public SimpleJsonWriter(TextWriter writer)
{
this.writer = new JsonTextWriter(writer);
}
public SimpleJsonWriter(Stream stream)
{
writer = new JsonTextWriter(new StreamWriter(stream));
}
public void Flush()
{
writer.Flush();
}
#region IProtocolWriter
public void WriteVersion()
{
throw new NotImplementedException();
}
#region Struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructBegin(Metadata metadata)
{
writer.WriteStartObject();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructEnd()
{
writer.WriteEndObject();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseBegin(Metadata metadata)
{}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseEnd()
{}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata)
{
string name;
writer.WritePropertyName(metadata.attributes.TryGetValue(NameAttribute, out name) ? name : metadata.name);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldEnd()
{}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldOmitted(BondDataType type, ushort id, Metadata metadata)
{}
#endregion
#region Containers
public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType)
{
writer.WriteStartArray();
}
public void WriteContainerBegin(int count, BondDataType elementType)
{
writer.WriteStartArray();
}
public void WriteContainerEnd()
{
writer.WriteEndArray();
}
#endregion
#region Scalars
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBool(bool value)
{
writer.WriteValue(value);
}
public void WriteBytes(ArraySegment<byte> data)
{
var end = data.Offset + data.Count;
for (var i = data.Offset; i != end; ++i)
{
writer.WriteValue((sbyte) data.Array[i]);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteDouble(double value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFloat(float value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt16(short value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt32(int value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt64(long value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt8(sbyte value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt16(ushort value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt32(uint value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt64(ulong value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt8(byte value)
{
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteString(string value)
{
// Other protocols depend on expressions such as value.Count to
// throw an NRE if we've been asked to serialize a non-nullable
// string field that is set to null. Newtonsoft.Json will
// successfully serialize it as a JSON null (the unquoted text
// null), so we need to check and throw explicitly before that.
if (value == null)
{
throw new NullReferenceException(
"Attempted to serialize a null string. This may indicate a non-nullable string field that was set to null.");
}
writer.WriteValue(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteWString(string value)
{
// Other protocols depend on expressions such as value.Count to
// throw an NRE if we've been asked to serialize a non-nullable
// string field that is set to null. Newtonsoft.Json will
// successfully serialize it as a JSON null (the unquoted text
// null), so we need to check and throw explicitly before that.
if (value == null)
{
throw new NullReferenceException(
"Attempted to serialize a null string. This may indicate a non-nullable string field that was set to null.");
}
writer.WriteValue(value);
}
#endregion
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Web;
using System.Web.UI;
using Umbraco.Core;
using Umbraco.Core.Configuration;
namespace umbraco.BusinessLogic
{
/// <summary>
/// The StateHelper class provides general helper methods for handling sessions, context, viewstate and cookies.
/// </summary>
[Obsolete("DO NOT USE THIS ANYMORE! REPLACE ALL CALLS WITH NEW EXTENSION METHODS")]
public class StateHelper
{
private static HttpContextBase _customHttpContext;
/// <summary>
/// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will
/// use the HttpContext.Current
/// </summary>
internal static HttpContextBase HttpContext
{
get
{
if (_customHttpContext == null && System.Web.HttpContext.Current != null)
{
//return the current HttpContxt, do NOT store this in the _customHttpContext field
//as it will persist across reqeusts!
return new HttpContextWrapper(System.Web.HttpContext.Current);
}
if (_customHttpContext == null && System.Web.HttpContext.Current == null)
{
throw new NullReferenceException("The HttpContext property has not been set or the object execution is not running inside of an HttpContext");
}
return _customHttpContext;
}
set { _customHttpContext = value; }
}
#region Session Helpers
/// <summary>
/// Gets the session value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T GetSessionValue<T>(string key)
{
return GetSessionValue<T>(HttpContext, key);
}
/// <summary>
/// Gets the session value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
[Obsolete("Use the GetSessionValue accepting an HttpContextBase instead")]
public static T GetSessionValue<T>(HttpContext context, string key)
{
return GetSessionValue<T>(new HttpContextWrapper(context), key);
}
/// <summary>
/// Gets the session value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T GetSessionValue<T>(HttpContextBase context, string key)
{
if (context == null)
return default(T);
object o = context.Session[key];
if (o == null)
return default(T);
return (T)o;
}
/// <summary>
/// Sets a session value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetSessionValue(string key, object value)
{
SetSessionValue(HttpContext, key, value);
}
/// <summary>
/// Sets the session value.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
[Obsolete("Use the SetSessionValue accepting an HttpContextBase instead")]
public static void SetSessionValue(HttpContext context, string key, object value)
{
SetSessionValue(new HttpContextWrapper(context), key, value);
}
/// <summary>
/// Sets the session value.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetSessionValue(HttpContextBase context, string key, object value)
{
if (context == null)
return;
context.Session[key] = value;
}
#endregion
#region Context Helpers
/// <summary>
/// Gets the context value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T GetContextValue<T>(string key)
{
return GetContextValue<T>(HttpContext, key);
}
/// <summary>
/// Gets the context value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
[Obsolete("Use the GetContextValue accepting an HttpContextBase instead")]
public static T GetContextValue<T>(HttpContext context, string key)
{
return GetContextValue<T>(new HttpContextWrapper(context), key);
}
/// <summary>
/// Gets the context value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T GetContextValue<T>(HttpContextBase context, string key)
{
if (context == null)
return default(T);
object o = context.Items[key];
if (o == null)
return default(T);
return (T)o;
}
/// <summary>
/// Sets the context value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetContextValue(string key, object value)
{
SetContextValue(HttpContext, key, value);
}
/// <summary>
/// Sets the context value.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
[Obsolete("Use the SetContextValue accepting an HttpContextBase instead")]
public static void SetContextValue(HttpContext context, string key, object value)
{
SetContextValue(new HttpContextWrapper(context), key, value);
}
/// <summary>
/// Sets the context value.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetContextValue(HttpContextBase context, string key, object value)
{
if (context == null)
return;
context.Items[key] = value;
}
#endregion
#region ViewState Helpers
/// <summary>
/// Gets the state bag.
/// </summary>
/// <returns></returns>
private static StateBag GetStateBag()
{
//if (HttpContext.Current == null)
// return null;
var page = HttpContext.CurrentHandler as Page;
if (page == null)
return null;
var pageType = typeof(Page);
var viewState = pageType.GetProperty("ViewState", BindingFlags.GetProperty | BindingFlags.Instance);
if (viewState == null)
return null;
return viewState.GetValue(page, null) as StateBag;
}
/// <summary>
/// Gets the view state value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T GetViewStateValue<T>(string key)
{
return GetViewStateValue<T>(GetStateBag(), key);
}
/// <summary>
/// Gets a view-state value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="bag">The bag.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public static T GetViewStateValue<T>(StateBag bag, string key)
{
if (bag == null)
return default(T);
object o = bag[key];
if (o == null)
return default(T);
return (T)o;
}
/// <summary>
/// Sets the view state value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetViewStateValue(string key, object value)
{
SetViewStateValue(GetStateBag(), key, value);
}
/// <summary>
/// Sets the view state value.
/// </summary>
/// <param name="bag">The bag.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetViewStateValue(StateBag bag, string key, object value)
{
if (bag != null)
bag[key] = value;
}
#endregion
#region Cookie Helpers
/// <summary>
/// Determines whether a cookie has a value with a specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if the cookie has a value with the specified key; otherwise, <c>false</c>.
/// </returns>
[Obsolete("Use !string.IsNullOrEmpty(GetCookieValue(key))", false)]
public static bool HasCookieValue(string key)
{
return !string.IsNullOrEmpty(GetCookieValue(key));
}
/// <summary>
/// Gets the cookie value.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public static string GetCookieValue(string key)
{
if (!Cookies.HasCookies)
return null;
var cookie = HttpContext.Request.Cookies[key];
return cookie == null ? null : cookie.Value;
}
/// <summary>
/// Sets the cookie value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void SetCookieValue(string key, string value)
{
SetCookieValue(key, value, 30d); // default Umbraco expires is 30 days
}
/// <summary>
/// Sets the cookie value including the number of days to persist the cookie
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="daysToPersist">How long the cookie should be present in the browser</param>
public static void SetCookieValue(string key, string value, double daysToPersist)
{
if (!Cookies.HasCookies)
return;
var context = HttpContext;
HttpCookie cookie = new HttpCookie(key, value);
cookie.Expires = DateTime.Now.AddDays(daysToPersist);
context.Response.Cookies.Set(cookie);
cookie = context.Request.Cookies[key];
if (cookie != null)
cookie.Value = value;
}
// zb-00004 #29956 : refactor cookies names & handling
public static class Cookies
{
/*
* helper class to manage cookies
*
* beware! SetValue(string value) does _not_ set expires, unless the cookie has been
* configured to have one. This allows us to have cookies w/out an expires timespan.
* However, default behavior in Umbraco was to set expires to 30days by default. This
* must now be managed in the Cookie constructor or by using an overriden SetValue(...).
*
* we currently reproduce this by configuring each cookie with a 30d expires, but does
* that actually make sense? shouldn't some cookie have _no_ expires?
*/
static readonly Cookie _preview = new Cookie(Constants.Web.PreviewCookieName, TimeSpan.Zero); // was "PreviewSet"
static readonly Cookie _userContext = new Cookie(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName, 30d); // was "UserContext"
static readonly Cookie _member = new Cookie("UMB_MEMBER", 30d); // was "umbracoMember"
public static Cookie Preview { get { return _preview; } }
public static Cookie UserContext { get { return _userContext; } }
public static Cookie Member { get { return _member; } }
public static bool HasCookies
{
get
{
var context = HttpContext;
// although just checking context should be enough?!
// but in some (replaced) umbraco code, everything is checked...
return context != null
&& context.Request != null & context.Request.Cookies != null
&& context.Response != null && context.Response.Cookies != null;
}
}
public static void ClearAll()
{
HttpContext.Response.Cookies.Clear();
}
public class Cookie
{
const string cookiesExtensionConfigKey = "umbracoCookiesExtension";
static readonly string _ext;
TimeSpan _expires;
string _key;
static Cookie()
{
var appSettings = System.Configuration.ConfigurationManager.AppSettings;
_ext = appSettings[cookiesExtensionConfigKey] == null ? "" : "_" + (string)appSettings[cookiesExtensionConfigKey];
}
public Cookie(string key)
: this(key, TimeSpan.Zero, true)
{ }
public Cookie(string key, double days)
: this(key, TimeSpan.FromDays(days), true)
{ }
public Cookie(string key, TimeSpan expires)
: this(key, expires, true)
{ }
public Cookie(string key, bool appendExtension)
: this(key, TimeSpan.Zero, appendExtension)
{ }
public Cookie(string key, double days, bool appendExtension)
: this(key, TimeSpan.FromDays(days), appendExtension)
{ }
public Cookie(string key, TimeSpan expires, bool appendExtension)
{
_key = appendExtension ? key + _ext : key;
_expires = expires;
}
public string Key
{
get { return _key; }
}
public bool HasValue
{
get { return RequestCookie != null; }
}
public string GetValue()
{
return RequestCookie == null ? null : RequestCookie.Value;
}
public void SetValue(string value)
{
SetValueWithDate(value, _expires == TimeSpan.Zero ? DateTime.MinValue : DateTime.Now + _expires);
}
public void SetValue(string value, double days)
{
SetValue(value, DateTime.Now.AddDays(days));
}
public void SetValue(string value, TimeSpan expires)
{
SetValue(value, expires == TimeSpan.Zero ? DateTime.MinValue : DateTime.Now + expires);
}
public void SetValue(string value, DateTime expires)
{
SetValueWithDate(value, expires);
}
private void SetValueWithDate(string value, DateTime expires)
{
var cookie = new HttpCookie(_key, value);
if (GlobalSettings.UseSSL)
cookie.Secure = true;
//ensure http only, this should only be able to be accessed via the server
cookie.HttpOnly = true;
//set an expiry date if not min value, otherwise leave it as a session cookie.
if (expires != DateTime.MinValue)
{
cookie.Expires = expires;
}
ResponseCookie = cookie;
// original Umbraco code also does this
// so we can GetValue() back what we previously set
cookie = RequestCookie;
if (cookie != null)
cookie.Value = value;
}
public void Clear()
{
if (RequestCookie != null || ResponseCookie != null)
{
var cookie = new HttpCookie(_key);
cookie.Expires = DateTime.Now.AddDays(-1);
ResponseCookie = cookie;
}
}
public void Remove()
{
// beware! will not clear browser's cookie
// you probably want to use .Clear()
HttpContext.Response.Cookies.Remove(_key);
}
public HttpCookie RequestCookie
{
get
{
return HttpContext.Request.Cookies[_key];
}
}
public HttpCookie ResponseCookie
{
get
{
return HttpContext.Response.Cookies[_key];
}
set
{
// .Set() ensures the uniqueness of cookies in the cookie collection
// ie it is the same as .Remove() + .Add() -- .Add() allows duplicates
HttpContext.Response.Cookies.Set(value);
}
}
}
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System.Text;
using System;
using NPOI.Util;
using System.Globalization;
/**
* NOTE: Comment Associated with a Cell (1Ch)
*
* @author Yegor Kozlov
*/
internal class NoteRecord : StandardRecord
{
public static NoteRecord[] EMPTY_ARRAY = { };
public const short sid = 0x1C;
/**
* Flag indicating that the comment Is hidden (default)
*/
public static short NOTE_HIDDEN = 0x0;
/**
* Flag indicating that the comment Is visible
*/
public static short NOTE_VISIBLE = 0x2;
private int field_1_row;
private int field_2_col;
private short field_3_flags;
private int field_4_shapeid;
private bool field_5_hasMultibyte;
private String field_6_author;
private const Byte DEFAULT_PADDING = (byte)0;
/**
* Saves padding byte value to reduce delta during round-trip serialization.<br/>
*
* The documentation is not clear about how padding should work. In any case
* Excel(2007) does something different.
*/
private Byte? field_7_padding;
/**
* Construct a new <c>NoteRecord</c> and
* Fill its data with the default values
*/
public NoteRecord()
{
field_6_author = "";
field_3_flags = 0;
field_7_padding = DEFAULT_PADDING; // seems to be always present regardless of author text
}
/**
* Constructs a <c>NoteRecord</c> and Fills its fields
* from the supplied <c>RecordInputStream</c>.
*
* @param in the stream to Read from
*/
public NoteRecord(RecordInputStream in1)
{
field_1_row = in1.ReadShort();
field_2_col = in1.ReadUShort();
field_3_flags = in1.ReadShort();
field_4_shapeid = in1.ReadUShort();
int length = in1.ReadShort();
field_5_hasMultibyte = in1.ReadByte() != 0x00;
if (field_5_hasMultibyte) {
field_6_author = StringUtil.ReadUnicodeLE(in1, length);
} else {
field_6_author = StringUtil.ReadCompressedUnicode(in1, length);
}
if (in1.Available() == 1) {
field_7_padding = (byte)in1.ReadByte();
}
}
/**
* @return id of this record.
*/
public override short Sid
{
get { return sid; }
}
/**
* Serialize the record data into the supplied array of bytes
*
* @param offset offset in the <c>data</c>
* @param data the data to Serialize into
*
* @return size of the record
*/
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_row);
out1.WriteShort(field_2_col);
out1.WriteShort(field_3_flags);
out1.WriteShort(field_4_shapeid);
out1.WriteShort(field_6_author.Length);
out1.WriteByte(field_5_hasMultibyte ? 0x01 : 0x00);
if (field_5_hasMultibyte) {
StringUtil.PutUnicodeLE(field_6_author, out1);
} else {
StringUtil.PutCompressedUnicode(field_6_author, out1);
}
if (field_7_padding != null) {
out1.WriteByte(Convert.ToInt32(field_7_padding, CultureInfo.InvariantCulture));
}
}
/**
* Size of record
*/
protected override int DataSize
{
get
{
return 11 // 5 shorts + 1 byte
+ field_6_author.Length * (field_5_hasMultibyte ? 2 : 1)
+ (field_7_padding == null ? 0 : 1);
}
}
/**
* Convert this record to string.
* Used by BiffViewer and other utulities.
*/
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[NOTE]\n");
buffer.Append(" .recordid = 0x" + StringUtil.ToHexString(Sid) + ", size = " + RecordSize + "\n");
buffer.Append(" .row = " + field_1_row + "\n");
buffer.Append(" .col = " + field_2_col + "\n");
buffer.Append(" .flags = " + field_3_flags + "\n");
buffer.Append(" .shapeid = " + field_4_shapeid + "\n");
buffer.Append(" .author = " + field_6_author + "\n");
buffer.Append("[/NOTE]\n");
return buffer.ToString();
}
/**
* Return the row that Contains the comment
*
* @return the row that Contains the comment
*/
public int Row
{
get{return field_1_row;}
set{ field_1_row = value;}
}
/**
* Return the column that Contains the comment
*
* @return the column that Contains the comment
*/
public int Column
{
get { return field_2_col; }
set { field_2_col = value; }
}
/**
* Options flags.
*
* @return the options flag
* @see #NOTE_VISIBLE
* @see #NOTE_HIDDEN
*/
public short Flags
{
get { return field_3_flags; }
set { field_3_flags = value; }
}
/**
* Object id for OBJ record that Contains the comment
*/
public int ShapeId
{
get { return field_4_shapeid; }
set { field_4_shapeid = value; }
}
/**
* Name of the original comment author
*
* @return the name of the original author of the comment
*/
public String Author
{
get { return field_6_author; }
set
{
field_6_author = value;
field_5_hasMultibyte = StringUtil.HasMultibyte(value);
}
}
/**
* For unit testing only!
*/
internal bool AuthorIsMultibyte
{
get
{
return field_5_hasMultibyte;
}
}
public override Object Clone()
{
NoteRecord rec = new NoteRecord();
rec.field_1_row = field_1_row;
rec.field_2_col = field_2_col;
rec.field_3_flags = field_3_flags;
rec.field_4_shapeid = field_4_shapeid;
rec.field_6_author = field_6_author;
return rec;
}
}
}
| |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Courier.Hosts
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Contracts;
using Events;
using Exceptions;
using GreenPipes;
using GreenPipes.Payloads;
using Results;
public class HostExecuteContext<TArguments> :
BasePipeContext,
ExecuteContext<TArguments>
where TArguments : class
{
readonly Activity _activity;
readonly TArguments _arguments;
readonly Uri _compensationAddress;
readonly ConsumeContext<RoutingSlip> _context;
readonly Guid _executionId;
readonly HostInfo _host;
readonly IRoutingSlipEventPublisher _publisher;
readonly SanitizedRoutingSlip _routingSlip;
readonly Stopwatch _timer;
readonly DateTime _timestamp;
public HostExecuteContext(HostInfo host, Uri compensationAddress, ConsumeContext<RoutingSlip> context)
: base(new PayloadCacheScope(context), context.CancellationToken)
{
_host = host;
_compensationAddress = compensationAddress;
_context = context;
_timer = Stopwatch.StartNew();
var newId = NewId.Next();
_executionId = newId.ToGuid();
_timestamp = newId.Timestamp;
_routingSlip = new SanitizedRoutingSlip(context);
if (_routingSlip.Itinerary.Count == 0)
throw new ArgumentException("The routingSlip must contain at least one activity");
_activity = _routingSlip.Itinerary[0];
_arguments = _routingSlip.GetActivityArguments<TArguments>();
_publisher = new RoutingSlipEventPublisher(this, _routingSlip);
}
Task IPublishEndpoint.Publish<T>(T message, CancellationToken cancellationToken)
{
return _context.Publish(message, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext<T>> publishPipe,
CancellationToken cancellationToken)
{
return _context.Publish(message, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(T message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
return _context.Publish(message, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, CancellationToken cancellationToken)
{
return _context.Publish(message, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken)
{
return _context.Publish(message, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, Type messageType, CancellationToken cancellationToken)
{
return _context.Publish(message, messageType, cancellationToken);
}
Task IPublishEndpoint.Publish(object message, Type messageType, IPipe<PublishContext> publishPipe,
CancellationToken cancellationToken)
{
return _context.Publish(message, messageType, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(object values, CancellationToken cancellationToken)
{
return _context.Publish<T>(values, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext<T>> publishPipe,
CancellationToken cancellationToken)
{
return _context.Publish(values, publishPipe, cancellationToken);
}
Task IPublishEndpoint.Publish<T>(object values, IPipe<PublishContext> publishPipe,
CancellationToken cancellationToken)
{
return _context.Publish<T>(values, publishPipe, cancellationToken);
}
HostInfo ExecuteContext.Host => _host;
DateTime ExecuteContext.Timestamp => _timestamp;
TimeSpan ExecuteContext.Elapsed => _timer.Elapsed;
ConsumeContext ExecuteContext.ConsumeContext => _context;
TArguments ExecuteContext<TArguments>.Arguments => _arguments;
Guid ExecuteContext.TrackingNumber => _routingSlip.TrackingNumber;
Guid ExecuteContext.ExecutionId => _executionId;
string ExecuteContext.ActivityName => _activity.Name;
ExecutionResult ExecuteContext.Completed()
{
return new NextActivityExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip);
}
ExecutionResult ExecuteContext.Completed<TLog>(TLog log)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
if (_compensationAddress == null)
throw new InvalidCompensationAddressException(_compensationAddress);
return new NextActivityExecutionResult<TArguments, TLog>(this, _publisher, _activity, _routingSlip, _compensationAddress, log);
}
ExecutionResult ExecuteContext.CompletedWithVariables(IEnumerable<KeyValuePair<string, object>> variables)
{
if (variables == null)
throw new ArgumentNullException(nameof(variables));
return new NextActivityWithVariablesExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip,
variables.ToDictionary(x => x.Key, x => x.Value));
}
ExecutionResult ExecuteContext.CompletedWithVariables(object variables)
{
if (variables == null)
throw new ArgumentNullException(nameof(variables));
return new NextActivityWithVariablesExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip,
RoutingSlipBuilder.GetObjectAsDictionary(variables));
}
ExecutionResult ExecuteContext.CompletedWithVariables<TLog>(TLog log, object variables)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
if (variables == null)
throw new ArgumentNullException(nameof(variables));
if (_compensationAddress == null)
throw new InvalidCompensationAddressException(_compensationAddress);
return new NextActivityWithVariablesExecutionResult<TArguments, TLog>(this, _publisher, _activity, _routingSlip, _compensationAddress, log,
RoutingSlipBuilder.GetObjectAsDictionary(variables));
}
ExecutionResult ExecuteContext.CompletedWithVariables<TLog>(TLog log, IEnumerable<KeyValuePair<string, object>> variables)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
if (variables == null)
throw new ArgumentNullException(nameof(variables));
if (_compensationAddress == null)
throw new InvalidCompensationAddressException(_compensationAddress);
return new NextActivityWithVariablesExecutionResult<TArguments, TLog>(this, _publisher, _activity, _routingSlip, _compensationAddress, log,
variables.ToDictionary(x => x.Key, x => x.Value));
}
ExecutionResult ExecuteContext.ReviseItinerary(Action<ItineraryBuilder> buildItinerary)
{
if (buildItinerary == null)
throw new ArgumentNullException(nameof(buildItinerary));
return new ReviseItineraryExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip, buildItinerary);
}
ExecutionResult ExecuteContext.ReviseItinerary<TLog>(TLog log, Action<ItineraryBuilder> buildItinerary)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
if (buildItinerary == null)
throw new ArgumentNullException(nameof(buildItinerary));
if (_compensationAddress == null)
throw new InvalidCompensationAddressException(_compensationAddress);
return new ReviseItineraryExecutionResult<TArguments, TLog>(this, _publisher, _activity, _routingSlip, _compensationAddress, log,
buildItinerary);
}
ExecutionResult ExecuteContext.ReviseItinerary<TLog>(TLog log, object variables, Action<ItineraryBuilder> buildItinerary)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
if (variables == null)
throw new ArgumentNullException(nameof(variables));
if (buildItinerary == null)
throw new ArgumentNullException(nameof(buildItinerary));
if (_compensationAddress == null)
throw new InvalidCompensationAddressException(_compensationAddress);
return new ReviseItineraryWithVariablesExecutionResult<TArguments, TLog>(this, _publisher, _activity, _routingSlip, _compensationAddress,
log, RoutingSlipBuilder.GetObjectAsDictionary(variables), buildItinerary);
}
ExecutionResult ExecuteContext.ReviseItinerary<TLog>(TLog log, IEnumerable<KeyValuePair<string, object>> variables,
Action<ItineraryBuilder> buildItinerary)
{
if (log == null)
throw new ArgumentNullException(nameof(log));
if (variables == null)
throw new ArgumentNullException(nameof(variables));
if (buildItinerary == null)
throw new ArgumentNullException(nameof(buildItinerary));
if (_compensationAddress == null)
throw new InvalidCompensationAddressException(_compensationAddress);
return new ReviseItineraryWithVariablesExecutionResult<TArguments, TLog>(this, _publisher, _activity, _routingSlip, _compensationAddress,
log, variables.ToDictionary(x => x.Key, x => x.Value), buildItinerary);
}
ExecutionResult ExecuteContext.Terminate()
{
return new TerminateExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip);
}
ExecutionResult ExecuteContext.Terminate(object variables)
{
if (variables == null)
throw new ArgumentNullException(nameof(variables));
return new TerminateWithVariablesExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip,
RoutingSlipBuilder.GetObjectAsDictionary(variables));
}
ExecutionResult ExecuteContext.Terminate(IEnumerable<KeyValuePair<string, object>> variables)
{
if (variables == null)
throw new ArgumentNullException(nameof(variables));
return new TerminateWithVariablesExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip,
variables.ToDictionary(x => x.Key, x => x.Value));
}
ExecutionResult ExecuteContext.Faulted()
{
return Faulted(new ActivityExecutionFaultedException());
}
ExecutionResult ExecuteContext.Faulted(Exception exception)
{
if (exception == null)
throw new ArgumentNullException(nameof(exception));
return Faulted(exception);
}
Task<ISendEndpoint> ISendEndpointProvider.GetSendEndpoint(Uri address)
{
return _context.GetSendEndpoint(address);
}
ConnectHandle IPublishObserverConnector.ConnectPublishObserver(IPublishObserver observer)
{
return _context.ConnectPublishObserver(observer);
}
public ConnectHandle ConnectSendObserver(ISendObserver observer)
{
return _context.ConnectSendObserver(observer);
}
ExecutionResult Faulted(Exception exception)
{
return new FaultedExecutionResult<TArguments>(this, _publisher, _activity, _routingSlip, new FaultExceptionInfo(exception));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ApplicationContext.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Provides consistent context information between the client</summary>
//-----------------------------------------------------------------------
using System;
using System.Security.Principal;
using Csla.Core;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
namespace Csla
{
/// <summary>
/// Provides consistent context information between the client
/// and server DataPortal objects.
/// </summary>
public class ApplicationContext
{
/// <summary>
/// Creates a new instance of the type
/// </summary>
/// <param name="contextManagerList">List of registered IContextManager</param>
/// <param name="serviceProvider">Current service provider</param>
/// <param name="runtimeInfo"></param>
public ApplicationContext(IEnumerable<IContextManager> contextManagerList, IServiceProvider serviceProvider, Runtime.IRuntimeInfo runtimeInfo)
{
_serviceProvider = serviceProvider;
RuntimeInfo = runtimeInfo;
foreach (var context in contextManagerList)
{
if (context.IsValid)
{
ContextManager = context;
break;
}
}
if (ContextManager is null)
{
ContextManager = new Core.ApplicationContextManagerAsyncLocal();
}
ContextManager.ApplicationContext = this;
}
private Runtime.IRuntimeInfo RuntimeInfo { get; set; }
/// <summary>
/// Gets the context manager responsible
/// for storing user and context information for
/// the application.
/// </summary>
public IContextManager ContextManager { get; internal set; }
/// <summary>
/// Get or set the current ClaimsPrincipal
/// object representing the user's identity.
/// </summary>
public ClaimsPrincipal Principal
{
get { return (ClaimsPrincipal)ContextManager.GetUser(); }
set { ContextManager.SetUser(value); }
}
/// <summary>
/// Get or set the current <see cref="IPrincipal" />
/// object representing the user's identity.
/// </summary>
/// <remarks>
/// This is discussed in Chapter 5. When running
/// under IIS the HttpContext.Current.User value
/// is used, otherwise the current Thread.CurrentPrincipal
/// value is used.
/// </remarks>
public IPrincipal User
{
get { return ContextManager.GetUser(); }
set { ContextManager.SetUser(value); }
}
/// <summary>
/// Returns the application-specific context data that
/// is local to the current AppDomain.
/// </summary>
/// <remarks>
/// <para>
/// The return value is a HybridDictionary. If one does
/// not already exist, and empty one is created and returned.
/// </para><para>
/// Note that data in this context is NOT transferred to and from
/// the client and server.
/// </para>
/// </remarks>
public ContextDictionary LocalContext
{
get
{
ContextDictionary ctx = ContextManager.GetLocalContext();
if (ctx == null)
{
ctx = new ContextDictionary();
ContextManager.SetLocalContext(ctx);
}
return ctx;
}
}
private readonly object _syncContext = new();
/// <summary>
/// Returns the application-specific context data provided
/// by the client.
/// </summary>
/// <remarks>
/// <para>
/// The return value is a HybridDictionary. If one does
/// not already exist, and empty one is created and returned.
/// </para><para>
/// Note that data in this context is transferred from
/// the client to the server. No data is transferred from
/// the server to the client.
/// </para><para>
/// This property is thread safe in a Windows client
/// setting and on an application server. It is not guaranteed
/// to be thread safe within the context of an ASP.NET
/// client setting (i.e. in your ASP.NET UI).
/// </para>
/// </remarks>
public ContextDictionary ClientContext
{
get
{
lock (_syncContext)
{
ContextDictionary ctx = ContextManager.GetClientContext(ExecutionLocation);
if (ctx == null)
{
ctx = new ContextDictionary();
ContextManager.SetClientContext(ctx, ExecutionLocation);
}
return ctx;
}
}
}
internal void SetContext(ContextDictionary clientContext)
{
lock (_syncContext)
ContextManager.SetClientContext(clientContext, ExecutionLocation);
}
/// <summary>
/// Clears all context collections.
/// </summary>
public void Clear()
{
SetContext(null);
ContextManager.SetLocalContext(null);
}
#region Settings
/// <summary>
/// Gets or sets a value indicating whether the app
/// should be considered "offline".
/// </summary>
/// <remarks>
/// If this value is true then the client-side data
/// portal will direct all calls to the local
/// data portal. No calls will flow to remote
/// data portal endpoints.
/// </remarks>
public bool IsOffline { get; set; }
/// <summary>
/// Gets or sets a value indicating whether CSLA
/// should fallback to using reflection instead of
/// System.Linq.Expressions (true, default).
/// </summary>
public static bool UseReflectionFallback { get; set; } = false;
/// <summary>
/// Gets a value representing the application version
/// for use in server-side data portal routing.
/// </summary>
public static string VersionRoutingTag { get; internal set; }
/// <summary>
/// Gets the authentication type being used by the
/// CSLA .NET framework.
/// </summary>
/// <value></value>
/// <returns></returns>
public static string AuthenticationType { get; internal set; } = "Csla";
/// <summary>
/// Gets a value indicating whether objects should be
/// automatically cloned by the data portal Update()
/// method when using a local data portal configuration.
/// </summary>
public static bool AutoCloneOnUpdate { get; internal set; } = true;
/// <summary>
/// Gets a value indicating whether the
/// server-side business object should be returned to
/// the client as part of the DataPortalException
/// (default is false).
/// </summary>
public static bool DataPortalReturnObjectOnException { get; internal set; }
/// <summary>
/// Enum representing the locations code can execute.
/// </summary>
public enum ExecutionLocations
{
/// <summary>
/// The code is executing on the client.
/// </summary>
Client,
/// <summary>
/// The code is executing on the application server.
/// </summary>
Server
}
/// <summary>
/// Gets the serialization formatter type used by CSLA .NET
/// for all explicit object serialization (such as cloning,
/// n-level undo, etc).
/// </summary>
public static Type SerializationFormatter { get; internal set; } = typeof(Serialization.Mobile.MobileFormatter);
/// <summary>
/// Gets or sets a value specifying how CSLA .NET should
/// raise PropertyChanged events.
/// </summary>
public static PropertyChangedModes PropertyChangedMode { get; set; }
/// <summary>
/// Enum representing the way in which CSLA .NET
/// should raise PropertyChanged events.
/// </summary>
public enum PropertyChangedModes
{
/// <summary>
/// Raise PropertyChanged events as required
/// by Windows Forms data binding.
/// </summary>
Windows,
/// <summary>
/// Raise PropertyChanged events as required
/// by XAML data binding in WPF.
/// </summary>
Xaml
}
private ExecutionLocations _executionLocation =
#if (ANDROID || IOS || NETFX_CORE) && !NETSTANDARD
ExecutionLocations.MobileClient;
#else
ExecutionLocations.Client;
#endif
/// <summary>
/// Returns a value indicating whether the application code
/// is currently executing on the client or server.
/// </summary>
public ExecutionLocations ExecutionLocation
{
get { return _executionLocation; }
}
internal void SetExecutionLocation(ExecutionLocations location)
{
_executionLocation = location;
}
/// <summary>
/// The default RuleSet name
/// </summary>
public const string DefaultRuleSet = "default";
/// <summary>
/// Gets or sets the RuleSet name to use for static HasPermission calls.
/// </summary>
/// <value>The rule set.</value>
public string RuleSet
{
get
{
var ruleSet = (string)ClientContext.GetValueOrNull("__ruleSet");
return string.IsNullOrEmpty(ruleSet) ? ApplicationContext.DefaultRuleSet : ruleSet;
}
set
{
ClientContext["__ruleSet"] = value;
}
}
/// <summary>
/// Gets or sets the default transaction isolation level.
/// </summary>
/// <value>
/// The default transaction isolation level.
/// </value>
public static TransactionIsolationLevel DefaultTransactionIsolationLevel { get; internal set; } = TransactionIsolationLevel.Unspecified;
/// <summary>
/// Gets or sets the default transaction timeout in seconds.
/// </summary>
/// <value>
/// The default transaction timeout in seconds.
/// </value>
public static int DefaultTransactionTimeoutInSeconds { get; internal set; } = 30;
/// <summary>
/// Gets or sets the default transaction async flow option
/// used to create new TransactionScope objects.
/// </summary>
public static System.Transactions.TransactionScopeAsyncFlowOption DefaultTransactionAsyncFlowOption
{ get; internal set; } = System.Transactions.TransactionScopeAsyncFlowOption.Suppress;
#endregion
#region Logical Execution Location
/// <summary>
/// Enum representing the logical execution location
/// The setting is set to server when server is execting
/// a CRUD opertion, otherwise the setting is always client
/// </summary>
public enum LogicalExecutionLocations
{
/// <summary>
/// The code is executing on the client.
/// </summary>
Client,
/// <summary>
/// The code is executing on the server. This includes
/// Local mode execution
/// </summary>
Server
}
/// <summary>
/// Return Logical Execution Location - Client or Server
/// This is applicable to Local mode as well
/// </summary>
public LogicalExecutionLocations LogicalExecutionLocation
{
get
{
object location = LocalContext.GetValueOrNull("__logicalExecutionLocation");
if (location != null)
return (LogicalExecutionLocations)location;
else
return LogicalExecutionLocations.Client;
}
}
/// <summary>
/// Set logical execution location
/// </summary>
/// <param name="location">Location to set context to</param>
internal void SetLogicalExecutionLocation(LogicalExecutionLocations location)
{
LocalContext["__logicalExecutionLocation"] = location;
}
#endregion
/// <summary>
/// Gets a value indicating whether the current
/// context manager is used in a stateful
/// context (e.g. WPF, Blazor, etc.)
/// </summary>
public bool IsAStatefulContextManager => ContextManager.IsStatefulContext;
private IServiceProvider _serviceProvider;
/// <summary>
/// Sets the service provider scope for this application context.
/// </summary>
internal IServiceProvider CurrentServiceProvider
{
get => _serviceProvider;
set => _serviceProvider = value;
}
/// <summary>
/// Creates an object using dependency injection, falling back
/// to Activator if no service provider is available.
/// </summary>
/// <typeparam name="T">Type of object to create.</typeparam>
/// <param name="parameters">Parameters for constructor</param>
public T CreateInstanceDI<T>(params object[] parameters)
{
return (T)CreateInstanceDI(typeof(T), parameters);
}
/// <summary>
/// Creates an object using dependency injection, falling back
/// to Activator if no service provider is available.
/// </summary>
/// <param name="objectType">Type of object to create</param>
/// <param name="parameters">Parameters for constructor</param>
public object CreateInstanceDI(Type objectType, params object[] parameters)
{
object result;
if (CurrentServiceProvider != null)
result = ActivatorUtilities.CreateInstance(CurrentServiceProvider, objectType, parameters);
else
result = Activator.CreateInstance(objectType, parameters);
if (result is IUseApplicationContext tmp)
{
tmp.ApplicationContext = this;
}
return result;
}
/// <summary>
/// Creates an instance of a generic type
/// using its default constructor.
/// </summary>
/// <param name="type">Generic type to create</param>
/// <param name="paramTypes">Type parameters</param>
/// <returns></returns>
internal object CreateGenericInstanceDI(Type type, params Type[] paramTypes)
{
var genericType = type.GetGenericTypeDefinition();
var gt = genericType.MakeGenericType(paramTypes);
return CreateInstanceDI(gt);
}
/// <summary>
/// Creates an object using Activator.
/// </summary>
/// <typeparam name="T">Type of object to create.</typeparam>
/// <param name="parameters">Parameters for constructor</param>
public T CreateInstance<T>(params object[] parameters)
{
return (T)CreateInstance(typeof(T), parameters);
}
/// <summary>
/// Creates an object using Activator.
/// </summary>
/// <param name="objectType">Type of object to create</param>
/// <param name="parameters">Parameters for constructor</param>
public object CreateInstance(Type objectType, params object[] parameters)
{
object result;
result = Activator.CreateInstance(objectType, parameters);
if (result is IUseApplicationContext tmp)
{
tmp.ApplicationContext = this;
}
return result;
}
/// <summary>
/// Creates an instance of a generic type using Activator.
/// </summary>
/// <param name="type">Generic type to create</param>
/// <param name="paramTypes">Type parameters</param>
/// <returns></returns>
internal object CreateGenericInstance(Type type, params Type[] paramTypes)
{
var genericType = type.GetGenericTypeDefinition();
var gt = genericType.MakeGenericType(paramTypes);
return CreateInstance(gt);
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using NuGet.Resources;
namespace NuGet
{
public class PackageManager : IPackageManager
{
private ILogger _logger;
public event EventHandler<PackageOperationEventArgs> PackageInstalling;
public event EventHandler<PackageOperationEventArgs> PackageInstalled;
public event EventHandler<PackageOperationEventArgs> PackageUninstalling;
public event EventHandler<PackageOperationEventArgs> PackageUninstalled;
public PackageManager(IPackageRepository sourceRepository, string path)
: this(sourceRepository, new DefaultPackagePathResolver(path), new PhysicalFileSystem(path))
{
}
public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem) :
this(sourceRepository, pathResolver, fileSystem, new LocalPackageRepository(pathResolver, fileSystem))
{
}
public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem, IPackageRepository localRepository)
{
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
if (localRepository == null)
{
throw new ArgumentNullException("localRepository");
}
SourceRepository = sourceRepository;
PathResolver = pathResolver;
FileSystem = fileSystem;
LocalRepository = localRepository;
}
public IFileSystem FileSystem
{
get;
set;
}
public IPackageRepository SourceRepository
{
get;
private set;
}
public IPackageRepository LocalRepository
{
get;
private set;
}
public IPackagePathResolver PathResolver
{
get;
private set;
}
public ILogger Logger
{
get
{
return _logger ?? NullLogger.Instance;
}
set
{
_logger = value;
}
}
public void InstallPackage(string packageId)
{
InstallPackage(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false);
}
public void InstallPackage(string packageId, SemanticVersion version)
{
InstallPackage(packageId, version, ignoreDependencies: false, allowPrereleaseVersions: false);
}
public virtual void InstallPackage(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions);
InstallPackage(package, ignoreDependencies, allowPrereleaseVersions);
}
public virtual void InstallPackage(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
Execute(package, new InstallWalker(LocalRepository,
SourceRepository,
Logger,
ignoreDependencies,
allowPrereleaseVersions));
}
private void Execute(IPackage package, IPackageOperationResolver resolver)
{
var operations = resolver.ResolveOperations(package);
if (operations.Any())
{
foreach (PackageOperation operation in operations)
{
Execute(operation);
}
}
else if (LocalRepository.Exists(package))
{
// If the package wasn't installed by our set of operations, notify the user.
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, package.GetFullName());
}
}
protected void Execute(PackageOperation operation)
{
bool packageExists = LocalRepository.Exists(operation.Package);
if (operation.Action == PackageAction.Install)
{
// If the package is already installed, then skip it
if (packageExists)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, operation.Package.GetFullName());
}
else
{
ExecuteInstall(operation.Package);
}
}
else
{
if (packageExists)
{
ExecuteUninstall(operation.Package);
}
}
}
protected void ExecuteInstall(IPackage package)
{
PackageOperationEventArgs args = CreateOperation(package);
OnInstalling(args);
if (args.Cancel)
{
return;
}
ExpandFiles(package);
LocalRepository.AddPackage(package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageInstalledSuccessfully, package.GetFullName());
OnInstalled(args);
}
private void ExpandFiles(IPackage package)
{
var batchProcessor = FileSystem as IBatchProcessor<string>;
try
{
var files = package.GetFiles().ToList();
if (batchProcessor != null)
{
// Notify the batch processor that the files are being added. This is to allow source controlled file systems
// to manage previously uninstalled files.
batchProcessor.BeginProcessing(files.Select(p => p.Path), PackageAction.Install);
}
string packageDirectory = PathResolver.GetPackageDirectory(package);
// Add files
FileSystem.AddFiles(files, packageDirectory);
// If this is a Satellite Package, then copy the satellite files into the related runtime package folder too
IPackage runtimePackage;
if (PackageUtility.IsSatellitePackage(package, LocalRepository, out runtimePackage))
{
var satelliteFiles = package.GetSatelliteFiles();
var runtimePath = PathResolver.GetPackageDirectory(runtimePackage);
FileSystem.AddFiles(satelliteFiles, runtimePath);
}
}
finally
{
if (batchProcessor != null)
{
batchProcessor.EndProcessing();
}
}
}
public void UninstallPackage(string packageId)
{
UninstallPackage(packageId, version: null, forceRemove: false, removeDependencies: false);
}
public void UninstallPackage(string packageId, SemanticVersion version)
{
UninstallPackage(packageId, version: version, forceRemove: false, removeDependencies: false);
}
public void UninstallPackage(string packageId, SemanticVersion version, bool forceRemove)
{
UninstallPackage(packageId, version: version, forceRemove: forceRemove, removeDependencies: false);
}
public virtual void UninstallPackage(string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
IPackage package = LocalRepository.FindPackage(packageId, version: version);
if (package == null)
{
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentCulture,
NuGetResources.UnknownPackage, packageId));
}
UninstallPackage(package, forceRemove, removeDependencies);
}
public void UninstallPackage(IPackage package)
{
UninstallPackage(package, forceRemove: false, removeDependencies: false);
}
public void UninstallPackage(IPackage package, bool forceRemove)
{
UninstallPackage(package, forceRemove: forceRemove, removeDependencies: false);
}
public virtual void UninstallPackage(IPackage package, bool forceRemove, bool removeDependencies)
{
Execute(package, new UninstallWalker(LocalRepository,
new DependentsWalker(LocalRepository),
Logger,
removeDependencies,
forceRemove));
}
protected virtual void ExecuteUninstall(IPackage package)
{
PackageOperationEventArgs args = CreateOperation(package);
OnUninstalling(args);
if (args.Cancel)
{
return;
}
RemoveFiles(package);
// Remove package to the repository
LocalRepository.RemovePackage(package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyUninstalledPackage, package.GetFullName());
OnUninstalled(args);
}
private void RemoveFiles(IPackage package)
{
string packageDirectory = PathResolver.GetPackageDirectory(package);
// Remove resource files
FileSystem.DeleteFiles(package.GetFiles(), packageDirectory);
// If this is a Satellite Package, then remove the files from the related runtime package folder too
IPackage runtimePackage;
if (PackageUtility.IsSatellitePackage(package, LocalRepository, out runtimePackage))
{
var satelliteFiles = package.GetSatelliteFiles();
var runtimePath = PathResolver.GetPackageDirectory(runtimePackage);
FileSystem.DeleteFiles(satelliteFiles, runtimePath);
}
}
private void OnInstalling(PackageOperationEventArgs e)
{
if (PackageInstalling != null)
{
PackageInstalling(this, e);
}
}
protected virtual void OnInstalled(PackageOperationEventArgs e)
{
if (PackageInstalled != null)
{
PackageInstalled(this, e);
}
}
protected virtual void OnUninstalled(PackageOperationEventArgs e)
{
if (PackageUninstalled != null)
{
PackageUninstalled(this, e);
}
}
private void OnUninstalling(PackageOperationEventArgs e)
{
if (PackageUninstalling != null)
{
PackageUninstalling(this, e);
}
}
private PackageOperationEventArgs CreateOperation(IPackage package)
{
return new PackageOperationEventArgs(package, FileSystem, PathResolver.GetInstallPath(package));
}
public void UpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackage(packageId, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions);
}
public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackage(packageId, () => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies, allowPrereleaseVersions);
}
public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackage(packageId, () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies, allowPrereleaseVersions);
}
internal void UpdatePackage(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
IPackage oldPackage = LocalRepository.FindPackage(packageId);
// Check to see if this package is installed
if (oldPackage == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.UnknownPackage, packageId));
}
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId);
IPackage newPackage = resolvePackage();
if (newPackage != null && oldPackage.Version != newPackage.Version)
{
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
else
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailable, packageId);
}
}
public void UpdatePackage(IPackage newPackage, bool updateDependencies, bool allowPrereleaseVersions)
{
Execute(newPackage, new UpdateWalker(LocalRepository,
SourceRepository,
new DependentsWalker(LocalRepository),
NullConstraintProvider.Instance,
Logger,
updateDependencies,
allowPrereleaseVersions));
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Reflection;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Class to deserialize property bags into formatting objects
/// by using ERS functionality.
/// </summary>
internal sealed class FormatObjectDeserializer
{
internal TerminatingErrorContext TerminatingErrorContext { get; }
/// <summary>
/// Expansion of TAB character to the following string.
/// </summary>
private const string TabExpansionString = " ";
internal FormatObjectDeserializer(TerminatingErrorContext errorContext)
{
TerminatingErrorContext = errorContext;
}
internal bool IsFormatInfoData(PSObject so)
{
var fid = PSObject.Base(so) as FormatInfoData;
if (fid != null)
{
if (fid is FormatStartData ||
fid is FormatEndData ||
fid is GroupStartData ||
fid is GroupEndData ||
fid is FormatEntryData)
{
return true;
}
// we have an unexpected type (CLSID not matching): this should never happen
ProcessUnknownInvalidClassId(fid.ClassId2e4f51ef21dd47e99d3c952918aff9cd, so, "FormatObjectDeserializerDeserializeInvalidClassId");
return false;
}
// check the type of the object by
// 1) verifying the type name information
// 2) trying to access the property containing CLSID information
if (!Deserializer.IsInstanceOfType(so, typeof(FormatInfoData)))
{
return false;
}
if (!(GetProperty(so, FormatInfoData.classidProperty) is string classId))
{
// it's not one of the objects derived from FormatInfoData
return false;
}
// it's one of ours, get the right class and deserialize it accordingly
if (IsClass(classId, FormatStartData.CLSID) ||
IsClass(classId, FormatEndData.CLSID) ||
IsClass(classId, GroupStartData.CLSID) ||
IsClass(classId, GroupEndData.CLSID) ||
IsClass(classId, FormatEntryData.CLSID))
{
return true;
}
// we have an unknown type (CLSID not matching): this should never happen
ProcessUnknownInvalidClassId(classId, so, "FormatObjectDeserializerIsFormatInfoDataInvalidClassId");
return false;
}
/// <summary>
/// Given a raw object out of the pipeline, it deserializes it accordingly to
/// its type.
/// If the object is not one of the well known ones (i.e. derived from FormatInfoData)
/// it just returns the object unchanged.
/// </summary>
/// <param name="so">Object to deserialize.</param>
/// <returns>Deserialized object or null.</returns>
internal object Deserialize(PSObject so)
{
var fid = PSObject.Base(so) as FormatInfoData;
if (fid != null)
{
if (fid is FormatStartData ||
fid is FormatEndData ||
fid is GroupStartData ||
fid is GroupEndData ||
fid is FormatEntryData)
{
return fid;
}
// we have an unexpected type (CLSID not matching): this should never happen
ProcessUnknownInvalidClassId(fid.ClassId2e4f51ef21dd47e99d3c952918aff9cd, so, "FormatObjectDeserializerDeserializeInvalidClassId");
return null;
}
// check the type of the object by
// 1) verifying the type name information
// 2) trying to access the property containing CLSID information
if (!Deserializer.IsInstanceOfType(so, typeof(FormatInfoData)))
{
return so;
}
if (!(GetProperty(so, FormatInfoData.classidProperty) is string classId))
{
// it's not one of the objects derived from FormatInfoData,
// just return it as is
return so;
}
// it's one of ours, get the right class and deserialize it accordingly
if (IsClass(classId, FormatStartData.CLSID) ||
IsClass(classId, FormatEndData.CLSID) ||
IsClass(classId, GroupStartData.CLSID) ||
IsClass(classId, GroupEndData.CLSID) ||
IsClass(classId, FormatEntryData.CLSID))
{
return DeserializeObject(so);
}
// we have an unknown type (CLSID not matching): this should never happen
ProcessUnknownInvalidClassId(classId, so, "FormatObjectDeserializerDeserializeInvalidClassId");
return null;
}
private void ProcessUnknownInvalidClassId(string classId, object obj, string errorId)
{
string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_ClassIdInvalid, classId);
ErrorRecord errorRecord = new ErrorRecord(
PSTraceSource.NewArgumentException(nameof(classId)),
errorId,
ErrorCategory.InvalidData,
obj);
errorRecord.ErrorDetails = new ErrorDetails(msg);
this.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
#region Helper Methods
private static bool IsClass(string x, string y)
{
return string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
}
#if _UNUSED
NOTE: this code is commented out because the current schema does not have the need for
it. We retail it because future schema extensions might require it
/// <summary>
/// ERS helper to reconstitute a string[] out of IEnumerable property.
/// </summary>
/// <param name="rawObject">Object to process.</param>
/// <param name="propertyName">Property to look up.</param>
/// <returns>String[] representation of the property.</returns>
private static string[] ReadStringArrayHelper (object rawObject, string propertyName)
{
// throw if the property is not there
IEnumerable e = (IEnumerable)ERSHelper.GetExtendedProperty (rawObject, propertyName, false);
if (e == null)
return null;
// copy to string collection, since, a priori, we do not know the length
StringCollection temp = new StringCollection ();
foreach (string s in e)
temp.Add (s);
if (temp.Count <= 0)
return null;
// copy to a string[] and return
string[] retVal = new string[temp.Count];
temp.CopyTo (retVal, 0);
return retVal;
}
#endif
#endregion
internal static object GetProperty(PSObject so, string name)
{
PSMemberInfo member = so.Properties[name];
if (member == null)
{
return null;
}
// NOTE: we do not distinguish between property not there and null property
// if an exception is thrown, it would be considered an internal failure
return member.Value;
}
// returns null on error
internal FormatInfoData DeserializeMemberObject(PSObject so, string property)
{
object memberRaw = GetProperty(so, property);
if (memberRaw == null)
return null;
if (so == memberRaw)
{
string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_RecursiveProperty, property);
ErrorRecord errorRecord = new ErrorRecord(
PSTraceSource.NewArgumentException(nameof(property)),
"FormatObjectDeserializerRecursiveProperty",
ErrorCategory.InvalidData,
so);
errorRecord.ErrorDetails = new ErrorDetails(msg);
this.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
return DeserializeObject(PSObject.AsPSObject(memberRaw));
}
internal FormatInfoData DeserializeMandatoryMemberObject(PSObject so, string property)
{
FormatInfoData fid = DeserializeMemberObject(so, property);
VerifyDataNotNull(fid, property);
return fid;
}
private object DeserializeMemberVariable(PSObject so, string property, System.Type t, bool cannotBeNull)
{
object objRaw = GetProperty(so, property);
if (cannotBeNull)
VerifyDataNotNull(objRaw, property);
if (objRaw != null && t != objRaw.GetType())
{
string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidPropertyType, t.Name, property);
ErrorRecord errorRecord = new ErrorRecord(
PSTraceSource.NewArgumentException(nameof(property)),
"FormatObjectDeserializerInvalidPropertyType",
ErrorCategory.InvalidData,
so);
errorRecord.ErrorDetails = new ErrorDetails(msg);
this.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
return objRaw;
}
/// <summary>
/// Deserialization of string without TAB expansion (RAW)
/// </summary>
/// <param name="so">Object whose the property belongs to.</param>
/// <param name="property">Name of the string property.</param>
/// <returns>String out of the MsObject.</returns>
internal string DeserializeStringMemberVariableRaw(PSObject so, string property)
{
return (string)DeserializeMemberVariable(so, property, typeof(string), false /* cannotBeNull */);
}
/// <summary>
/// Deserialization of string performing TAB expansion.
/// </summary>
/// <param name="so">Object whose the property belongs to.</param>
/// <param name="property">Name of the string property.</param>
/// <returns>String out of the MsObject.</returns>
internal string DeserializeStringMemberVariable(PSObject so, string property)
{
string val = (string)DeserializeMemberVariable(so, property, typeof(string), false /* cannotBeNull */);
// expand TAB's
if (string.IsNullOrEmpty(val))
return val;
return val.Replace("\t", TabExpansionString);
}
internal int DeserializeIntMemberVariable(PSObject so, string property)
{
return (int)DeserializeMemberVariable(so, property, typeof(int), true /* cannotBeNull */);
}
internal bool DeserializeBoolMemberVariable(PSObject so, string property, bool cannotBeNull = true)
{
var val = DeserializeMemberVariable(so, property, typeof(bool), cannotBeNull);
return val != null && (bool)val;
}
internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so)
{
object wsTypeValue = GetProperty(so, "writeStream");
if (wsTypeValue == null)
{
return WriteStreamType.None;
}
WriteStreamType rtnWSType;
if (wsTypeValue is WriteStreamType)
{
rtnWSType = (WriteStreamType)wsTypeValue;
}
else if (wsTypeValue is string)
{
if (!Enum.TryParse<WriteStreamType>(wsTypeValue as string, true, out rtnWSType))
{
rtnWSType = WriteStreamType.None;
}
}
else
{
rtnWSType = WriteStreamType.None;
}
return rtnWSType;
}
// returns null on error
internal FormatInfoData DeserializeObject(PSObject so)
{
FormatInfoData fid = FormatInfoDataClassFactory.CreateInstance(so, this);
if (fid != null)
fid.Deserialize(so, this);
return fid;
}
internal void VerifyDataNotNull(object obj, string name)
{
if (obj != null)
return;
string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_NullDataMember, name);
ErrorRecord errorRecord = new ErrorRecord(
new ArgumentException(),
"FormatObjectDeserializerNullDataMember",
ErrorCategory.InvalidData,
null);
errorRecord.ErrorDetails = new ErrorDetails(msg);
this.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
}
internal static class FormatInfoDataClassFactory
{
static FormatInfoDataClassFactory()
{
s_constructors = new Dictionary<string, Func<FormatInfoData>>
{
{FormatStartData.CLSID, static () => new FormatStartData()},
{FormatEndData.CLSID, static () => new FormatEndData()},
{GroupStartData.CLSID, static () => new GroupStartData()},
{GroupEndData.CLSID, static () => new GroupEndData()},
{FormatEntryData.CLSID, static () => new FormatEntryData()},
{WideViewHeaderInfo.CLSID, static () => new WideViewHeaderInfo()},
{TableHeaderInfo.CLSID, static () => new TableHeaderInfo()},
{TableColumnInfo.CLSID, static () => new TableColumnInfo()},
{ListViewHeaderInfo.CLSID, static () => new ListViewHeaderInfo()},
{ListViewEntry.CLSID, static () => new ListViewEntry()},
{ListViewField.CLSID, static () => new ListViewField()},
{TableRowEntry.CLSID, static () => new TableRowEntry()},
{WideViewEntry.CLSID, static () => new WideViewEntry()},
{ComplexViewHeaderInfo.CLSID, static () => new ComplexViewHeaderInfo()},
{ComplexViewEntry.CLSID, static () => new ComplexViewEntry()},
{GroupingEntry.CLSID, static () => new GroupingEntry()},
{PageHeaderEntry.CLSID, static () => new PageHeaderEntry()},
{PageFooterEntry.CLSID, static () => new PageFooterEntry()},
{AutosizeInfo.CLSID, static () => new AutosizeInfo()},
{FormatNewLine.CLSID, static () => new FormatNewLine()},
{FrameInfo.CLSID, static () => new FrameInfo()},
{FormatTextField.CLSID, static () => new FormatTextField()},
{FormatPropertyField.CLSID, static () => new FormatPropertyField()},
{FormatEntry.CLSID, static () => new FormatEntry()},
{RawTextFormatEntry.CLSID, static () => new RawTextFormatEntry()}
};
}
// returns null on error
internal static FormatInfoData CreateInstance(PSObject so, FormatObjectDeserializer deserializer)
{
if (so == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(so));
}
// look for the property that defines the type of object
string classId = FormatObjectDeserializer.GetProperty(so, FormatInfoData.classidProperty) as string;
if (classId == null)
{
string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidClassidProperty);
ErrorRecord errorRecord = new ErrorRecord(
PSTraceSource.NewArgumentException("classid"),
"FormatObjectDeserializerInvalidClassidProperty",
ErrorCategory.InvalidData,
so);
errorRecord.ErrorDetails = new ErrorDetails(msg);
deserializer.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
FormatInfoData fid = CreateInstance(classId, deserializer);
return fid;
}
// returns null on failure
private static FormatInfoData CreateInstance(string clsid, FormatObjectDeserializer deserializer)
{
Func<FormatInfoData> ctor;
if (!s_constructors.TryGetValue(clsid, out ctor))
{
CreateInstanceError(PSTraceSource.NewArgumentException(nameof(clsid)), clsid, deserializer);
return null;
}
try
{
FormatInfoData fid = ctor();
return fid;
}
catch (ArgumentException e)
{
CreateInstanceError(e, clsid, deserializer);
}
catch (NotSupportedException e)
{
CreateInstanceError(e, clsid, deserializer);
}
catch (TargetInvocationException e)
{
CreateInstanceError(e, clsid, deserializer);
}
catch (MemberAccessException e) // also MethodAccessException and MissingMethodException
{
CreateInstanceError(e, clsid, deserializer);
}
catch (System.Runtime.InteropServices.InvalidComObjectException e)
{
CreateInstanceError(e, clsid, deserializer);
}
catch (System.Runtime.InteropServices.COMException e)
{
CreateInstanceError(e, clsid, deserializer);
}
catch (TypeLoadException e)
{
CreateInstanceError(e, clsid, deserializer);
}
catch (Exception e) // will rethrow
{
Diagnostics.Assert(false,
"Unexpected Activator.CreateInstance error in FormatInfoDataClassFactory.CreateInstance: "
+ e.GetType().FullName);
throw;
}
return null;
}
private static void CreateInstanceError(Exception e, string clsid, FormatObjectDeserializer deserializer)
{
string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidClassid, clsid);
ErrorRecord errorRecord = new ErrorRecord(
e,
"FormatObjectDeserializerInvalidClassid",
ErrorCategory.InvalidData,
null);
errorRecord.ErrorDetails = new ErrorDetails(msg);
deserializer.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
private static readonly Dictionary<string, Func<FormatInfoData>> s_constructors;
}
internal static class FormatInfoDataListDeserializer<T> where T : FormatInfoData
{
private static void ReadListHelper(IEnumerable en, List<T> lst, FormatObjectDeserializer deserializer)
{
deserializer.VerifyDataNotNull(en, "enumerable");
foreach (object obj in en)
{
FormatInfoData fid = deserializer.DeserializeObject(PSObjectHelper.AsPSObject(obj));
T entry = fid as T;
deserializer.VerifyDataNotNull(entry, "entry");
lst.Add(entry);
}
}
internal static void ReadList(PSObject so, string property, List<T> lst, FormatObjectDeserializer deserializer)
{
if (lst == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(lst));
}
object memberRaw = FormatObjectDeserializer.GetProperty(so, property);
ReadListHelper(PSObjectHelper.GetEnumerable(memberRaw), lst, deserializer);
}
}
#region Formatting Objects Deserializer
internal abstract partial class FormatInfoData
{
internal virtual void Deserialize(PSObject so, FormatObjectDeserializer deserializer) { }
}
internal abstract partial class ControlInfoData : PacketInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
// optional
this.groupingEntry = (GroupingEntry)deserializer.DeserializeMemberObject(so, "groupingEntry");
}
}
internal abstract partial class StartData : ControlInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.shapeInfo = (ShapeInfo)deserializer.DeserializeMemberObject(so, "shapeInfo");
}
}
internal sealed partial class AutosizeInfo : FormatInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.objectCount = deserializer.DeserializeIntMemberVariable(so, "objectCount");
}
}
internal sealed partial class FormatStartData : StartData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
// for the base class the shapeInfo is optional, but it's mandatory for this class
deserializer.VerifyDataNotNull(this.shapeInfo, "shapeInfo");
this.pageHeaderEntry = (PageHeaderEntry)deserializer.DeserializeMemberObject(so, "pageHeaderEntry");
this.pageFooterEntry = (PageFooterEntry)deserializer.DeserializeMemberObject(so, "pageFooterEntry");
this.autosizeInfo = (AutosizeInfo)deserializer.DeserializeMemberObject(so, "autosizeInfo");
}
}
internal sealed partial class FormatEntryData : PacketInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.formatEntryInfo = (FormatEntryInfo)deserializer.DeserializeMandatoryMemberObject(so, "formatEntryInfo");
this.outOfBand = deserializer.DeserializeBoolMemberVariable(so, "outOfBand");
this.writeStream = deserializer.DeserializeWriteStreamTypeMemberVariable(so);
this.isHelpObject = so.IsHelpObject;
}
}
internal sealed partial class WideViewHeaderInfo : ShapeInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.columns = deserializer.DeserializeIntMemberVariable(so, "columns");
}
}
internal sealed partial class TableHeaderInfo : ShapeInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
// The "repeatHeader" property was added later (V5, V6) and presents an incompatibility when remoting to older version PowerShell sessions.
// When the property is missing from the serialized object, let the deserialized property be false.
this.repeatHeader = deserializer.DeserializeBoolMemberVariable(so, "repeatHeader", cannotBeNull: false);
this.hideHeader = deserializer.DeserializeBoolMemberVariable(so, "hideHeader");
FormatInfoDataListDeserializer<TableColumnInfo>.ReadList(so, "tableColumnInfoList", this.tableColumnInfoList, deserializer);
}
}
internal sealed partial class TableColumnInfo : FormatInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.width = deserializer.DeserializeIntMemberVariable(so, "width");
this.alignment = deserializer.DeserializeIntMemberVariable(so, "alignment");
this.label = deserializer.DeserializeStringMemberVariable(so, "label");
this.propertyName = deserializer.DeserializeStringMemberVariable(so, "propertyName");
}
}
internal sealed partial class RawTextFormatEntry : FormatEntryInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.text = deserializer.DeserializeStringMemberVariableRaw(so, "text");
}
}
internal abstract partial class FreeFormatEntry : FormatEntryInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
FormatInfoDataListDeserializer<FormatValue>.ReadList(so, "formatValueList", this.formatValueList, deserializer);
}
}
internal sealed partial class ListViewEntry : FormatEntryInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
FormatInfoDataListDeserializer<ListViewField>.ReadList(so, "listViewFieldList", this.listViewFieldList, deserializer);
}
}
internal sealed partial class ListViewField : FormatInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.label = deserializer.DeserializeStringMemberVariable(so, "label");
this.propertyName = deserializer.DeserializeStringMemberVariable(so, "propertyName");
this.formatPropertyField = (FormatPropertyField)deserializer.DeserializeMandatoryMemberObject(so, "formatPropertyField");
}
}
internal sealed partial class TableRowEntry : FormatEntryInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
FormatInfoDataListDeserializer<FormatPropertyField>.ReadList(so, "formatPropertyFieldList", this.formatPropertyFieldList, deserializer);
this.multiLine = deserializer.DeserializeBoolMemberVariable(so, "multiLine");
}
}
internal sealed partial class WideViewEntry : FormatEntryInfo
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.formatPropertyField = (FormatPropertyField)deserializer.DeserializeMandatoryMemberObject(so, "formatPropertyField");
}
}
internal sealed partial class FormatTextField : FormatValue
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.text = deserializer.DeserializeStringMemberVariable(so, "text");
}
}
internal sealed partial class FormatPropertyField : FormatValue
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.propertyValue = deserializer.DeserializeStringMemberVariable(so, "propertyValue");
this.alignment = deserializer.DeserializeIntMemberVariable(so, "alignment");
}
}
internal sealed partial class FormatEntry : FormatValue
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
FormatInfoDataListDeserializer<FormatValue>.ReadList(so, "formatValueList", this.formatValueList, deserializer);
this.frameInfo = (FrameInfo)deserializer.DeserializeMemberObject(so, "frameInfo");
}
}
internal sealed partial class FrameInfo : FormatInfoData
{
internal override void Deserialize(PSObject so, FormatObjectDeserializer deserializer)
{
base.Deserialize(so, deserializer);
this.leftIndentation = deserializer.DeserializeIntMemberVariable(so, "leftIndentation");
this.rightIndentation = deserializer.DeserializeIntMemberVariable(so, "rightIndentation");
this.firstLine = deserializer.DeserializeIntMemberVariable(so, "firstLine");
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Terra.WebUI.Models;
using Terra.WebUI.Models.AccountViewModels;
using Terra.WebUI.Services;
namespace Terra.WebUI.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace WarZ
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class FPSCamera : Camera
{
private const float _rotationSpeed = 0.005f;
private MouseState _originalMouseState;
private float _moveSpeed = 20f;//0.02f;
private float _standingOffset = 4f;
private float _crouchedOffset = 1.5f;
private bool keyW_pressed, keyA_pressed, keyS_pressed, keyD_pressed, keyQ_pressed, keyZ_pressed;
public FPSCamera(Game game, Vector3 position, Vector3 target, Vector3 up)
: base(game, position, target, up)
{
_yaw = 0;
_pitch = 0;
//_verticalOffset = _standingOffset;
Mouse.SetPosition(Game.GraphicsDevice.Viewport.Width / 2, Game.GraphicsDevice.Viewport.Height / 2);
_originalMouseState = Mouse.GetState();
}
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize()
{
// TODO: Add your initialization code here
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
MouseState currentMouseState = Mouse.GetState();
//KeyboardState keyState = Keyboard.GetState();
if (currentMouseState != _originalMouseState)
{
float xDifference = currentMouseState.X - _originalMouseState.X;
float yDifference = currentMouseState.Y - _originalMouseState.Y;
_yaw -= _rotationSpeed*xDifference;
_pitch -= _rotationSpeed*yDifference;
Mouse.SetPosition(Game.GraphicsDevice.Viewport.Width / 2, Game.GraphicsDevice.Viewport.Height / 2);
}
/*
if (keyState.IsKeyDown(Keys.Up) || keyState.IsKeyDown(Keys.W)) //Forward
AddToCameraPosition(new Vector3(0, 0, -1), gameTime);
if (keyState.IsKeyDown(Keys.Down) || keyState.IsKeyDown(Keys.S)) //Backward
AddToCameraPosition(new Vector3(0, 0, 1), gameTime);
if (keyState.IsKeyDown(Keys.Right) || keyState.IsKeyDown(Keys.D)) //Right
AddToCameraPosition(new Vector3(1, 0, 0), gameTime);
if (keyState.IsKeyDown(Keys.Left) || keyState.IsKeyDown(Keys.A)) //Left
AddToCameraPosition(new Vector3(-1, 0, 0), gameTime);
if (keyState.IsKeyDown(Keys.Q)) //Up
AddToCameraPosition(new Vector3(0, 1, 0), gameTime);
if (keyState.IsKeyDown(Keys.Z)) //Down
AddToCameraPosition(new Vector3(0, -1, 0), gameTime);
if (keyState.IsKeyDown(Keys.LeftControl))
_verticalOffset = _crouchedOffset;
else
_verticalOffset = _standingOffset;
* */
UpdateViewMatrix();
base.Update(gameTime);
}
private void AddToCameraPosition(Vector3 vectorToAdd, GameTime gameTime)
{
Matrix cameraRotation = Matrix.CreateRotationX(_pitch) * Matrix.CreateRotationY(_yaw);
Vector3 rotatedVector = Vector3.Transform(vectorToAdd, cameraRotation);
_position += rotatedVector * (float)gameTime.ElapsedGameTime.TotalSeconds * _moveSpeed;
UpdateViewMatrix();
}
public override void UpdateViewMatrix()
{
Matrix cameraRotation = Matrix.CreateRotationX(_pitch) * Matrix.CreateRotationY(_yaw);
Vector3 cameraOriginalTarget = Vector3.Forward;
Vector3 cameraOriginalUpVector = Vector3.Up;
Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
Vector3 cameraFinalTarget = _position + cameraRotatedTarget;
Vector3 cameraRotatedUpVector = Vector3.Transform(cameraOriginalUpVector, cameraRotation);
Vector3 cameraFinalUpVector = _position + cameraRotatedUpVector;
_position += Vector3.Transform(_offset, cameraRotation);
_view = Matrix.CreateLookAt(_position, cameraFinalTarget + _offset.Y * Vector3.Up, cameraRotatedUpVector);
}
public void ToggleCrouch()
{
_offset.Y = _offset.Y.CompareTo(_standingOffset) == 0 ? _crouchedOffset : _standingOffset;
}
#region Properties
public new Vector3 Position
{
get { return _position; }
set
{
_position = value;
this.UpdateViewMatrix();
}
}
public Vector3 TargetPosition
{
get
{
Matrix cameraRotation = Matrix.CreateRotationX(_pitch) * Matrix.CreateRotationY(_yaw);
Vector3 cameraOriginalTarget = new Vector3(0, 0, -1);
Vector3 cameraRotatedTarget = Vector3.Transform(cameraOriginalTarget, cameraRotation);
Vector3 cameraFinalTarget = _position + cameraRotatedTarget;
return cameraFinalTarget;
}
}
public Vector3 Forward
{
get
{
Matrix cameraRotation = Matrix.CreateRotationX(_pitch) * Matrix.CreateRotationY(_yaw);
Vector3 cameraForward = new Vector3(0, 0, -1);
Vector3 cameraRotatedForward = Vector3.Transform(cameraForward, cameraRotation);
return cameraRotatedForward;
}
}
public Vector3 SideVector
{
get
{
Matrix cameraRotation = Matrix.CreateRotationX(_pitch) * Matrix.CreateRotationY(_yaw);
Vector3 cameraOriginalSide = new Vector3(1, 0, 0);
Vector3 cameraRotatedSide = Vector3.Transform(cameraOriginalSide, cameraRotation);
return cameraRotatedSide;
}
}
public Vector3 UpVector
{
get
{
Matrix cameraRotation = Matrix.CreateRotationX(_pitch) * Matrix.CreateRotationY(_yaw);
Vector3 cameraOriginalUp = new Vector3(0, 1, 0);
Vector3 cameraRotatedUp = Vector3.Transform(cameraOriginalUp, cameraRotation);
return cameraRotatedUp;
}
}
#region inputProperties
public bool KeyWPressed
{
get { return keyW_pressed; }
set { keyW_pressed = value; }
}
public bool KeyAPressed
{
get { return keyA_pressed; }
set { keyA_pressed = value; }
}
public bool KeySPressed
{
get { return keyS_pressed; }
set { keyS_pressed = value; }
}
public bool KeyDPressed
{
get { return keyD_pressed; }
set { keyD_pressed = value; }
}
public bool KeyQPressed
{
get { return keyQ_pressed; }
set { keyQ_pressed = value; }
}
public bool KeyZPressed
{
get { return keyZ_pressed; }
set { keyZ_pressed = value; }
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace Provision.AspNet.Identity.PlainSql
{
/// <summary>
/// Class that represents the AspNetUsers table in the SQL database.
/// </summary>
internal class UserTable<TUser>
where TUser : IdentityUser, new()
{
private readonly SqlDatabase _database;
/// <summary>
/// Constructor that takes a SQL database instance.
/// </summary>
/// <param name="database"></param>
public UserTable(SqlDatabase database)
{
_database = database;
}
/// <summary>
/// Gets the user's name, provided with an ID.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public String GetUserName(Guid userId)
{
const string commandText = "SELECT \"UserName\" FROM \"AspNetUsers\" WHERE \"Id\" = @id";
var parameters = new Dictionary<String, Object>() { { "@id", userId } };
return _database.GetString(commandText, parameters);
}
/// <summary>
/// Gets the user's ID, provided with a user name.
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public String GetUserId(String userName)
{
if (String.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException(nameof(userName));
//Due to SQL's case sensitivity, we have another column for the user name in lowercase.
userName = userName.ToLower(System.Globalization.CultureInfo.InvariantCulture);
const string commandText = "SELECT \"Id\" FROM \"AspNetUsers\" WHERE LOWER(\"UserName\") = @name";
var parameters = new Dictionary<String, Object>() { { "@name", userName } };
return _database.GetString(commandText, parameters);
}
/// <summary>
/// Returns all users.
/// </summary>
/// <returns></returns>
public IEnumerable<TUser> GetAllUsers()
{
var users = new List<TUser>();
const string commandText = "SELECT * FROM \"AspNetUsers\"";
var rows = _database.Query(commandText, new Dictionary<String, Object>());
foreach (var row in rows) {
var user = new TUser {
Id = Guid.Parse(row["Id"]),
UserName = row["UserName"],
PasswordHash = String.IsNullOrEmpty(row["PasswordHash"]) ? null : row["PasswordHash"],
SecurityStamp = String.IsNullOrEmpty(row["SecurityStamp"]) ? null : row["SecurityStamp"],
Email = String.IsNullOrEmpty(row["Email"]) ? null : row["Email"],
EmailConfirmed = row["EmailConfirmed"] == "True"
};
users.Add(user);
}
return users;
}
public TUser GetUserById(Guid userId)
{
TUser user = null;
const string commandText = "SELECT * FROM \"AspNetUsers\" WHERE \"Id\" = @id";
var parameters = new Dictionary<String, Object>() { { "@id", userId } };
var rows = _database.Query(commandText, parameters);
if (rows != null && rows.Count == 1) {
var row = rows[0];
user = new TUser {
Id = Guid.Parse(row["Id"]),
UserName = row["UserName"],
PasswordHash = String.IsNullOrEmpty(row["PasswordHash"]) ? null : row["PasswordHash"],
SecurityStamp = String.IsNullOrEmpty(row["SecurityStamp"]) ? null : row["SecurityStamp"],
Email = String.IsNullOrEmpty(row["Email"]) ? null : row["Email"],
EmailConfirmed = row["EmailConfirmed"] == "True"
};
}
return user;
}
/// <summary>
/// Returns a list of TUser instances given a user name.
/// </summary>
/// <param name="userName">User's name.</param>
/// <returns></returns>
public IEnumerable<TUser> GetUserByName(String userName)
{
if (String.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException(nameof(userName));
//Due to SQL's case sensitivity, we have another column for the user name in lowercase.
userName = userName.ToLower(System.Globalization.CultureInfo.InvariantCulture);
var users = new List<TUser>();
const string commandText = "SELECT * FROM \"AspNetUsers\" WHERE LOWER(\"UserName\") = @name";
var parameters = new Dictionary<String, Object>() { { "@name", userName } };
var rows = _database.Query(commandText, parameters);
foreach (var row in rows) {
var user = new TUser {
Id = Guid.Parse(row["Id"]),
UserName = row["UserName"],
PasswordHash = String.IsNullOrEmpty(row["PasswordHash"]) ? null : row["PasswordHash"],
SecurityStamp = String.IsNullOrEmpty(row["SecurityStamp"]) ? null : row["SecurityStamp"],
Email = String.IsNullOrEmpty(row["Email"]) ? null : row["Email"],
EmailConfirmed = row["EmailConfirmed"] == "True"
};
users.Add(user);
}
return users;
}
/// <summary>
/// Returns a list of TUser instances given a user email.
/// </summary>
/// <param name="email">User's email address.</param>
/// <returns></returns>
public IEnumerable<TUser> GetUserByEmail(String email)
{
if (String.IsNullOrWhiteSpace(email))
throw new ArgumentNullException(nameof(email));
//Due to SQL's case sensitivity, we have another column for the user name in lowercase.
email = email.ToLower(System.Globalization.CultureInfo.InvariantCulture);
var users = new List<TUser>();
const string commandText = "SELECT * FROM \"AspNetUsers\" WHERE LOWER(\"Email\") = @email";
var parameters = new Dictionary<String, Object>() { { "@email", email } };
var rows = _database.Query(commandText, parameters);
foreach (var row in rows) {
var user = new TUser {
Id = Guid.Parse(row["Id"]),
UserName = row["UserName"],
PasswordHash = String.IsNullOrEmpty(row["PasswordHash"]) ? null : row["PasswordHash"],
SecurityStamp = String.IsNullOrEmpty(row["SecurityStamp"]) ? null : row["SecurityStamp"],
Email = String.IsNullOrEmpty(row["Email"]) ? null : row["Email"],
EmailConfirmed = row["EmailConfirmed"] == "True"
};
users.Add(user);
}
return users;
}
/// <summary>
/// Return the user's password hash.
/// </summary>
/// <param name="userId">The user's id.</param>
/// <returns></returns>
public String GetPasswordHash(Guid userId)
{
const string commandText = "SELECT \"PasswordHash\" FROM \"AspNetUsers\" WHERE \"Id\" = @id";
var parameters = new Dictionary<String, Object>();
parameters.Add("@id", userId);
var passHash = _database.GetString(commandText, parameters);
if (String.IsNullOrEmpty(passHash)) {
return null;
}
return passHash;
}
/// <summary>
/// Sets the user's password hash.
/// </summary>
/// <param name="userId"></param>
/// <param name="passwordHash"></param>
/// <returns></returns>
public Int32 SetPasswordHash(Guid userId, String passwordHash)
{
if (String.IsNullOrWhiteSpace(passwordHash))
throw new ArgumentNullException(nameof(passwordHash));
const string commandText = "UPDATE \"AspNetUsers\" SET \"PasswordHash\" = @pwdHash WHERE \"Id\" = @id";
var parameters = new Dictionary<String, Object>();
parameters.Add("@pwdHash", passwordHash);
parameters.Add("@id", userId);
return _database.Execute(commandText, parameters);
}
/// <summary>
/// Returns the user's security stamp.
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public String GetSecurityStamp(Guid userId)
{
const string commandText = "SELECT \"SecurityStamp\" FROM \"AspNetUsers\" WHERE \"Id\" = @id";
var parameters = new Dictionary<String, Object>() { { "@id", userId } };
var result = _database.GetString(commandText, parameters);
return result;
}
/// <summary>
/// Inserts a new user in the AspNetUsers table.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public Int32 Insert(TUser user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
const string commandText = @"
INSERT INTO ""AspNetUsers""(""Id"", ""UserName"", ""PasswordHash"", ""SecurityStamp"", ""Email"", ""EmailConfirmed"")
VALUES (@id, @name, @pwdHash, @SecStamp, @email, @emailconfirmed);";
var parameters = new Dictionary<String, Object>();
parameters.Add("@name", user.UserName);
parameters.Add("@id", user.Id);
parameters.Add("@pwdHash", user.PasswordHash);
parameters.Add("@SecStamp", user.SecurityStamp);
parameters.Add("@email", user.Email);
parameters.Add("@emailconfirmed", user.EmailConfirmed);
return _database.Execute(commandText, parameters);
}
/// <summary>
/// Deletes a user from the AspNetUsers table.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public Int32 Delete(TUser user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
return Delete(user.Id);
}
/// <summary>
/// Updates a user in the AspNetUsers table.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public Int32 Update(TUser user)
{
if (user == null)
throw new ArgumentNullException(nameof(user));
const string commandText = "UPDATE \"AspNetUsers\" SET \"UserName\" = @userName, \"PasswordHash\" = @pswHash, \"SecurityStamp\" = @secStamp, \"Email\"= @email, \"EmailConfirmed\" = @emailconfirmed WHERE \"Id\" = @userId;";
var parameters = new Dictionary<String, Object>();
parameters.Add("@userName", user.UserName);
parameters.Add("@pswHash", user.PasswordHash);
parameters.Add("@secStamp", user.SecurityStamp);
parameters.Add("@userId", user.Id);
parameters.Add("@email", user.Email);
parameters.Add("@emailconfirmed", user.EmailConfirmed);
return _database.Execute(commandText, parameters);
}
/// <summary>
/// Deletes a user from the AspNetUsers table.
/// </summary>
/// <param name="userId">The user's id.</param>
/// <returns></returns>
private Int32 Delete(Guid userId)
{
const string commandText = "DELETE FROM \"AspNetUsers\" WHERE \"Id\" = @userId";
var parameters = new Dictionary<String, Object>();
parameters.Add("@userId", userId);
return _database.Execute(commandText, parameters);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// The BigNumber class implements methods for formatting and parsing
// big numeric values. To format and parse numeric values, applications should
// use the Format and Parse methods provided by the numeric
// classes (BigInteger). Those
// Format and Parse methods share a common implementation
// provided by this class, and are thus documented in detail here.
//
// Formatting
//
// The Format methods provided by the numeric classes are all of the
// form
//
// public static String Format(XXX value, String format);
// public static String Format(XXX value, String format, NumberFormatInfo info);
//
// where XXX is the name of the particular numeric class. The methods convert
// the numeric value to a string using the format string given by the
// format parameter. If the format parameter is null or
// an empty string, the number is formatted as if the string "G" (general
// format) was specified. The info parameter specifies the
// NumberFormatInfo instance to use when formatting the number. If the
// info parameter is null or omitted, the numeric formatting information
// is obtained from the current culture. The NumberFormatInfo supplies
// such information as the characters to use for decimal and thousand
// separators, and the spelling and placement of currency symbols in monetary
// values.
//
// Format strings fall into two categories: Standard format strings and
// user-defined format strings. A format string consisting of a single
// alphabetic character (A-Z or a-z), optionally followed by a sequence of
// digits (0-9), is a standard format string. All other format strings are
// used-defined format strings.
//
// A standard format string takes the form Axx, where A is an
// alphabetic character called the format specifier and xx is a
// sequence of digits called the precision specifier. The format
// specifier controls the type of formatting applied to the number and the
// precision specifier controls the number of significant digits or decimal
// places of the formatting operation. The following table describes the
// supported standard formats.
//
// C c - Currency format. The number is
// converted to a string that represents a currency amount. The conversion is
// controlled by the currency format information of the NumberFormatInfo
// used to format the number. The precision specifier indicates the desired
// number of decimal places. If the precision specifier is omitted, the default
// currency precision given by the NumberFormatInfo is used.
//
// D d - Decimal format. This format is
// supported for integral types only. The number is converted to a string of
// decimal digits, prefixed by a minus sign if the number is negative. The
// precision specifier indicates the minimum number of digits desired in the
// resulting string. If required, the number will be left-padded with zeros to
// produce the number of digits given by the precision specifier.
//
// E e Engineering (scientific) format.
// The number is converted to a string of the form
// "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative, and one digit always precedes the decimal point. The
// precision specifier indicates the desired number of digits after the decimal
// point. If the precision specifier is omitted, a default of 6 digits after
// the decimal point is used. The format specifier indicates whether to prefix
// the exponent with an 'E' or an 'e'. The exponent is always consists of a
// plus or minus sign and three digits.
//
// F f Fixed point format. The number is
// converted to a string of the form "-ddd.ddd....", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. The precision specifier indicates the desired number of
// decimal places. If the precision specifier is omitted, the default numeric
// precision given by the NumberFormatInfo is used.
//
// G g - General format. The number is
// converted to the shortest possible decimal representation using fixed point
// or scientific format. The precision specifier determines the number of
// significant digits in the resulting string. If the precision specifier is
// omitted, the number of significant digits is determined by the type of the
// number being converted (10 for int, 19 for long, 7 for
// float, 15 for double, 19 for Currency, and 29 for
// Decimal). Trailing zeros after the decimal point are removed, and the
// resulting string contains a decimal point only if required. The resulting
// string uses fixed point format if the exponent of the number is less than
// the number of significant digits and greater than or equal to -4. Otherwise,
// the resulting string uses scientific format, and the case of the format
// specifier controls whether the exponent is prefixed with an 'E' or an
// 'e'.
//
// N n Number format. The number is
// converted to a string of the form "-d,ddd,ddd.ddd....", where
// each 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. Thousand separators are inserted between each group of
// three digits to the left of the decimal point. The precision specifier
// indicates the desired number of decimal places. If the precision specifier
// is omitted, the default numeric precision given by the
// NumberFormatInfo is used.
//
// X x - Hexadecimal format. This format is
// supported for integral types only. The number is converted to a string of
// hexadecimal digits. The format specifier indicates whether to use upper or
// lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF',
// and 'x' for 'abcdef'). The precision specifier indicates the minimum number
// of digits desired in the resulting string. If required, the number will be
// left-padded with zeros to produce the number of digits given by the
// precision specifier.
//
// Some examples of standard format strings and their results are shown in the
// table below. (The examples all assume a default NumberFormatInfo.)
//
// Value Format Result
// 12345.6789 C $12,345.68
// -12345.6789 C ($12,345.68)
// 12345 D 12345
// 12345 D8 00012345
// 12345.6789 E 1.234568E+004
// 12345.6789 E10 1.2345678900E+004
// 12345.6789 e4 1.2346e+004
// 12345.6789 F 12345.68
// 12345.6789 F0 12346
// 12345.6789 F6 12345.678900
// 12345.6789 G 12345.6789
// 12345.6789 G7 12345.68
// 123456789 G7 1.234568E8
// 12345.6789 N 12,345.68
// 123456789 N4 123,456,789.0000
// 0x2c45e x 2c45e
// 0x2c45e X 2C45E
// 0x2c45e X8 0002C45E
//
// Format strings that do not start with an alphabetic character, or that start
// with an alphabetic character followed by a non-digit, are called
// user-defined format strings. The following table describes the formatting
// characters that are supported in user defined format strings.
//
//
// 0 - Digit placeholder. If the value being
// formatted has a digit in the position where the '0' appears in the format
// string, then that digit is copied to the output string. Otherwise, a '0' is
// stored in that position in the output string. The position of the leftmost
// '0' before the decimal point and the rightmost '0' after the decimal point
// determines the range of digits that are always present in the output
// string.
//
// # - Digit placeholder. If the value being
// formatted has a digit in the position where the '#' appears in the format
// string, then that digit is copied to the output string. Otherwise, nothing
// is stored in that position in the output string.
//
// . - Decimal point. The first '.' character
// in the format string determines the location of the decimal separator in the
// formatted value; any additional '.' characters are ignored. The actual
// character used as a the decimal separator in the output string is given by
// the NumberFormatInfo used to format the number.
//
// , - Thousand separator and number scaling.
// The ',' character serves two purposes. First, if the format string contains
// a ',' character between two digit placeholders (0 or #) and to the left of
// the decimal point if one is present, then the output will have thousand
// separators inserted between each group of three digits to the left of the
// decimal separator. The actual character used as a the decimal separator in
// the output string is given by the NumberFormatInfo used to format the
// number. Second, if the format string contains one or more ',' characters
// immediately to the left of the decimal point, or after the last digit
// placeholder if there is no decimal point, then the number will be divided by
// 1000 times the number of ',' characters before it is formatted. For example,
// the format string '0,,' will represent 100 million as just 100. Use of the
// ',' character to indicate scaling does not also cause the formatted number
// to have thousand separators. Thus, to scale a number by 1 million and insert
// thousand separators you would use the format string '#,##0,,'.
//
// % - Percentage placeholder. The presence of
// a '%' character in the format string causes the number to be multiplied by
// 100 before it is formatted. The '%' character itself is inserted in the
// output string where it appears in the format string.
//
// E+ E- e+ e- - Scientific notation.
// If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format
// string and are immediately followed by at least one '0' character, then the
// number is formatted using scientific notation with an 'E' or 'e' inserted
// between the number and the exponent. The number of '0' characters following
// the scientific notation indicator determines the minimum number of digits to
// output for the exponent. The 'E+' and 'e+' formats indicate that a sign
// character (plus or minus) should always precede the exponent. The 'E-' and
// 'e-' formats indicate that a sign character should only precede negative
// exponents.
//
// \ - Literal character. A backslash character
// causes the next character in the format string to be copied to the output
// string as-is. The backslash itself isn't copied, so to place a backslash
// character in the output string, use two backslashes (\\) in the format
// string.
//
// 'ABC' "ABC" - Literal string. Characters
// enclosed in single or double quotation marks are copied to the output string
// as-is and do not affect formatting.
//
// ; - Section separator. The ';' character is
// used to separate sections for positive, negative, and zero numbers in the
// format string.
//
// Other - All other characters are copied to
// the output string in the position they appear.
//
// For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or
// 'e-'), the number is rounded to as many decimal places as there are digit
// placeholders to the right of the decimal point. If the format string does
// not contain a decimal point, the number is rounded to the nearest
// integer. If the number has more digits than there are digit placeholders to
// the left of the decimal point, the extra digits are copied to the output
// string immediately before the first digit placeholder.
//
// For scientific formats, the number is rounded to as many significant digits
// as there are digit placeholders in the format string.
//
// To allow for different formatting of positive, negative, and zero values, a
// user-defined format string may contain up to three sections separated by
// semicolons. The results of having one, two, or three sections in the format
// string are described in the table below.
//
// Sections:
//
// One - The format string applies to all values.
//
// Two - The first section applies to positive values
// and zeros, and the second section applies to negative values. If the number
// to be formatted is negative, but becomes zero after rounding according to
// the format in the second section, then the resulting zero is formatted
// according to the first section.
//
// Three - The first section applies to positive
// values, the second section applies to negative values, and the third section
// applies to zeros. The second section may be left empty (by having no
// characters between the semicolons), in which case the first section applies
// to all non-zero values. If the number to be formatted is non-zero, but
// becomes zero after rounding according to the format in the first or second
// section, then the resulting zero is formatted according to the third
// section.
//
// For both standard and user-defined formatting operations on values of type
// float and double, if the value being formatted is a NaN (Not
// a Number) or a positive or negative infinity, then regardless of the format
// string, the resulting string is given by the NaNSymbol,
// PositiveInfinitySymbol, or NegativeInfinitySymbol property of
// the NumberFormatInfo used to format the number.
//
// Parsing
//
// The Parse methods provided by the numeric classes are all of the form
//
// public static XXX Parse(String s);
// public static XXX Parse(String s, int style);
// public static XXX Parse(String s, int style, NumberFormatInfo info);
//
// where XXX is the name of the particular numeric class. The methods convert a
// string to a numeric value. The optional style parameter specifies the
// permitted style of the numeric string. It must be a combination of bit flags
// from the NumberStyles enumeration. The optional info parameter
// specifies the NumberFormatInfo instance to use when parsing the
// string. If the info parameter is null or omitted, the numeric
// formatting information is obtained from the current culture.
//
// Numeric strings produced by the Format methods using the Currency,
// Decimal, Engineering, Fixed point, General, or Number standard formats
// (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable
// by the Parse methods if the NumberStyles.Any style is
// specified. Note, however, that the Parse methods do not accept
// NaNs or Infinities.
//
namespace System.Numerics {
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using Conditional = System.Diagnostics.ConditionalAttribute;
internal static class BigNumber {
#if !SILVERLIGHT || FEATURE_NETCORE
private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign
| NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
internal struct BigNumberBuffer {
public StringBuilder digits;
public int precision;
public int scale;
public bool sign; // negative sign exists
public static BigNumberBuffer Create() {
BigNumberBuffer number = new BigNumberBuffer();
number.digits = new StringBuilder();
return number;
}
}
internal static bool TryValidateParseStyleInteger(NumberStyles style, out ArgumentException e) {
// Check for undefined flags
if ((style & InvalidNumberStyles) != 0) {
e = new ArgumentException(SR.GetString(SR.Argument_InvalidNumberStyles, "style"));
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
if ((style & ~NumberStyles.HexNumber) != 0) {
e = new ArgumentException(SR.GetString(SR.Argument_InvalidHexStyle));
return false;
}
}
e = null;
return true;
}
[SecuritySafeCritical]
internal unsafe static Boolean TryParseBigInteger(String value, NumberStyles style, NumberFormatInfo info, out BigInteger result) {
result = BigInteger.Zero;
ArgumentException e;
if (!TryValidateParseStyleInteger(style, out e))
throw e; // TryParse still throws ArgumentException on invalid NumberStyles
BigNumberBuffer bignumber = BigNumberBuffer.Create();
Byte * numberBufferBytes = stackalloc Byte[Number.NumberBuffer.NumberBufferBytes];
Number.NumberBuffer number = new Number.NumberBuffer(numberBufferBytes);
result = 0;
if (!Number.TryStringToNumber(value, style, ref number, bignumber.digits, info, false)) {
return false;
}
bignumber.precision = number.precision;
bignumber.scale = number.scale;
bignumber.sign = number.sign;
if ((style & NumberStyles.AllowHexSpecifier) != 0) {
if (!HexNumberToBigInteger(ref bignumber, ref result)) {
return false;
}
}
else {
if (!NumberToBigInteger(ref bignumber, ref result)) {
return false;
}
}
return true;
}
internal unsafe static BigInteger ParseBigInteger(String value, NumberStyles style, NumberFormatInfo info) {
if (value == null)
throw new ArgumentNullException("value");
ArgumentException e;
if (!TryValidateParseStyleInteger(style, out e))
throw e;
BigInteger result = BigInteger.Zero;
if (!TryParseBigInteger(value, style, info, out result)) {
throw new FormatException(SR.GetString(SR.Overflow_ParseBigInteger));
}
return result;
}
private unsafe static Boolean HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) {
if (number.digits == null || number.digits.Length == 0)
return false;
int len = number.digits.Length - 1; // ignore trailing '\0'
byte[] bits = new byte[(len / 2) + (len % 2)];
bool shift = false;
bool isNegative = false;
int bitIndex = 0;
// parse the string into a little-endian two's complement byte array
// string value : O F E B 7 \0
// string index (i) : 0 1 2 3 4 5 <--
// byte[] (bitIndex): 2 1 1 0 0 <--
//
for (int i = len-1; i > -1; i--) {
char c = number.digits[i];
byte b;
if (c >= '0' && c <= '9') {
b = (byte)(c - '0');
}
else if (c >= 'A' && c <= 'F') {
b = (byte)((c - 'A') + 10);
}
else {
Contract.Assert(c >= 'a' && c <= 'f');
b = (byte)((c - 'a') + 10);
}
if (i == 0 && (b & 0x08) == 0x08)
isNegative = true;
if (shift) {
bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4));
bitIndex++;
}
else {
bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b);
}
shift = !shift;
}
value = new BigInteger(bits);
return true;
}
private unsafe static Boolean NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) {
Int32 i = number.scale;
Int32 cur = 0;
value = 0;
while (--i >= 0) {
value *= 10;
if (number.digits[cur] != '\0') {
value += (Int32)(number.digits[cur++] - '0');
}
}
while (number.digits[cur] != '\0') {
if (number.digits[cur++] != '0') return false; // disallow non-zero trailing decimal places
}
if (number.sign) {
value = -value;
}
return true;
}
#endif //!SILVERLIGHT ||FEATURE_NETCORE
// this function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier
internal static char ParseFormatSpecifier(String format, out Int32 digits) {
digits = -1;
if (String.IsNullOrEmpty(format)) {
return 'R';
}
int i = 0;
char ch = format[i];
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') {
i++;
int n = -1;
if (i < format.Length && format[i] >= '0' && format[i] <= '9') {
n = format[i++] - '0';
while (i < format.Length && format[i] >= '0' && format[i] <= '9') {
n = n * 10 + (format[i++] - '0');
if (n >= 10)
break;
}
}
if (i >= format.Length || format[i] == '\0') {
digits = n;
return ch;
}
}
return (char)0; // custom format
}
private static String FormatBigIntegerToHexString(BigInteger value, char format, int digits, NumberFormatInfo info) {
StringBuilder sb = new StringBuilder();
byte[] bits = value.ToByteArray();
String fmt = null;
int cur = bits.Length-1;
if (cur > -1) {
// [FF..F8] drop the high F as the two's complement negative number remains clear
// [F7..08] retain the high bits as the two's complement number is wrong without it
// [07..00] drop the high 0 as the two's complement positive number remains clear
bool clearHighF = false;
byte head = bits[cur];
if (head > 0xF7) {
head -= 0xF0;
clearHighF = true;
}
if (head < 0x08 || clearHighF) {
// {0xF8-0xFF} print as {8-F}
// {0x00-0x07} print as {0-7}
fmt = String.Format(CultureInfo.InvariantCulture, "{0}1", format);
sb.Append(head.ToString(fmt, info));
cur--;
}
}
if (cur > -1) {
fmt = String.Format(CultureInfo.InvariantCulture, "{0}2", format);
while (cur > -1) {
sb.Append(bits[cur--].ToString(fmt, info));
}
}
if (digits > 0 && digits > sb.Length) {
// insert leading zeros. User specified "X5" so we create "0ABCD" instead of "ABCD"
sb.Insert(0, (value._sign >= 0 ? ("0") : (format == 'x' ? "f" : "F")), digits - sb.Length);
}
return sb.ToString();
}
//
// internal [unsafe] static String FormatBigInteger(BigInteger value, String format, NumberFormatInfo info) {
//
#if !SILVERLIGHT ||FEATURE_NETCORE
[SecuritySafeCritical]
#endif // !SILVERLIGHT ||FEATURE_NETCORE
internal
#if !SILVERLIGHT ||FEATURE_NETCORE
unsafe
#endif //!SILVERLIGHT ||FEATURE_NETCORE
static String FormatBigInteger(BigInteger value, String format, NumberFormatInfo info) {
int digits = 0;
char fmt = ParseFormatSpecifier(format, out digits);
if (fmt == 'x' || fmt == 'X')
return FormatBigIntegerToHexString(value, fmt, digits, info);
bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R');
#if SILVERLIGHT ||FEATURE_NETCORE
if (!decimalFmt) {
// Silverlight supports invariant formats only
throw new FormatException(SR.GetString(SR.Format_InvalidFormatSpecifier));
}
#endif //SILVERLIGHT ||FEATURE_NETCORE
if (value._bits == null) {
if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R') {
if (digits > 0)
format = String.Format(CultureInfo.InvariantCulture, "D{0}", digits.ToString(CultureInfo.InvariantCulture));
else
format = "D";
}
return value._sign.ToString(format, info);
}
// First convert to base 10^9.
const uint kuBase = 1000000000; // 10^9
const int kcchBase = 9;
int cuSrc = BigInteger.Length(value._bits);
int cuMax;
try {
cuMax = checked(cuSrc * 10 / 9 + 2);
}
catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); }
uint[] rguDst = new uint[cuMax];
int cuDst = 0;
for (int iuSrc = cuSrc; --iuSrc >= 0; ) {
uint uCarry = value._bits[iuSrc];
for (int iuDst = 0; iuDst < cuDst; iuDst++) {
Contract.Assert(rguDst[iuDst] < kuBase);
ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry);
rguDst[iuDst] = (uint)(uuRes % kuBase);
uCarry = (uint)(uuRes / kuBase);
}
if (uCarry != 0) {
rguDst[cuDst++] = uCarry % kuBase;
uCarry /= kuBase;
if (uCarry != 0)
rguDst[cuDst++] = uCarry;
}
}
int cchMax;
try {
// Each uint contributes at most 9 digits to the decimal representation.
cchMax = checked(cuDst * kcchBase);
}
catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); }
if (decimalFmt) {
if (digits > 0 && digits > cchMax)
cchMax = digits;
if (value._sign < 0) {
try {
// Leave an extra slot for a minus sign.
cchMax = checked(cchMax + info.NegativeSign.Length);
}
catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); }
}
}
int rgchBufSize;
try {
// We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs
// to be null terminated. Let's ensure that we can allocate a buffer of that size.
rgchBufSize = checked(cchMax + 1);
} catch (OverflowException e) { throw new FormatException(SR.GetString(SR.Format_TooLarge), e); }
char[] rgch = new char[rgchBufSize];
int ichDst = cchMax;
for (int iuDst = 0; iuDst < cuDst - 1; iuDst++) {
uint uDig = rguDst[iuDst];
Contract.Assert(uDig < kuBase);
for (int cch = kcchBase; --cch >= 0; ) {
rgch[--ichDst] = (char)('0' + uDig % 10);
uDig /= 10;
}
}
for (uint uDig = rguDst[cuDst - 1]; uDig != 0; ) {
rgch[--ichDst] = (char)('0' + uDig % 10);
uDig /= 10;
}
#if !SILVERLIGHT ||FEATURE_NETCORE
if (!decimalFmt) {
//
// Go to the VM for GlobLoc aware formatting
//
Byte * numberBufferBytes = stackalloc Byte[Number.NumberBuffer.NumberBufferBytes];
Number.NumberBuffer number = new Number.NumberBuffer(numberBufferBytes);
// sign = true for negative and false for 0 and positive values
number.sign = (value._sign < 0);
// the cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form
number.precision = 29;
number.digits[0] = '\0';
number.scale = cchMax - ichDst;
int maxDigits = Math.Min(ichDst + 50, cchMax);
for (int i = ichDst; i < maxDigits; i++) {
number.digits[i - ichDst] = rgch[i];
}
fixed(char* pinnedExtraDigits = rgch) {
return Number.FormatNumberBuffer(number.PackForNative(), format, info, pinnedExtraDigits + ichDst);
}
}
#endif //!SILVERLIGHT ||FEATURE_NETCORE
// Format Round-trip decimal
// This format is supported for integral types only. The number is converted to a string of
// decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision
// specifier indicates the minimum number of digits desired in the resulting string. If required,
// the number is padded with zeros to its left to produce the number of digits given by the
// precision specifier.
int numDigitsPrinted = cchMax - ichDst;
while (digits > 0 && digits > numDigitsPrinted) {
// pad leading zeros
rgch[--ichDst] = '0';
digits--;
}
if (value._sign < 0) {
String negativeSign = info.NegativeSign;
for (int i = info.NegativeSign.Length - 1; i > -1; i--)
rgch[--ichDst] = info.NegativeSign[i];
}
return new String(rgch, ichDst, cchMax - ichDst);
}
}
}
| |
// 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.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// Library of XPathNode helper routines.
/// </summary>
internal abstract class XPathNodeHelper
{
/// <summary>
/// Return chain of namespace nodes. If specified node has no local namespaces, then 0 will be
/// returned. Otherwise, the first node in the chain is guaranteed to be a local namespace (its
/// parent is this node). Subsequent nodes may not have the same node as parent, so the caller will
/// need to test the parent in order to terminate a search that processes only local namespaces.
/// </summary>
public static int GetLocalNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
if (pageElem[idxElem].HasNamespaceDecls)
{
// Only elements have namespace nodes
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element);
return pageElem[idxElem].Document.LookupNamespaces(pageElem, idxElem, out pageNmsp);
}
pageNmsp = null;
return 0;
}
/// <summary>
/// Return chain of in-scope namespace nodes for nodes of type Element. Nodes in the chain might not
/// have this element as their parent. Since the xmlns:xml namespace node is always in scope, this
/// method will never return 0 if the specified node is an element.
/// </summary>
public static int GetInScopeNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
XPathDocument doc;
// Only elements have namespace nodes
if (pageElem[idxElem].NodeType == XPathNodeType.Element)
{
doc = pageElem[idxElem].Document;
// Walk ancestors, looking for an ancestor that has at least one namespace declaration
while (!pageElem[idxElem].HasNamespaceDecls)
{
idxElem = pageElem[idxElem].GetParent(out pageElem);
if (idxElem == 0)
{
// There are no namespace nodes declared on ancestors, so return xmlns:xml node
return doc.GetXmlNamespaceNode(out pageNmsp);
}
}
// Return chain of in-scope namespace nodes
return doc.LookupNamespaces(pageElem, idxElem, out pageNmsp);
}
pageNmsp = null;
return 0;
}
/// <summary>
/// Return the first attribute of the specified node. If no attribute exist, do not
/// set pageNode or idxNode and return false.
/// </summary>
public static bool GetFirstAttribute(ref XPathNode[] pageNode, ref int idxNode)
{
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (pageNode[idxNode].HasAttribute)
{
GetChild(ref pageNode, ref idxNode);
Debug.Assert(pageNode[idxNode].NodeType == XPathNodeType.Attribute);
return true;
}
return false;
}
/// <summary>
/// Return the next attribute sibling of the specified node. If the node is not itself an
/// attribute, or if there are no siblings, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetNextAttribute(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page;
int idx;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
idx = pageNode[idxNode].GetSibling(out page);
if (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute)
{
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return the first content-typed child of the specified node. If the node has no children, or
/// if the node is not content-typed, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].HasContentChild)
{
GetChild(ref page, ref idx);
// Skip past attribute children
while (page[idx].NodeType == XPathNodeType.Attribute)
{
idx = page[idx].GetSibling(out page);
Debug.Assert(idx != 0);
}
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return the next content-typed sibling of the specified node. If the node has no siblings, or
/// if the node is not content-typed, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (!page[idx].IsAttrNmsp)
{
idx = page[idx].GetSibling(out page);
if (idx != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
}
return false;
}
/// <summary>
/// Return the parent of the specified node. If the node has no parent, do not set pageNode
/// or idxNode and return false.
/// </summary>
public static bool GetParent(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
idx = page[idx].GetParent(out page);
if (idx != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return a location integer that can be easily compared with other locations from the same document
/// in order to determine the relative document order of two nodes.
/// </summary>
public static int GetLocation(XPathNode[] pageNode, int idxNode)
{
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
Debug.Assert(idxNode <= UInt16.MaxValue);
Debug.Assert(pageNode[0].PageInfo.PageNumber <= Int16.MaxValue);
return (pageNode[0].PageInfo.PageNumber << 16) | idxNode;
}
/// <summary>
/// Return the first element child of the specified node that has the specified name. If no such child exists,
/// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect
/// to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetElementChild(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Only check children if at least one element child exists
if (page[idx].HasElementChild)
{
GetChild(ref page, ref idx);
Debug.Assert(idx != 0);
// Find element with specified localName and namespaceName
do
{
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0);
}
return false;
}
/// <summary>
/// Return a following sibling element of the specified node that has the specified name. If no such
/// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and
/// return false. Assume that the localName has been atomized with respect to this document's name table,
/// but not the namespaceName.
/// </summary>
public static bool GetElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Elements should not be returned as "siblings" of attributes (namespaces don't link to elements, so don't need to check them)
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
idx = page[idx].GetSibling(out page);
if (idx == 0)
break;
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return the first child of the specified node that has the specified type (must be a content type). If no such
/// child exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Only check children if at least one content-typed child exists
if (page[idx].HasContentChild)
{
mask = XPathNavigatorEx.GetContentKindMask(typ);
GetChild(ref page, ref idx);
do
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
// Never return attributes, as Attribute is not a content type
if (typ == XPathNodeType.Attribute)
return false;
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0);
}
return false;
}
/// <summary>
/// Return a following sibling of the specified node that has the specified type. If no such
/// sibling exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask = XPathNavigatorEx.GetContentKindMask(typ);
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
idx = page[idx].GetSibling(out page);
if (idx == 0)
break;
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
Debug.Assert(typ != XPathNodeType.Attribute && typ != XPathNodeType.Namespace);
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return the first preceding sibling of the specified node. If no such sibling exists, then do not set
/// pageNode or idxNode and return false.
/// </summary>
public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] pageParent = pageNode, pagePrec, pageAnc;
int idxParent = idxNode, idxPrec, idxAnc;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
Debug.Assert(pageNode[idxNode].NodeType != XPathNodeType.Attribute);
// Since nodes are laid out in document order on pages, the algorithm is:
// 1. Get parent of current node
// 2. If no parent, then there is no previous sibling, so return false
// 3. Get node that immediately precedes the current node in document order
// 4. If preceding node is parent, then there is no previous sibling, so return false
// 5. Walk ancestors of preceding node, until parent of current node is found
idxParent = pageParent[idxParent].GetParent(out pageParent);
if (idxParent != 0)
{
idxPrec = idxNode - 1;
if (idxPrec == 0)
{
// Need to get previous page
pagePrec = pageNode[0].PageInfo.PreviousPage;
idxPrec = pagePrec.Length - 1;
}
else
{
// Previous node is on the same page
pagePrec = pageNode;
}
// If parent node is previous node, then no previous sibling
if (idxParent == idxPrec && pageParent == pagePrec)
return false;
// Find child of parent node by walking ancestor chain
pageAnc = pagePrec;
idxAnc = idxPrec;
do
{
pagePrec = pageAnc;
idxPrec = idxAnc;
idxAnc = pageAnc[idxAnc].GetParent(out pageAnc);
Debug.Assert(idxAnc != 0 && pageAnc != null);
}
while (idxAnc != idxParent || pageAnc != pageParent);
// We found the previous sibling, but if it's an attribute node, then return false
if (pagePrec[idxPrec].NodeType != XPathNodeType.Attribute)
{
pageNode = pagePrec;
idxNode = idxPrec;
return true;
}
}
return false;
}
/// <summary>
/// Return the attribute of the specified node that has the specified name. If no such attribute exists,
/// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect
/// to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetAttribute(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Find attribute with specified localName and namespaceName
if (page[idx].HasAttribute)
{
GetChild(ref page, ref idx);
do
{
if (page[idx].NameMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute);
}
return false;
}
/// <summary>
/// Get the next element node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered)
/// 3. Has the specified QName
/// If no such element exists, then do not set pageCurrent or idxCurrent and return false.
/// Assume that the localName has been atomized with respect to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetElementFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, string localName, string namespaceName)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
// If current node is an element having a matching name,
if (page[idx].NodeType == XPathNodeType.Element && (object)page[idx].LocalName == (object)localName)
{
// Then follow similar element name pointers
int idxPageEnd = 0;
int idxPageCurrent;
if (pageEnd != null)
{
idxPageEnd = pageEnd[0].PageInfo.PageNumber;
idxPageCurrent = page[0].PageInfo.PageNumber;
// If ending node is <= starting node in document order, then scan to end of document
if (idxPageCurrent > idxPageEnd || (idxPageCurrent == idxPageEnd && idx >= idxEnd))
pageEnd = null;
}
while (true)
{
idx = page[idx].GetSimilarElement(out page);
if (idx == 0)
break;
// Only scan to ending node
if (pageEnd != null)
{
idxPageCurrent = page[0].PageInfo.PageNumber;
if (idxPageCurrent > idxPageEnd)
break;
if (idxPageCurrent == idxPageEnd && idx >= idxEnd)
break;
}
if ((object)page[idx].LocalName == (object)localName && page[idx].NamespaceUri == namespaceName)
goto FoundNode;
}
return false;
}
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (page[idx].ElementMatch(localName, namespaceName))
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (page[idx].ElementMatch(localName, namespaceName))
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Get the next node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered)
/// 3. Has the specified XPathNodeType (but Attributes and Namespaces never match)
/// If no such node exists, then do not set pageCurrent or idxCurrent and return false.
/// </summary>
public static bool GetContentFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, XPathNodeType typ)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
int mask = XPathNavigatorEx.GetContentKindMask(typ);
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
Debug.Assert(typ != XPathNodeType.Text, "Text should be handled by GetTextFollowing in order to take into account collapsed text.");
Debug.Assert(page[idx].NodeType != XPathNodeType.Attribute, "Current node should never be an attribute or namespace--caller should handle this case.");
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following sibling/child/parent links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
Debug.Assert(!page[idx].IsAttrNmsp, "GetContentFollowing should never return attributes or namespaces.");
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Scan all nodes that follow the current node in document order, but precede the ending node in document order.
/// Return two types of nodes with non-null text:
/// 1. Element parents of collapsed text nodes (since it is the element parent that has the collapsed text)
/// 2. Non-collapsed text nodes
/// If no such node exists, then do not set pageCurrent or idxCurrent and return false.
/// </summary>
public static bool GetTextFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
Debug.Assert(!page[idx].IsAttrNmsp, "Current node should never be an attribute or namespace--caller should handle this case.");
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following sibling/child/parent links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText))
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText))
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order,
/// but is not a descendant. If no such node exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetNonDescendant(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
// Get page, idx at which to end sequential scan of nodes
do
{
// If the current node has a sibling,
if (page[idx].HasSibling)
{
// Then that is the first non-descendant
pageNode = page;
idxNode = page[idx].GetSibling(out pageNode);
return true;
}
// Otherwise, try finding a sibling at the parent level
idx = page[idx].GetParent(out page);
}
while (idx != 0);
return false;
}
/// <summary>
/// Return the page and index of the first child (attribute or content) of the specified node.
/// </summary>
private static void GetChild(ref XPathNode[] pageNode, ref int idxNode)
{
Debug.Assert(pageNode[idxNode].HasAttribute || pageNode[idxNode].HasContentChild, "Caller must check HasAttribute/HasContentChild on parent before calling GetChild.");
Debug.Assert(pageNode[idxNode].HasAttribute || !pageNode[idxNode].HasCollapsedText, "Text child is virtualized and therefore is not present in the physical node page.");
if (++idxNode >= pageNode.Length)
{
// Child is first node on next page
pageNode = pageNode[0].PageInfo.NextPage;
idxNode = 1;
}
// Else child is next node on this page
}
}
}
| |
/*
Copyright (c) 2012 Ant Micro <www.antmicro.com>
Authors:
* Konrad Kruczynski (kkruczynski@antmicro.com)
* Piotr Zierhoffer (pzierhoffer@antmicro.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using NUnit.Framework;
using System.IO;
using Antmicro.Migrant;
using System.Collections.Generic;
namespace Antmicro.Migrant.Tests
{
[TestFixture(false, false)]
[TestFixture(true, false)]
[TestFixture(false, true)]
[TestFixture(true, true)]
public class SurrogateTests : BaseTestWithSettings
{
public SurrogateTests(bool useGeneratedSerializer, bool useGeneratedDeserializer) : base(useGeneratedSerializer, useGeneratedDeserializer, false, false, false)
{
}
[Test]
public void ShouldPlaceObjectForSurrogate()
{
var b = new SurrogateMockB();
var pseudocopy = PseudoClone(b, serializer =>
{
serializer.ForSurrogate<SurrogateMockB>().SetObject(x => new SurrogateMockA(999));
});
var a = pseudocopy as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(999, a.Field);
}
[Test]
public void ShouldPlaceObjectForSurrogatePreservingIdentity()
{
var b = new SurrogateMockB();
var list = new List<object> { b, new List<object> { b }, new SurrogateMockB() };
var counter = 0;
var pseudocopy = PseudoClone(list, serializer =>
{
serializer.ForSurrogate<SurrogateMockB>().SetObject(x => new SurrogateMockA(counter++));
});
list = pseudocopy as List<object>;
Assert.IsNotNull(list);
var sublist = list[1] as List<object>;
Assert.IsNotNull(sublist);
Assert.AreSame(list[0], sublist[0]);
Assert.AreNotSame(list[0], list[2]);
var a = list[0] as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(counter - 2, a.Field);
var secondA = list[2] as SurrogateMockA;
Assert.IsNotNull(secondA);
Assert.AreEqual(counter - 1, secondA.Field);
}
[Test]
public void ShouldPlaceSurrogateForObject()
{
var b = new SurrogateMockB();
var pseudocopy = PseudoClone(b, serializer =>
{
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(1));
});
var a = pseudocopy as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(1, a.Field);
}
[Test]
public void ShouldPlaceSurrogateForObjectPreservingIdentity()
{
var b = new SurrogateMockB();
var counter = 0;
var list = new List<object> { b, new SurrogateMockB(), b };
var pseudocopy = PseudoClone(list, serializer =>
{
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(counter++));
});
list = pseudocopy as List<object>;
Assert.IsNotNull(list);
Assert.AreSame(list[0], list[2]);
Assert.AreNotSame(list[0], list[1]);
var a = list[0] as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(counter - 2, a.Field);
var secondA = list[1] as SurrogateMockA;
Assert.IsNotNull(secondA);
Assert.AreEqual(counter - 1, secondA.Field);
}
[Test]
public void ShouldDoSurrogateObjectSwap()
{
var b = new SurrogateMockB();
var pseudocopy = PseudoClone(b, serializer =>
{
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(1));
serializer.ForSurrogate<SurrogateMockA>().SetObject(x => new SurrogateMockC());
});
var c = pseudocopy as SurrogateMockC;
Assert.IsNotNull(c);
}
[Test]
public void ShouldPlaceObjectForDerivedSurrogate()
{
var d = new SurrogateMockD();
var pseudocopy = PseudoClone(d, serializer =>
{
serializer.ForSurrogate<SurrogateMockC>().SetObject(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldPlaceSurrogateForDerivedObject()
{
var d = new SurrogateMockD();
var pseudocopy = PseudoClone(d, serializer =>
{
serializer.ForObject<SurrogateMockC>().SetSurrogate(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldPlaceObjectForSurrogateImplementingInterface()
{
var e = new SurrogateMockE();
var pseudocopy = PseudoClone(e, serializer =>
{
serializer.ForSurrogate<ISurrogateMockE>().SetObject(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldPlaceSurrogateForObjectImplementingInterface()
{
var e = new SurrogateMockE();
var pseudocopy = PseudoClone(e, serializer =>
{
serializer.ForObject<ISurrogateMockE>().SetSurrogate(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldUseMoreSpecificSurrogateIfPossible()
{
var mock = new SurrogateMockD();
var pseudocopy = PseudoClone(mock, serializer =>
{
serializer.ForObject<SurrogateMockC>().SetSurrogate(x => new SurrogateMockA(1));
serializer.ForObject<SurrogateMockD>().SetSurrogate(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldThrowWhenSettingSurrogatesAfterSerialization()
{
var serializer = new Serializer(GetSettings());
serializer.Serialize(new object(), Stream.Null);
Assert.Throws<InvalidOperationException>(() => serializer.ForObject<object>().SetSurrogate(x => new object()));
}
[Test]
public void ShouldThrowWhenSettingObjectForSurrogateAfterDeserialization()
{
var serializer = new Serializer(GetSettings());
var stream = new MemoryStream();
serializer.Serialize(new object(), stream);
stream.Seek(0, SeekOrigin.Begin);
serializer.Deserialize<object>(stream);
Assert.Throws<InvalidOperationException>(() => serializer.ForSurrogate<object>().SetObject(x => new object()));
}
[Test]
public void ShouldDoSurrogateObjectSwapTwoTimes()
{
var b = new SurrogateMockB();
var serializer = new Serializer(GetSettings());
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(1));
serializer.ForSurrogate<SurrogateMockA>().SetObject(x => new SurrogateMockC());
for(var i = 0; i < 2; i++)
{
using(var stream = new MemoryStream())
{
serializer.Serialize(b, stream);
stream.Seek(0, SeekOrigin.Begin);
var pseudocopy = serializer.Deserialize<object>(stream);
var c = pseudocopy as SurrogateMockC;
Assert.IsNotNull(c);
}
}
}
}
public class SurrogateMockA
{
public SurrogateMockA(int field)
{
Field = field;
}
public int Field { get; private set; }
}
public class SurrogateMockB
{
}
public class SurrogateMockC
{
}
public class SurrogateMockD : SurrogateMockC
{
}
public interface ISurrogateMockE
{
}
public class SurrogateMockE : ISurrogateMockE
{
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A Stream whose backing store is memory. Great
** for temporary storage without creating a temp file. Also
** lets users expose a byte[] as a stream.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = Int32.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
_buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead
{
get { return _isOpen; }
}
public override bool CanSeek
{
get { return _isOpen; }
}
public override bool CanWrite
{
get { return _writable; }
}
private void EnsureWriteable()
{
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
throw new IOException(SR.IO_StreamTooLong);
if (value > _capacity)
{
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
newCapacity = _capacity * 2;
// We want to expand the array up to Array.MaxArrayLengthOneDimensional
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer()
{
if (!_exposable)
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: Get origin and length - used in ResourceWriter.
[FriendAccessAllowed]
internal void InternalGetOriginAndLength(out int origin, out int length)
{
if (!_isOpen) __Error.StreamIsClosed();
origin = _origin;
length = _length;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32()
{
if (!_isOpen)
__Error.StreamIsClosed();
int pos = (_position += 4); // use temp to avoid a race condition
if (pos > _length)
{
_position = _length;
__Error.EndOfFile();
}
return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n < 0) n = 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
if (!_isOpen) __Error.StreamIsClosed();
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
public override long Position
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
_position = _origin + (int)value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n <= 0)
return 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override int Read(Span<byte> destination)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(destination);
}
if (!_isOpen)
{
__Error.StreamIsClosed();
}
int n = Math.Min(_length - _position, destination.Length);
if (n <= 0)
{
return 0;
}
// TODO https://github.com/dotnet/corefx/issues/22388:
// Read(byte[], int, int) has an n <= 8 optimization, presumably based
// on benchmarking. Determine if/where such a cut-off is here and add
// an equivalent optimization if necessary.
new Span<byte>(_buffer, _position, n).CopyTo(destination);
_position += n;
return n;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
try
{
// ReadAsync(Memory<byte>,...) needs to delegate to an existing virtual to do the work, in case an existing derived type
// has changed or augmented the logic associated with reads. If the Memory wraps an array, we could delegate to
// ReadAsync(byte[], ...), but that would defeat part of the purpose, as ReadAsync(byte[], ...) often needs to allocate
// a Task<int> for the return value, so we want to delegate to one of the synchronous methods. We could always
// delegate to the Read(Span<byte>) method, and that's the most efficient solution when dealing with a concrete
// MemoryStream, but if we're dealing with a type derived from MemoryStream, Read(Span<byte>) will end up delegating
// to Read(byte[], ...), which requires it to get a byte[] from ArrayPool and copy the data. So, we special-case the
// very common case of the Memory<byte> wrapping an array: if it does, we delegate to Read(byte[], ...) with it,
// as that will be efficient in both cases, and we fall back to Read(Span<byte>) if the Memory<byte> wrapped something
// else; if this is a concrete MemoryStream, that'll be efficient, and only in the case where the Memory<byte> wrapped
// something other than an array and this is a MemoryStream-derived type that doesn't override Read(Span<byte>) will
// it then fall back to doing the ArrayPool/copy behavior.
return new ValueTask<int>(
destination.TryGetArray(out ArraySegment<byte> destinationArray) ?
Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) :
Read(destination.Span));
}
catch (OperationCanceledException oce)
{
return new ValueTask<int>(Task.FromCancellation<int>(oce));
}
catch (Exception exception)
{
return new ValueTask<int>(Task.FromException<int>(exception));
}
}
public override int ReadByte()
{
if (!_isOpen) __Error.StreamIsClosed();
if (_position >= _length) return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (this.GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
Int32 pos = _position;
Int32 n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try
{
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin))
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
}
public virtual byte[] ToArray()
{
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(SR.IO_StreamTooLong);
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, i - _length);
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
}
public override void Write(ReadOnlySpan<byte> source)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(source);
return;
}
if (!_isOpen)
{
__Error.StreamIsClosed();
}
EnsureWriteable();
// Check for overflow
int i = _position + source.Length;
if (i < 0)
{
throw new IOException(SR.IO_StreamTooLong);
}
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
source.CopyTo(new Span<byte>(_buffer, _position, source.Length));
_position = i;
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<VoidTaskResult>(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
try
{
// See corresponding comment in ReadAsync for why we don't just always use Write(ReadOnlySpan<byte>).
// Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency.
if (source.DangerousTryGetArray(out ArraySegment<byte> sourceArray))
{
Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count);
}
else
{
Write(source.Span);
}
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<VoidTaskResult>(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override void WriteByte(byte value)
{
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, _position - _length);
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
if (!_isOpen) __Error.StreamIsClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// ToInt64(System.Decimal)
/// </summary>
public class ConvertToInt64_4
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt64(0<decimal<0.5)");
try
{
double random;
do
random = TestLibrary.Generator.GetDouble(-55);
while (random >= 0.5);
decimal d = decimal.Parse(random.ToString());
long actual = Convert.ToInt64(d);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt64(1>decimal>=0.5)");
try
{
double random;
do
random = TestLibrary.Generator.GetDouble(-55);
while (random < 0.5);
decimal d = decimal.Parse(random.ToString());
long actual = Convert.ToInt64(d);
long expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt64(0)");
try
{
decimal d = 0m;
long actual = Convert.ToInt64(d);
long expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt64(int64.max)");
try
{
decimal d = Int64.MaxValue;
long actual = Convert.ToInt64(d);
long expected = Int64.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt64(int64.min)");
try
{
decimal d = Int64.MinValue;
long actual = Convert.ToInt64(d);
long expected = Int64.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt64 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
decimal d = (decimal)Int64.MaxValue + 1;
long i = Convert.ToInt64(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
decimal d = (decimal)Int64.MinValue - 1;
long i = Convert.ToInt64(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt64_4 test = new ConvertToInt64_4();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt64_4");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace System.Win32
{
public delegate int WindowProcDelegate(IntPtr hw, IntPtr uMsg, IntPtr wParam, IntPtr lParam);
public static class User32
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ChangeClipboardChain(
IntPtr hWndRemove, // handle to window to remove
IntPtr hWndNewNext // handle to next window
);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
}
/// <summary>
/// Windows Event Messages sent to the WindowProc
/// </summary>
public enum Msgs
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400,
WM_POWERBROADCAST = 0x0218,
// For Windows XP Balloon messages from the System Notification Area
NIN_BALLOONSHOW = 0x0402,
NIN_BALLOONHIDE = 0x0403,
NIN_BALLOONTIMEOUT = 0x0404,
NIN_BALLOONUSERCLICK = 0x0405
}
}
| |
using System.Collections.Generic;
namespace UnityEngine.Rendering.PostProcessing
{
//
// Here's a quick look at the architecture of this framework and how it's integrated into Unity
// (written between versions 5.6 and 2017.1):
//
// Users have to be able to plug in their own effects without having to modify the codebase and
// these custom effects should work out-of-the-box with all the other features we provide
// (volume blending etc). This relies on heavy use of polymorphism, but the only way to get
// the serialization system to work well with polymorphism in Unity is to use ScriptableObjects.
//
// Users can push their custom effects at different (hardcoded) injection points.
//
// Each effect consists of at least two classes (+ shaders): a POD "Settings" class which only
// stores parameters, and a "Renderer" class that holds the rendering logic. Settings are linked
// to renderers using a PostProcessAttribute. These are automatically collected at init time
// using reflection. Settings in this case are ScriptableObjects, we only need to serialize
// these.
//
// We could store these settings object straight into each volume and call it a day, but
// unfortunately there's one feature of Unity that doesn't work well with scene-stored assets:
// prefabs. So we need to store all of these settings in a disk-asset and treat them as
// sub-assets.
//
// Note: We have to use ScriptableObject for everything but these don't work with the Animator
// tool. It's unfortunate but it's the only way to make it easily extensible. On the other
// hand, users can animate post-processing effects using Volumes or straight up scripting.
//
// Volume blending leverages the physics system for distance checks to the nearest point on
// volume colliders. Each volume can have several colliders or any type (cube, mesh...), making
// it quite a powerful feature to use.
//
// Volumes & blending are handled by a singleton manager (see PostProcessManager).
//
// Rendering is handled by a PostProcessLayer component living on the camera, which mean you
// can easily toggle post-processing on & off or change the anti-aliasing type per-camera,
// which is very useful when doing multi-layered camera rendering or any other technique that
// involves multiple-camera setups. This PostProcessLayer component can also filters volumes
// by layers (as in Unity layers) so you can easily choose which volumes should affect the
// camera.
//
// All post-processing shaders MUST use the custom Standard Shader Library bundled with the
// framework. The reason for that is because the codebase is meant to work without any
// modification on the Classic Render Pipelines (Forward, Deferred...) and the upcoming
// Scriptable Render Pipelines (HDPipe, LDPipe...). But these don't have compatible shader
// libraries so instead of writing two code paths we chose to provide a minimalist, generic
// Standard Library geared toward post-processing use. An added bonus to that if users create
// their own post-processing effects using this framework, then they'll work without any
// modification on both Classic and Scriptable Render Pipelines.
//
[ExecuteInEditMode]
[AddComponentMenu("Rendering/Post-process Volume", 1001)]
public sealed class PostProcessVolume : MonoBehaviour
{
// Modifying sharedProfile will change the behavior of all volumes using this profile, and
// change profile settings that are stored in the project too
public PostProcessProfile sharedProfile;
[Tooltip("A global volume is applied to the whole scene.")]
public bool isGlobal = false;
[Min(0f), Tooltip("Outer distance to start blending from. A value of 0 means no blending and the volume overrides will be applied immediatly upon entry.")]
public float blendDistance = 0f;
[Range(0f, 1f), Tooltip("Total weight of this volume in the scene. 0 means it won't do anything, 1 means full effect.")]
public float weight = 1f;
[Tooltip("Volume priority in the stack. Higher number means higher priority. Negative values are supported.")]
public float priority = 0f;
// This property automatically instantiates the profile and make it unique to this volume
// so you can safely edit it via scripting at runtime without changing the original asset
// in the project.
// Note that if you pass in your own profile, it is your responsability to destroy it once
// it's not in use anymore.
public PostProcessProfile profile
{
get
{
if (m_InternalProfile == null)
{
m_InternalProfile = ScriptableObject.CreateInstance<PostProcessProfile>();
if (sharedProfile != null)
{
foreach (var item in sharedProfile.settings)
{
var itemCopy = Instantiate(item);
m_InternalProfile.settings.Add(itemCopy);
}
}
}
return m_InternalProfile;
}
set
{
m_InternalProfile = value;
}
}
internal PostProcessProfile profileRef
{
get
{
return m_InternalProfile == null
? sharedProfile
: m_InternalProfile;
}
}
int m_PreviousLayer;
float m_PreviousPriority;
List<Collider> m_TempColliders;
PostProcessProfile m_InternalProfile;
void OnEnable()
{
PostProcessManager.instance.Register(this);
m_PreviousLayer = gameObject.layer;
m_TempColliders = new List<Collider>();
}
void OnDisable()
{
PostProcessManager.instance.Unregister(this);
}
void Update()
{
// Unfortunately we need to track the current layer to update the volume manager in
// real-time as the user could change it at any time in the editor or at runtime.
// Because no event is raised when the layer changes, we have to track it on every
// frame :/
int layer = gameObject.layer;
if (layer != m_PreviousLayer)
{
PostProcessManager.instance.UpdateVolumeLayer(this, m_PreviousLayer, layer);
m_PreviousLayer = layer;
}
// Same for `priority`. We could use a property instead, but it doesn't play nice with
// the serialization system. Using a custom Attribute/PropertyDrawer for a property is
// possible but it doesn't work with Undo/Redo in the editor, which makes it useless.
if (priority != m_PreviousPriority)
{
PostProcessManager.instance.SetLayerDirty(layer);
m_PreviousPriority = priority;
}
}
// TODO: Look into a better volume previsualization system
void OnDrawGizmos()
{
var colliders = m_TempColliders;
GetComponents(colliders);
if (isGlobal || colliders == null)
return;
#if UNITY_EDITOR
// Can't access the UnityEditor.Rendering.PostProcessing namespace from here, so
// we'll get the preferred color manually
unchecked
{
int value = UnityEditor.EditorPrefs.GetInt("PostProcessing.Volume.GizmoColor", (int)0x8033cc1a);
Gizmos.color = ColorUtilities.ToRGBA((uint)value);
}
#endif
var scale = transform.localScale;
var invScale = new Vector3(1f / scale.x, 1f / scale.y, 1f / scale.z);
Gizmos.matrix = Matrix4x4.TRS(transform.position, transform.rotation, scale);
// Draw a separate gizmo for each collider
foreach (var collider in colliders)
{
if (!collider.enabled)
continue;
// We'll just use scaling as an approximation for volume skin. It's far from being
// correct (and is completely wrong in some cases). Ultimately we'd use a distance
// field or at least a tesselate + push modifier on the collider's mesh to get a
// better approximation, but the current Gizmo system is a bit limited and because
// everything is dynamic in Unity and can be changed at anytime, it's hard to keep
// track of changes in an elegant way (which we'd need to implement a nice cache
// system for generated volume meshes).
var type = collider.GetType();
if (type == typeof(BoxCollider))
{
var c = (BoxCollider)collider;
Gizmos.DrawCube(c.center, c.size);
Gizmos.DrawWireCube(c.center, c.size + invScale * blendDistance * 4f);
}
else if (type == typeof(SphereCollider))
{
var c = (SphereCollider)collider;
Gizmos.DrawSphere(c.center, c.radius);
Gizmos.DrawWireSphere(c.center, c.radius + invScale.x * blendDistance * 2f);
}
else if (type == typeof(MeshCollider))
{
var c = (MeshCollider)collider;
// Only convex mesh colliders are allowed
if (!c.convex)
c.convex = true;
// Mesh pivot should be centered or this won't work
Gizmos.DrawMesh(c.sharedMesh);
Gizmos.DrawWireMesh(c.sharedMesh, Vector3.zero, Quaternion.identity, Vector3.one + invScale * blendDistance * 4f);
}
// Nothing for capsule (DrawCapsule isn't exposed in Gizmo), terrain, wheel and
// other colliders...
}
colliders.Clear();
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace gpcc
{
internal class Scanner
{
public class ParseException : Exception
{
public int line;
public int column;
public ParseException(int line, int column, string message) : base(message)
{
this.line = line;
this.column = column;
}
}
public string yylval;
private char next;
private string line;
private int section;
private string filename;
private int linenr;
private int pos;
private StreamReader reader;
private StringBuilder builder;
public int CurrentLine
{
get
{
return this.linenr;
}
}
public int CurrentColumn
{
get
{
return this.pos;
}
}
public Scanner(string path)
{
this.section = 0;
this.filename = path;
this.reader = new StreamReader(path);
this.builder = new StringBuilder();
this.pos = 0;
this.linenr = 0;
this.line = "";
this.Advance();
}
public GrammarToken Next()
{
this.yylval = null;
if (this.next == '\0')
{
return GrammarToken.Eof;
}
if (this.section == 3)
{
this.builder.Length = 0;
if (GPCG.LINES)
{
this.builder.AppendFormat("#line {0} \"{1}\"", this.linenr, this.filename);
this.builder.AppendLine();
}
while (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
}
this.yylval = this.builder.ToString();
return GrammarToken.Epilog;
}
if (this.pos == 0 && this.line.StartsWith("%%"))
{
this.Advance();
this.Advance();
this.section++;
return GrammarToken.EndOfSection;
}
if (this.section == 0)
{
this.builder.Length = 0;
if (GPCG.LINES)
{
this.builder.AppendFormat("#line {0} \"{1}\"", this.linenr, this.filename);
this.builder.AppendLine();
}
while (this.next != '\0' && !this.line.StartsWith("%%"))
{
while (this.next != '\0' && this.next != '\n')
{
this.builder.Append(this.next);
this.Advance();
}
if (this.next != '\0')
{
this.builder.AppendLine();
this.Advance();
}
}
this.yylval = this.builder.ToString();
return GrammarToken.Prelude;
}
char c = this.next;
if (c <= '\'')
{
switch (c)
{
case '\t':
case '\n':
break;
default:
if (c != ' ')
{
switch (c)
{
case '%':
this.Advance();
if (this.next == '{')
{
this.Advance();
this.builder.Length = 0;
if (GPCG.LINES)
{
this.builder.AppendFormat("#line {0} \"{1}\"", this.linenr, this.filename);
this.builder.AppendLine();
}
while (true)
{
if (this.next == '%')
{
this.Advance();
if (this.next == '}')
{
break;
}
}
else
{
this.builder.Append(this.next);
this.Advance();
}
}
this.Advance();
this.yylval = this.builder.ToString();
return GrammarToken.Prolog;
}
if (char.IsLetter(this.next))
{
this.builder.Length = 0;
while (char.IsLetter(this.next))
{
this.builder.Append(this.next);
this.Advance();
}
string text = this.builder.ToString();
string key;
switch (key = text)
{
case "union":
this.yylval = this.ScanUnion();
return GrammarToken.Union;
case "prec":
return GrammarToken.Prec;
case "token":
return GrammarToken.Token;
case "type":
return GrammarToken.Type;
case "nonassoc":
return GrammarToken.NonAssoc;
case "left":
return GrammarToken.Left;
case "right":
return GrammarToken.Right;
case "start":
return GrammarToken.Start;
case "namespace":
return GrammarToken.Namespace;
case "visibility":
return GrammarToken.Visibility;
case "attributes":
return GrammarToken.Attributes;
case "parsertype":
return GrammarToken.ParserName;
case "tokens":
return GrammarToken.GenerateTokens;
case "tokentype":
return GrammarToken.TokenName;
case "valuetype":
return GrammarToken.ValueTypeName;
case "positiontype":
return GrammarToken.PositionType;
}
this.ReportError("Unexpected keyword {0}", new object[]
{
text
});
return this.Next();
}
this.ReportError("Unexpected keyword {0}", new object[]
{
this.next
});
return this.Next();
case '&':
goto IL_642;
case '\'':
{
this.Advance();
bool flag = this.next == '\\';
if (flag)
{
this.Advance();
}
this.yylval = new string(this.Escape(flag, this.next), 1);
this.Advance();
if (this.next != '\'')
{
this.ReportError("Expected closing character quote", new object[0]);
}
else
{
this.Advance();
}
return GrammarToken.Literal;
}
default:
goto IL_642;
}
}
break;
}
this.Advance();
return this.Next();
}
if (c != '/')
{
switch (c)
{
case ':':
this.Advance();
return GrammarToken.Colon;
case ';':
this.Advance();
return GrammarToken.SemiColon;
case '<':
this.Advance();
this.builder.Length = 0;
while (this.next != '>' && this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
}
this.Advance();
this.yylval = this.builder.ToString();
return GrammarToken.Kind;
default:
switch (c)
{
case '{':
if (this.section == 1)
{
this.Advance();
return GrammarToken.LeftCurly;
}
this.yylval = this.ScanCodeBlock();
return GrammarToken.Action;
case '|':
this.Advance();
return GrammarToken.Divider;
case '}':
this.Advance();
return GrammarToken.RightCurly;
}
break;
}
}
else
{
this.Advance();
if (this.next == '/')
{
while (this.next != '\n')
{
this.Advance();
}
return this.Next();
}
if (this.next == '*')
{
this.Advance();
while (true)
{
if (this.next == '*')
{
this.Advance();
if (this.next == '/')
{
break;
}
}
else
{
this.Advance();
}
}
this.Advance();
return this.Next();
}
this.ReportError("unexpected / character, not in comment", new object[0]);
return this.Next();
}
IL_642:
if (char.IsLetter(this.next))
{
this.builder.Length = 0;
while (char.IsLetterOrDigit(this.next) || this.next == '_' || this.next == '.')
{
this.builder.Append(this.next);
this.Advance();
}
this.yylval = this.builder.ToString();
return GrammarToken.Symbol;
}
this.ReportError("Unexpected character '{0}'", new object[]
{
this.next
});
this.Advance();
return this.Next();
}
private void Advance()
{
if (this.pos + 1 < this.line.Length)
{
this.pos++;
this.next = this.line[this.pos];
return;
}
if (this.reader.EndOfStream)
{
this.next = '\0';
return;
}
this.line = this.reader.ReadLine() + "\n";
this.linenr++;
this.pos = 0;
this.next = this.line[this.pos];
}
private string ScanCodeBlock()
{
this.builder.Length = 0;
if (GPCG.LINES)
{
this.builder.AppendFormat("#line {0} \"{1}\"\n", this.linenr, this.filename);
this.builder.Append("\t\t\t");
}
this.builder.Append(this.next);
this.Advance();
int num = 1;
while (true)
{
char c = this.next;
if (c <= '\'')
{
if (c != '"')
{
if (c == '\'')
{
this.builder.Append(this.next);
this.Advance();
while (this.next != '\0' && this.next != '\'')
{
if (this.next == '\\')
{
this.builder.Append(this.next);
this.Advance();
}
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
}
}
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
continue;
}
continue;
}
}
else
{
this.builder.Append(this.next);
this.Advance();
while (this.next != '\0' && this.next != '"')
{
if (this.next == '\\')
{
this.builder.Append(this.next);
this.Advance();
}
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
}
}
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
continue;
}
continue;
}
}
else
{
if (c != '/')
{
if (c != '@')
{
switch (c)
{
case '{':
num++;
this.builder.Append(this.next);
this.Advance();
continue;
case '}':
this.builder.Append(this.next);
this.Advance();
if (--num == 0)
{
goto Block_8;
}
continue;
}
}
else
{
this.builder.Append(this.next);
this.Advance();
if (this.next != '"')
{
continue;
}
this.builder.Append(this.next);
this.Advance();
while (this.next != '\0' && this.next != '"')
{
this.builder.Append(this.next);
this.Advance();
}
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
continue;
}
continue;
}
}
else
{
this.builder.Append(this.next);
this.Advance();
if (this.next == '/')
{
while (this.next != '\0')
{
if (this.next == '\n')
{
break;
}
this.builder.Append(this.next);
this.Advance();
}
continue;
}
if (this.next != '*')
{
this.builder.Append(this.next);
this.Advance();
continue;
}
this.builder.Append(this.next);
this.Advance();
while (true)
{
if (this.next == '\0' || this.next == '*')
{
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
}
if (this.next == '\0' || this.next == '/')
{
break;
}
}
else
{
this.builder.Append(this.next);
this.Advance();
}
}
if (this.next != '\0')
{
this.builder.Append(this.next);
this.Advance();
continue;
}
continue;
}
}
this.builder.Append(this.next);
this.Advance();
}
Block_8:
return this.builder.ToString();
}
private string ScanUnion()
{
while (this.next != '{')
{
this.Advance();
}
return this.ScanCodeBlock();
}
private char Escape(bool backslash, char ch)
{
if (!backslash)
{
return ch;
}
if (ch <= 'b')
{
if (ch == '\'')
{
return '\'';
}
if (ch == '0')
{
return '\0';
}
switch (ch)
{
case 'a':
return '\a';
case 'b':
return '\b';
}
}
else
{
if (ch == 'f')
{
return '\f';
}
if (ch == 'n')
{
return '\n';
}
switch (ch)
{
case 'r':
return '\r';
case 't':
return '\t';
case 'v':
return '\v';
}
}
this.ReportError("Unexpected escape character '\\{0}'", new object[]
{
ch
});
return ch;
}
public void ReportError(string format, params object[] args)
{
throw new Scanner.ParseException(this.linenr, this.pos, string.Format(format, args));
}
}
}
| |
#if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Collections.Generic;
#if NETFX_CORE
using FileStream = BestHTTP.PlatformSupport.IO.FileStream;
using Directory = BestHTTP.PlatformSupport.IO.Directory;
using File = BestHTTP.PlatformSupport.IO.File;
using BestHTTP.PlatformSupport.IO;
#else
using FileStream = System.IO.FileStream;
using System.IO;
#endif
namespace BestHTTP.Caching
{
using BestHTTP.Extensions;
/// <summary>
/// Holds all metadata that need for efficient caching, so we don't need to touch the disk to load headers.
/// </summary>
internal class HTTPCacheFileInfo : IComparable<HTTPCacheFileInfo>
{
#region Properties
/// <summary>
/// The uri that this HTTPCacheFileInfo belongs to.
/// </summary>
internal Uri Uri { get; set; }
/// <summary>
/// The last access time to this cache entity. The date is in UTC.
/// </summary>
internal DateTime LastAccess { get; set; }
/// <summary>
/// The length of the cache entity's body.
/// </summary>
internal int BodyLength { get; set; }
/// <summary>
/// ETag of the entity.
/// </summary>
private string ETag { get; set; }
/// <summary>
/// LastModified date of the entity.
/// </summary>
private string LastModified { get; set; }
/// <summary>
/// When the cache will expire.
/// </summary>
private DateTime Expires { get; set; }
/// <summary>
/// The age that came with the response
/// </summary>
private long Age { get; set; }
/// <summary>
/// Maximum how long the entry should served from the cache without revalidation.
/// </summary>
private long MaxAge { get; set; }
/// <summary>
/// The Date that came with the response.
/// </summary>
private DateTime Date { get; set; }
/// <summary>
/// Indicates whether the entity must be revalidated with the server or can be serverd directly from the cache without touching the server.
/// </summary>
private bool MustRevalidate { get; set; }
/// <summary>
/// The date and time when the HTTPResponse received.
/// </summary>
private DateTime Received { get; set; }
/// <summary>
/// Cached path.
/// </summary>
private string ConstructedPath { get; set; }
/// <summary>
/// This is the index of the enity. Filenames are generated from this value.
/// </summary>
internal UInt64 MappedNameIDX { get; set; }
#endregion
#region Constructors
internal HTTPCacheFileInfo(Uri uri)
:this(uri, DateTime.UtcNow, -1)
{
}
internal HTTPCacheFileInfo(Uri uri, DateTime lastAcces, int bodyLength)
{
this.Uri = uri;
this.LastAccess = lastAcces;
this.BodyLength = bodyLength;
this.MaxAge = -1;
this.MappedNameIDX = HTTPCacheService.GetNameIdx();
}
internal HTTPCacheFileInfo(Uri uri, System.IO.BinaryReader reader, int version)
{
this.Uri = uri;
this.LastAccess = DateTime.FromBinary(reader.ReadInt64());
this.BodyLength = reader.ReadInt32();
switch(version)
{
case 2:
this.MappedNameIDX = reader.ReadUInt64();
goto case 1;
case 1:
{
this.ETag = reader.ReadString();
this.LastModified = reader.ReadString();
this.Expires = DateTime.FromBinary(reader.ReadInt64());
this.Age = reader.ReadInt64();
this.MaxAge = reader.ReadInt64();
this.Date = DateTime.FromBinary(reader.ReadInt64());
this.MustRevalidate = reader.ReadBoolean();
this.Received = DateTime.FromBinary(reader.ReadInt64());
break;
}
}
}
#endregion
#region Helper Functions
internal void SaveTo(System.IO.BinaryWriter writer)
{
writer.Write(LastAccess.ToBinary());
writer.Write(BodyLength);
writer.Write(MappedNameIDX);
writer.Write(ETag);
writer.Write(LastModified);
writer.Write(Expires.ToBinary());
writer.Write(Age);
writer.Write(MaxAge);
writer.Write(Date.ToBinary());
writer.Write(MustRevalidate);
writer.Write(Received.ToBinary());
}
private string GetPath()
{
if (ConstructedPath != null)
return ConstructedPath;
return ConstructedPath = System.IO.Path.Combine(HTTPCacheService.CacheFolder, MappedNameIDX.ToString("X"));
}
internal bool IsExists()
{
if (!HTTPCacheService.IsSupported)
return false;
return File.Exists(GetPath());
}
internal void Delete()
{
if (!HTTPCacheService.IsSupported)
return;
string path = GetPath();
try
{
File.Delete(path);
}
catch
{ }
finally
{
Reset();
}
}
private void Reset()
{
this.MappedNameIDX = 0x0000;
this.BodyLength = -1;
this.ETag = string.Empty;
this.Expires = DateTime.FromBinary(0);
this.LastModified = string.Empty;
this.Age = 0;
this.MaxAge = -1;
this.Date = DateTime.FromBinary(0);
this.MustRevalidate = false;
this.Received = DateTime.FromBinary(0);
}
#endregion
#region Caching
private void SetUpCachingValues(HTTPResponse response)
{
this.ETag = response.GetFirstHeaderValue("ETag").ToStrOrEmpty();
this.Expires = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0));
this.LastModified = response.GetFirstHeaderValue("Last-Modified").ToStrOrEmpty();
this.Age = response.GetFirstHeaderValue("Age").ToInt64(0);
this.Date = response.GetFirstHeaderValue("Date").ToDateTime(DateTime.FromBinary(0));
string cacheControl = response.GetFirstHeaderValue("cache-control");
if (!string.IsNullOrEmpty(cacheControl))
{
string[] kvp = cacheControl.FindOption("Max-Age");
if (kvp != null)
{
// Some cache proxies will return float values
double maxAge;
if (double.TryParse(kvp[1], out maxAge))
this.MaxAge = (int)maxAge;
}
this.MustRevalidate = cacheControl.ToLower().Contains("must-revalidate");
}
this.Received = DateTime.UtcNow;
}
internal bool WillExpireInTheFuture()
{
if (!IsExists())
return false;
if (MustRevalidate)
return false;
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.2.4 :
// The max-age directive takes priority over Expires
if (MaxAge != -1)
{
// Age calculation:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.2.3
long apparent_age = Math.Max(0, (long)(Received - Date).TotalSeconds);
long corrected_received_age = Math.Max(apparent_age, Age);
long resident_time = (long)(DateTime.UtcNow - Date).TotalSeconds;
long current_age = corrected_received_age + resident_time;
return current_age < MaxAge;
}
return Expires > DateTime.UtcNow;
}
internal void SetUpRevalidationHeaders(HTTPRequest request)
{
if (!IsExists())
return;
// -If an entity tag has been provided by the origin server, MUST use that entity tag in any cache-conditional request (using If-Match or If-None-Match).
// -If only a Last-Modified value has been provided by the origin server, SHOULD use that value in non-subrange cache-conditional requests (using If-Modified-Since).
// -If both an entity tag and a Last-Modified value have been provided by the origin server, SHOULD use both validators in cache-conditional requests. This allows both HTTP/1.0 and HTTP/1.1 caches to respond appropriately.
if (!string.IsNullOrEmpty(ETag))
request.AddHeader("If-None-Match", ETag);
if (!string.IsNullOrEmpty(LastModified))
request.AddHeader("If-Modified-Since", LastModified);
}
internal System.IO.Stream GetBodyStream(out int length)
{
if (!IsExists())
{
length = 0;
return null;
}
length = BodyLength;
LastAccess = DateTime.UtcNow;
FileStream stream = new FileStream(GetPath(), FileMode.Open);
stream.Seek(-length, System.IO.SeekOrigin.End);
return stream;
}
internal HTTPResponse ReadResponseTo(HTTPRequest request)
{
if (!IsExists())
return null;
LastAccess = DateTime.UtcNow;
using (FileStream stream = new FileStream(GetPath(), FileMode.Open))
{
var response = new HTTPResponse(request, stream, request.UseStreaming, true);
response.Receive(BodyLength);
return response;
}
}
internal void Store(HTTPResponse response)
{
if (!HTTPCacheService.IsSupported)
return;
string path = GetPath();
// Path name too long, we don't want to get exceptions
if (path.Length > HTTPManager.MaxPathLength)
return;
if (File.Exists(path))
Delete();
using (FileStream writer = new FileStream(path, FileMode.Create))
{
writer.WriteLine("HTTP/1.1 {0} {1}", response.StatusCode, response.Message);
foreach (var kvp in response.Headers)
{
for (int i = 0; i < kvp.Value.Count; ++i)
writer.WriteLine("{0}: {1}", kvp.Key, kvp.Value[i]);
}
writer.WriteLine();
writer.Write(response.Data, 0, response.Data.Length);
}
BodyLength = response.Data.Length;
LastAccess = DateTime.UtcNow;
SetUpCachingValues(response);
}
internal System.IO.Stream GetSaveStream(HTTPResponse response)
{
if (!HTTPCacheService.IsSupported)
return null;
LastAccess = DateTime.UtcNow;
string path = GetPath();
if (File.Exists(path))
Delete();
// Path name too long, we don't want to get exceptions
if (path.Length > HTTPManager.MaxPathLength)
return null;
// First write out the headers
using (FileStream writer = new FileStream(path, FileMode.Create))
{
writer.WriteLine("HTTP/1.1 {0} {1}", response.StatusCode, response.Message);
foreach (var kvp in response.Headers)
{
for (int i = 0; i < kvp.Value.Count; ++i)
writer.WriteLine("{0}: {1}", kvp.Key, kvp.Value[i]);
}
writer.WriteLine();
}
// If caching is enabled and the response is from cache, and no content-length header set, then we set one to the response.
if (response.IsFromCache && !response.Headers.ContainsKey("content-length"))
response.Headers.Add("content-length", new List<string> { BodyLength.ToString() });
SetUpCachingValues(response);
// then create the stream with Append FileMode
return new FileStream(GetPath(), FileMode.Append);
}
#endregion
#region IComparable<HTTPCacheFileInfo>
public int CompareTo(HTTPCacheFileInfo other)
{
return this.LastAccess.CompareTo(other.LastAccess);
}
#endregion
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableHashSet{T}.HashBucket"/> struct.
/// </content>
public partial class ImmutableHashSet<T>
{
/// <summary>
/// The result of a mutation operation.
/// </summary>
internal enum OperationResult
{
/// <summary>
/// The change required element(s) to be added or removed from the collection.
/// </summary>
SizeChanged,
/// <summary>
/// No change was required (the operation ended in a no-op).
/// </summary>
NoChangeRequired,
}
/// <summary>
/// Contains all the keys in the collection that hash to the same value.
/// </summary>
internal readonly struct HashBucket
{
/// <summary>
/// One of the values in this bucket.
/// </summary>
private readonly T _firstValue;
/// <summary>
/// Any other elements that hash to the same value.
/// </summary>
/// <value>
/// This is null if and only if the entire bucket is empty (including <see cref="_firstValue"/>).
/// It's empty if <see cref="_firstValue"/> has an element but no additional elements.
/// </value>
private readonly ImmutableList<T>.Node _additionalElements;
/// <summary>
/// Initializes a new instance of the <see cref="HashBucket"/> struct.
/// </summary>
/// <param name="firstElement">The first element.</param>
/// <param name="additionalElements">The additional elements.</param>
private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null)
{
_firstValue = firstElement;
_additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
internal bool IsEmpty
{
get { return _additionalElements == null; }
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Throws an exception to catch any errors in comparing <see cref="HashBucket"/> instances.
/// </summary>
public override bool Equals(object obj)
{
// This should never be called, as hash buckets don't know how to equate themselves.
throw new NotSupportedException();
}
/// <summary>
/// Throws an exception to catch any errors in comparing <see cref="HashBucket"/> instances.
/// </summary>
public override int GetHashCode()
{
// This should never be called, as hash buckets don't know how to hash themselves.
throw new NotSupportedException();
}
/// <summary>
/// Checks whether this <see cref="HashBucket"/> is exactly like another one,
/// comparing by reference. For use when type parameter T is an object.
/// </summary>
/// <param name="other">The other bucket.</param>
/// <returns><c>true</c> if the two <see cref="HashBucket"/> structs have precisely the same values.</returns>
internal bool EqualsByRef(HashBucket other)
{
return object.ReferenceEquals(_firstValue, other._firstValue)
&& object.ReferenceEquals(_additionalElements, other._additionalElements);
}
/// <summary>
/// Checks whether this <see cref="HashBucket"/> is exactly like another one,
/// comparing by value. For use when type parameter T is a struct.
/// </summary>
/// <param name="other">The other bucket.</param>
/// <param name="valueComparer">The comparer to use for the first value in the bucket.</param>
/// <returns><c>true</c> if the two <see cref="HashBucket"/> structs have precisely the same values.</returns>
internal bool EqualsByValue(HashBucket other, IEqualityComparer<T> valueComparer)
{
return valueComparer.Equals(_firstValue, other._firstValue)
&& object.ReferenceEquals(_additionalElements, other._additionalElements);
}
/// <summary>
/// Adds the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param>
/// <returns>A new <see cref="HashBucket"/> that contains the added value and any values already held by this <see cref="HashBucket"/>.</returns>
internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket(value);
}
if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
result = OperationResult.SizeChanged;
return new HashBucket(_firstValue, _additionalElements.Add(value));
}
/// <summary>
/// Determines whether the <see cref="HashBucket"/> contains the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="valueComparer">The value comparer.</param>
internal bool Contains(T value, IEqualityComparer<T> valueComparer)
{
if (this.IsEmpty)
{
return false;
}
return valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0;
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="value">The value to search for.</param>
/// <param name="valueComparer">The value comparer.</param>
/// <param name="existingValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>
/// A value indicating whether the search was successful.
/// </returns>
internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue)
{
if (!this.IsEmpty)
{
if (valueComparer.Equals(value, _firstValue))
{
existingValue = _firstValue;
return true;
}
int index = _additionalElements.IndexOf(value, valueComparer);
if (index >= 0)
{
#if !NETSTANDARD10
existingValue = _additionalElements.ItemRef(index);
#else
existingValue = _additionalElements[index];
#endif
return true;
}
}
existingValue = value;
return false;
}
/// <summary>
/// Removes the specified value if it exists in the collection.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param>
/// <returns>A new <see cref="HashBucket"/> that does not contain the removed value and any values already held by this <see cref="HashBucket"/>.</returns>
internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result)
{
if (this.IsEmpty)
{
result = OperationResult.NoChangeRequired;
return this;
}
if (equalityComparer.Equals(_firstValue, value))
{
if (_additionalElements.IsEmpty)
{
result = OperationResult.SizeChanged;
return new HashBucket();
}
else
{
// We can promote any element from the list into the first position, but it's most efficient
// to remove the root node in the binary tree that implements the list.
int indexOfRootNode = _additionalElements.Left.Count;
result = OperationResult.SizeChanged;
return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(indexOfRootNode));
}
}
int index = _additionalElements.IndexOf(value, equalityComparer);
if (index < 0)
{
result = OperationResult.NoChangeRequired;
return this;
}
else
{
result = OperationResult.SizeChanged;
return new HashBucket(_firstValue, _additionalElements.RemoveAt(index));
}
}
/// <summary>
/// Freezes this instance so that any further mutations require new memory allocations.
/// </summary>
internal void Freeze()
{
if (_additionalElements != null)
{
_additionalElements.Freeze();
}
}
/// <summary>
/// Enumerates all the elements in this instance.
/// </summary>
internal struct Enumerator : IEnumerator<T>, IDisposable
{
/// <summary>
/// The bucket being enumerated.
/// </summary>
private readonly HashBucket _bucket;
/// <summary>
/// A value indicating whether this enumerator has been disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// The current position of this enumerator.
/// </summary>
private Position _currentPosition;
/// <summary>
/// The enumerator that represents the current position over the <see cref="_additionalElements"/> of the <see cref="HashBucket"/>.
/// </summary>
private ImmutableList<T>.Enumerator _additionalEnumerator;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet{T}.HashBucket.Enumerator"/> struct.
/// </summary>
/// <param name="bucket">The bucket.</param>
internal Enumerator(HashBucket bucket)
{
_disposed = false;
_bucket = bucket;
_currentPosition = Position.BeforeFirst;
_additionalEnumerator = default(ImmutableList<T>.Enumerator);
}
/// <summary>
/// Describes the positions the enumerator state machine may be in.
/// </summary>
private enum Position
{
/// <summary>
/// The first element has not yet been moved to.
/// </summary>
BeforeFirst,
/// <summary>
/// We're at the <see cref="_firstValue"/> of the containing bucket.
/// </summary>
First,
/// <summary>
/// We're enumerating the <see cref="_additionalElements"/> in the bucket.
/// </summary>
Additional,
/// <summary>
/// The end of enumeration has been reached.
/// </summary>
End,
}
/// <summary>
/// Gets the current element.
/// </summary>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <summary>
/// Gets the current element.
/// </summary>
public T Current
{
get
{
this.ThrowIfDisposed();
switch (_currentPosition)
{
case Position.First:
return _bucket._firstValue;
case Position.Additional:
return _additionalEnumerator.Current;
default:
throw new InvalidOperationException();
}
}
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public bool MoveNext()
{
this.ThrowIfDisposed();
if (_bucket.IsEmpty)
{
_currentPosition = Position.End;
return false;
}
switch (_currentPosition)
{
case Position.BeforeFirst:
_currentPosition = Position.First;
return true;
case Position.First:
if (_bucket._additionalElements.IsEmpty)
{
_currentPosition = Position.End;
return false;
}
_currentPosition = Position.Additional;
_additionalEnumerator = new ImmutableList<T>.Enumerator(_bucket._additionalElements);
return _additionalEnumerator.MoveNext();
case Position.Additional:
return _additionalEnumerator.MoveNext();
case Position.End:
return false;
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception>
public void Reset()
{
this.ThrowIfDisposed();
_additionalEnumerator.Dispose();
_currentPosition = Position.BeforeFirst;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_disposed = true;
_additionalEnumerator.Dispose();
}
/// <summary>
/// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (_disposed)
{
Requires.FailObjectDisposed(this);
}
}
}
}
}
}
| |
namespace android.graphics.drawable
{
[global::MonoJavaBridge.JavaClass()]
public partial class ClipDrawable : android.graphics.drawable.Drawable, android.graphics.drawable.Drawable.Callback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ClipDrawable()
{
InitJNI();
}
protected ClipDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _inflate3882;
public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._inflate3882, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._inflate3882, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _draw3883;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._draw3883, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._draw3883, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getChangingConfigurations3884;
public override int getChangingConfigurations()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._getChangingConfigurations3884);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._getChangingConfigurations3884);
}
internal static global::MonoJavaBridge.MethodId _setAlpha3885;
public override void setAlpha(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._setAlpha3885, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._setAlpha3885, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColorFilter3886;
public override void setColorFilter(android.graphics.ColorFilter arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._setColorFilter3886, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._setColorFilter3886, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isStateful3887;
public override bool isStateful()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._isStateful3887);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._isStateful3887);
}
internal static global::MonoJavaBridge.MethodId _setVisible3888;
public override bool setVisible(bool arg0, bool arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._setVisible3888, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._setVisible3888, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getOpacity3889;
public override int getOpacity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._getOpacity3889);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._getOpacity3889);
}
internal static global::MonoJavaBridge.MethodId _onStateChange3890;
protected override bool onStateChange(int[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._onStateChange3890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._onStateChange3890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onLevelChange3891;
protected override bool onLevelChange(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._onLevelChange3891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._onLevelChange3891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onBoundsChange3892;
protected override void onBoundsChange(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._onBoundsChange3892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._onBoundsChange3892, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicWidth3893;
public override int getIntrinsicWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._getIntrinsicWidth3893);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._getIntrinsicWidth3893);
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicHeight3894;
public override int getIntrinsicHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._getIntrinsicHeight3894);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._getIntrinsicHeight3894);
}
internal static global::MonoJavaBridge.MethodId _getPadding3895;
public override bool getPadding(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._getPadding3895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._getPadding3895, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getConstantState3896;
public override global::android.graphics.drawable.Drawable.ConstantState getConstantState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._getConstantState3896)) as android.graphics.drawable.Drawable.ConstantState;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._getConstantState3896)) as android.graphics.drawable.Drawable.ConstantState;
}
internal static global::MonoJavaBridge.MethodId _invalidateDrawable3897;
public virtual void invalidateDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._invalidateDrawable3897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._invalidateDrawable3897, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _scheduleDrawable3898;
public virtual void scheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1, long arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._scheduleDrawable3898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._scheduleDrawable3898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _unscheduleDrawable3899;
public virtual void unscheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable._unscheduleDrawable3899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._unscheduleDrawable3899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _ClipDrawable3900;
public ClipDrawable(android.graphics.drawable.Drawable arg0, int arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.ClipDrawable.staticClass, global::android.graphics.drawable.ClipDrawable._ClipDrawable3900, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
public static int HORIZONTAL
{
get
{
return 1;
}
}
public static int VERTICAL
{
get
{
return 2;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.ClipDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/ClipDrawable"));
global::android.graphics.drawable.ClipDrawable._inflate3882 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V");
global::android.graphics.drawable.ClipDrawable._draw3883 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V");
global::android.graphics.drawable.ClipDrawable._getChangingConfigurations3884 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "getChangingConfigurations", "()I");
global::android.graphics.drawable.ClipDrawable._setAlpha3885 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "setAlpha", "(I)V");
global::android.graphics.drawable.ClipDrawable._setColorFilter3886 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V");
global::android.graphics.drawable.ClipDrawable._isStateful3887 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "isStateful", "()Z");
global::android.graphics.drawable.ClipDrawable._setVisible3888 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "setVisible", "(ZZ)Z");
global::android.graphics.drawable.ClipDrawable._getOpacity3889 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "getOpacity", "()I");
global::android.graphics.drawable.ClipDrawable._onStateChange3890 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "onStateChange", "([I)Z");
global::android.graphics.drawable.ClipDrawable._onLevelChange3891 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "onLevelChange", "(I)Z");
global::android.graphics.drawable.ClipDrawable._onBoundsChange3892 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V");
global::android.graphics.drawable.ClipDrawable._getIntrinsicWidth3893 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "getIntrinsicWidth", "()I");
global::android.graphics.drawable.ClipDrawable._getIntrinsicHeight3894 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "getIntrinsicHeight", "()I");
global::android.graphics.drawable.ClipDrawable._getPadding3895 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z");
global::android.graphics.drawable.ClipDrawable._getConstantState3896 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;");
global::android.graphics.drawable.ClipDrawable._invalidateDrawable3897 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "invalidateDrawable", "(Landroid/graphics/drawable/Drawable;)V");
global::android.graphics.drawable.ClipDrawable._scheduleDrawable3898 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "scheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V");
global::android.graphics.drawable.ClipDrawable._unscheduleDrawable3899 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "unscheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V");
global::android.graphics.drawable.ClipDrawable._ClipDrawable3900 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ClipDrawable.staticClass, "<init>", "(Landroid/graphics/drawable/Drawable;II)V");
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Chutzpah.FrameworkDefinitions;
using Chutzpah.Models;
using Chutzpah.Utility;
using Chutzpah.Wrappers;
using Moq;
using Xunit;
namespace Chutzpah.Facts
{
public class TestHarnessBuilderFacts
{
private const string TestTempateContents = @"
<!DOCTYPE html><html><head>
@@TestFrameworkDependencies@@
@@ReferencedCSSFiles@@
@@TestHtmlTemplateFiles@@
@@ReferencedJSFiles@@
@@TestJSFile@@
@@CustomReplacement1@@
@@CustomReplacement2@@
</head>
<body><div id=""qunit-fixture""></div></body></html>
";
private static string TestContextBuilder_GetScriptStatement(string path)
{
return new Script(new ReferencedFile { Path = path, PathForUseInTestHarness = path }).ToString();
}
private static string TestContextBuilder_GetStyleStatement(string path)
{
return new ExternalStylesheet(new ReferencedFile { Path = path, PathForUseInTestHarness = path }).ToString();
}
private class TestableTestHarnessBuilder : Testable<TestHarnessBuilder>
{
public TestableTestHarnessBuilder()
{
var frameworkMock = Mock<IFrameworkDefinition>();
frameworkMock.Setup(x => x.FileUsesFramework(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<PathType>())).Returns(true);
frameworkMock.Setup(x => x.FrameworkKey).Returns("qunit");
frameworkMock.Setup(x => x.GetTestRunner(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunitRunner.js");
frameworkMock.Setup(x => x.GetTestHarness(It.IsAny<ChutzpahTestSettingsFile>())).Returns("qunit.html");
frameworkMock.Setup(x => x.GetFileDependencies(It.IsAny<ChutzpahTestSettingsFile>())).Returns(new[] { "qunit.js", "qunit.css" });
Mock<IFileProbe>().Setup(x => x.FindFilePath(It.IsAny<string>())).Returns<string>(x => x);
Mock<IFileProbe>().Setup(x => x.GetPathInfo(It.IsAny<string>())).Returns<string>(x => new PathInfo { FullPath = x, Type = PathType.JavaScript });
Mock<IFileSystemWrapper>().Setup(x => x.GetTemporaryFolder(It.IsAny<string>())).Returns(@"C:\temp\");
Mock<IFileSystemWrapper>().Setup(x => x.GetText(It.IsAny<string>())).Returns(string.Empty);
Mock<IFileSystemWrapper>().Setup(x => x.GetRandomFileName()).Returns("unique");
Mock<IFileSystemWrapper>().Setup(x => x.FolderExists(It.IsAny<string>())).Returns(true);
Mock<IHasher>().Setup(x => x.Hash(It.IsAny<string>())).Returns("hash");
Mock<IFileProbe>()
.Setup(x => x.GetPathInfo(@"TestFiles\qunit.html"))
.Returns(new PathInfo { Type = PathType.JavaScript, FullPath = @"path\qunit.html" });
Mock<IFileProbe>()
.Setup(x => x.BuiltInDependencyDirectory)
.Returns(@"dependencyPath\");
Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"dependencyPath\qunit.html"))
.Returns(TestTempateContents);
}
public TestContext GetContext()
{
var context = new TestContext
{
InputTestFiles = new []{ @"C:\folder\test.js"},
TestHarnessDirectory = @"C:\folder",
FrameworkDefinition = Mock<IFrameworkDefinition>().Object,
TestFileSettings = new ChutzpahTestSettingsFile().InheritFromDefault()
};
context.TestFileSettings.SettingsFileDirectory = "settingsPath";
return context;
}
}
[Fact]
public void Will_save_generated_test_html()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
creator.Mock<IFileSystemWrapper>().Verify(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()));
Assert.Equal(@"C:\folder\_Chutzpah.hash.test.html", context.TestHarnessPath);
Assert.Equal(@"C:\folder\test.js", context.InputTestFiles.FirstOrDefault());
}
[Fact]
public void Will_use_custom_template_path()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
string text = null;
context.ReferencedFiles.Add(new ReferencedFile { Path = @"dependencyPath\qunit.js", PathForUseInTestHarness = @"dependencyPath\qunit.js", IsTestFrameworkFile = true});
context.ReferencedFiles.Add(new ReferencedFile { Path = @"dependencyPath\qunit.css", PathForUseInTestHarness = @"dependencyPath\qunit.css", IsTestFrameworkFile = true });
context.TestFileSettings.CustomTestHarnessPath = @"folder\customHarness.html";
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.Mock<IFileProbe>()
.Setup(x => x.FindFilePath(@"settingsPath\folder\customHarness.html"))
.Returns(@"path\customHarness.html");
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\customHarness.html"))
.Returns(TestTempateContents);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement = TestContextBuilder_GetScriptStatement(@"dependencyPath\qunit.js");
string cssStatement = TestContextBuilder_GetStyleStatement(@"dependencyPath\qunit.css");
Assert.Contains(scriptStatement, text);
Assert.Contains(cssStatement, text);
Assert.DoesNotContain("@@TestFrameworkDependencies@@", text);
}
[Fact]
public void Will_replace_test_dependency_placeholder_in_test_harness_html()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"dependencyPath\qunit.js", PathForUseInTestHarness = @"dependencyPath\qunit.js", IsTestFrameworkFile = true });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"dependencyPath\qunit.css", PathForUseInTestHarness = @"dependencyPath\qunit.css", IsTestFrameworkFile = true });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement = TestContextBuilder_GetScriptStatement(@"dependencyPath\qunit.js");
string cssStatement = TestContextBuilder_GetStyleStatement(@"dependencyPath\qunit.css");
Assert.Contains(scriptStatement, text);
Assert.Contains(cssStatement, text);
Assert.DoesNotContain("@@TestFrameworkDependencies@@", text);
}
[Fact]
public void Will_put_test_html_file_at_end_of_references_in_html_template()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\file.html" , PathForUseInTestHarness = @"path\file.html" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.GetText(@"path\file.html"))
.Returns("<h1>This is the included HTML</h1>");
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
Assert.Contains("<h1>This is the included HTML</h1>", text);
}
[Fact]
public void Will_put_test_js_file_at_end_of_references_in_html_template_with_test_file()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\test.js", PathForUseInTestHarness = @"path\test.js", IsFileUnderTest = true });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\lib.js" , PathForUseInTestHarness = @"path\lib.js" });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\common.js" , PathForUseInTestHarness = @"path\common.js" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement1 = TestContextBuilder_GetScriptStatement(@"path\lib.js");
string scriptStatement2 = TestContextBuilder_GetScriptStatement(@"path\common.js");
string scriptStatement3 = TestContextBuilder_GetScriptStatement(@"path\test.js");
var pos1 = text.IndexOf(scriptStatement1);
var pos2 = text.IndexOf(scriptStatement2);
var pos3 = text.IndexOf(scriptStatement3);
Assert.True(pos1 < pos2);
Assert.True(pos2 < pos3);
Assert.Equal(1, context.ReferencedFiles.Count(x => x.IsFileUnderTest));
}
[Fact]
public void Will_replace_referenced_js_file_place_holder_in_html_template_with_referenced_js_files_from_js_test_file()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\lib.js", PathForUseInTestHarness = @"path\lib.js" });
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\common.js", PathForUseInTestHarness = @"path\common.js" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string scriptStatement1 = TestContextBuilder_GetScriptStatement(@"path\lib.js");
string scriptStatement2 = TestContextBuilder_GetScriptStatement(@"path\common.js");
Assert.Contains(scriptStatement1, text);
Assert.Contains(scriptStatement2, text);
Assert.DoesNotContain("@@ReferencedJSFiles@@", text);
}
[Fact]
public void Will_replace_referenced_css_file_place_holder_in_html_template_with_referenced_css_files_from_js_test_file()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
context.ReferencedFiles.Add(new ReferencedFile { Path = @"path\style.css", PathForUseInTestHarness = @"path\style.css" });
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
string styleStatement = TestContextBuilder_GetStyleStatement(@"path\style.css");
Assert.Contains(styleStatement, text);
Assert.DoesNotContain("@@ReferencedCSSFiles@@", text);
}
[Fact]
public void Will_replace_custom_framework_placeholders_with_contents_from_framwork_definition()
{
var creator = new TestableTestHarnessBuilder();
var context = creator.GetContext();
string text = null;
creator.Mock<IFileSystemWrapper>()
.Setup(x => x.Save(@"C:\folder\_Chutzpah.hash.test.html", It.IsAny<string>()))
.Callback<string, string>((x, y) => text = y);
creator.Mock<IFrameworkDefinition>()
.Setup(x => x.GetFrameworkReplacements(It.IsAny<ChutzpahTestSettingsFile>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns(new Dictionary<string, string>
{
{"CustomReference1", "CustomReplacement1"},
{"CustomReference2", "CustomReplacement2"}
});
creator.ClassUnderTest.CreateTestHarness(context, new TestOptions());
Assert.DoesNotContain("@@CustomReference1@@", text);
Assert.DoesNotContain("@@CustomReference2@@", text);
Assert.Contains("CustomReplacement1", text);
Assert.Contains("CustomReplacement2", text);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ARPrestoCallbackManager.cs" company="Google">
//
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
using System;
using System.Collections.Generic;
using GoogleARCore;
using UnityEngine;
#if UNITY_IOS && !UNITY_EDITOR
using AndroidImport = GoogleARCoreInternal.DllImportNoop;
using IOSImport = System.Runtime.InteropServices.DllImportAttribute;
#else
using AndroidImport = System.Runtime.InteropServices.DllImportAttribute;
using IOSImport = GoogleARCoreInternal.DllImportNoop;
#endif
internal class ARPrestoCallbackManager
{
private static ARPrestoCallbackManager s_Instance;
private CheckApkAvailabilityResultCallback m_CheckApkAvailabilityResultCallback;
private RequestApkInstallationResultCallback m_RequestApkInstallationResultCallback;
private CameraPermissionRequestProvider m_RequestCameraPermissionCallback;
private EarlyUpdateCallback m_EarlyUpdateCallback;
private OnBeforeSetConfigurationCallback m_OnBeforeSetConfigurationCallback;
private OnBeforeResumeSessionCallback m_OnBeforeResumeSessionCallback;
private List<Action<ApkAvailabilityStatus>> m_PendingAvailabilityCheckCallbacks =
new List<Action<ApkAvailabilityStatus>>();
private List<Action<ApkInstallationStatus>> m_PendingInstallationRequestCallbacks =
new List<Action<ApkInstallationStatus>>();
public delegate void EarlyUpdateCallback();
private delegate void OnBeforeSetConfigurationCallback(
IntPtr sessionHandle, IntPtr configHandle);
private delegate void OnBeforeResumeSessionCallback(IntPtr sessionHandle);
private delegate void CameraPermissionRequestProvider(
CameraPermissionsResultCallback onComplete, IntPtr context);
private delegate void CameraPermissionsResultCallback(bool granted,
IntPtr context);
private delegate void CheckApkAvailabilityResultCallback(ApiAvailability status,
IntPtr context);
private delegate void RequestApkInstallationResultCallback(
ApiApkInstallationStatus status, IntPtr context);
private delegate void SessionCreationResultCallback(
IntPtr sessionHandle, IntPtr frameHandle, IntPtr context, ApiArStatus status);
public event Action EarlyUpdate;
public event Action<IntPtr> BeforeResumeSession;
public static ARPrestoCallbackManager Instance
{
get
{
if (s_Instance == null)
{
s_Instance = new ARPrestoCallbackManager();
s_Instance._Initialize();
}
return s_Instance;
}
}
public AsyncTask<ApkAvailabilityStatus> CheckApkAvailability()
{
Action<ApkAvailabilityStatus> onComplete;
AsyncTask<ApkAvailabilityStatus> task =
new AsyncTask<ApkAvailabilityStatus>(out onComplete);
if (InstantPreviewManager.IsProvidingPlatform)
{
InstantPreviewManager.LogLimitedSupportMessage("determine ARCore APK " +
"availability");
return task;
}
ExternApi.ArPresto_checkApkAvailability(m_CheckApkAvailabilityResultCallback,
IntPtr.Zero);
m_PendingAvailabilityCheckCallbacks.Add(onComplete);
return task;
}
public AsyncTask<ApkInstallationStatus> RequestApkInstallation(bool userRequested)
{
Action<ApkInstallationStatus> onComplete;
AsyncTask<ApkInstallationStatus> task =
new AsyncTask<ApkInstallationStatus>(out onComplete);
if (InstantPreviewManager.IsProvidingPlatform)
{
InstantPreviewManager.LogLimitedSupportMessage("request installation of ARCore " +
"APK");
return task;
}
ExternApi.ArPresto_requestApkInstallation(userRequested,
m_RequestApkInstallationResultCallback, IntPtr.Zero);
m_PendingInstallationRequestCallbacks.Add(onComplete);
return task;
}
[AOT.MonoPInvokeCallback(typeof(CheckApkAvailabilityResultCallback))]
private static void _OnCheckApkAvailabilityResultTrampoline(
ApiAvailability status, IntPtr context)
{
Instance._OnCheckApkAvailabilityResult(status.ToApkAvailabilityStatus());
}
[AOT.MonoPInvokeCallback(typeof(RequestApkInstallationResultCallback))]
private static void _OnApkInstallationResultTrampoline(
ApiApkInstallationStatus status, IntPtr context)
{
Instance._OnRequestApkInstallationResult(status.ToApkInstallationStatus());
}
[AOT.MonoPInvokeCallback(typeof(CameraPermissionRequestProvider))]
private static void _RequestCameraPermissionTrampoline(
CameraPermissionsResultCallback onComplete, IntPtr context)
{
Instance._RequestCameraPermission(onComplete, context);
}
[AOT.MonoPInvokeCallback(typeof(EarlyUpdateCallback))]
private static void _EarlyUpdateTrampoline()
{
if (Instance.EarlyUpdate != null)
{
Instance.EarlyUpdate();
}
}
[AOT.MonoPInvokeCallback(typeof(OnBeforeSetConfigurationCallback))]
private static void _BeforeSetConfigurationTrampoline(
IntPtr sessionHandle, IntPtr configHandle)
{
ExperimentManager.Instance.OnBeforeSetConfiguration(sessionHandle, configHandle);
}
[AOT.MonoPInvokeCallback(typeof(OnBeforeResumeSessionCallback))]
private static void _BeforeResumeSessionTrampoline(IntPtr sessionHandle)
{
if (Instance.BeforeResumeSession != null)
{
Instance.BeforeResumeSession(sessionHandle);
}
}
private void _Initialize()
{
m_EarlyUpdateCallback = new EarlyUpdateCallback(_EarlyUpdateTrampoline);
if (InstantPreviewManager.IsProvidingPlatform)
{
// Instant preview does not support updated function signature returning 'bool'.
ExternApi.ArCoreUnity_setArPrestoInitialized(m_EarlyUpdateCallback);
}
else if (!ExternApi.ArCoreUnity_setArPrestoInitialized(m_EarlyUpdateCallback))
{
Debug.LogError(
"Missing Unity Engine ARCore support. Please ensure that the Unity project " +
"has the 'Player Settings > XR Settings > ARCore Supported' checkbox enabled.");
}
IntPtr javaVMHandle = IntPtr.Zero;
IntPtr activityHandle = IntPtr.Zero;
ExternApi.ArCoreUnity_getJniInfo(ref javaVMHandle, ref activityHandle);
m_CheckApkAvailabilityResultCallback =
new CheckApkAvailabilityResultCallback(_OnCheckApkAvailabilityResultTrampoline);
m_RequestApkInstallationResultCallback =
new RequestApkInstallationResultCallback(_OnApkInstallationResultTrampoline);
m_RequestCameraPermissionCallback =
new CameraPermissionRequestProvider(_RequestCameraPermissionTrampoline);
m_OnBeforeSetConfigurationCallback =
new OnBeforeSetConfigurationCallback(_BeforeSetConfigurationTrampoline);
m_OnBeforeResumeSessionCallback =
new OnBeforeResumeSessionCallback(_BeforeResumeSessionTrampoline);
ExternApi.ArPresto_initialize(
javaVMHandle, activityHandle, m_RequestCameraPermissionCallback,
m_OnBeforeSetConfigurationCallback, m_OnBeforeResumeSessionCallback);
}
private void _OnCheckApkAvailabilityResult(ApkAvailabilityStatus status)
{
foreach (var onComplete in m_PendingAvailabilityCheckCallbacks)
{
onComplete(status);
}
m_PendingAvailabilityCheckCallbacks.Clear();
}
private void _OnRequestApkInstallationResult(ApkInstallationStatus status)
{
foreach (var onComplete in m_PendingInstallationRequestCallbacks)
{
onComplete(status);
}
m_PendingInstallationRequestCallbacks.Clear();
}
private void _RequestCameraPermission(CameraPermissionsResultCallback onComplete,
IntPtr context)
{
const string cameraPermissionName = "android.permission.CAMERA";
AndroidPermissionsManager.RequestPermission(cameraPermissionName)
.ThenAction((grantResult) =>
{
onComplete(grantResult.IsAllGranted, context);
});
}
private struct ExternApi
{
#pragma warning disable 626
[AndroidImport(ApiConstants.ARCoreShimApi)]
public static extern void ArCoreUnity_getJniInfo(
ref IntPtr javaVM, ref IntPtr activity);
[AndroidImport(ApiConstants.ARCoreShimApi)]
public static extern bool ArCoreUnity_setArPrestoInitialized(
EarlyUpdateCallback onEarlyUpdate);
[AndroidImport(ApiConstants.ARPrestoApi)]
public static extern void ArPresto_initialize(
IntPtr javaVM, IntPtr activity,
CameraPermissionRequestProvider requestCameraPermission,
OnBeforeSetConfigurationCallback onBeforeSetConfiguration,
OnBeforeResumeSessionCallback onBeforeResumeSession);
[AndroidImport(ApiConstants.ARPrestoApi)]
public static extern void ArPresto_checkApkAvailability(
CheckApkAvailabilityResultCallback onResult, IntPtr context);
[AndroidImport(ApiConstants.ARPrestoApi)]
public static extern void ArPresto_requestApkInstallation(
bool user_requested, RequestApkInstallationResultCallback onResult, IntPtr context);
#pragma warning restore 626
}
}
}
| |
#region Copyright
/*
* Copyright (C) 2017 Angel Newton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
namespace Ideal.SampleDBModel
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class SampleModel : DbContext
{
public SampleModel()
: base("name=SampleModel")
{
}
public virtual DbSet<ACCOUNT_TBL> ACCOUNT_TBL { get; set; }
public virtual DbSet<ADDRESS_TBL> ADDRESS_TBL { get; set; }
public virtual DbSet<CLIENT_TBL> CLIENT_TBL { get; set; }
public virtual DbSet<EMPLOYEE_TBL> EMPLOYEE_TBL { get; set; }
public virtual DbSet<ITEM_TBL> ITEM_TBL { get; set; }
public virtual DbSet<PAYMENT_MODE_TBL> PAYMENT_MODE_TBL { get; set; }
public virtual DbSet<PAYMENT_TBL> PAYMENT_TBL { get; set; }
public virtual DbSet<PROVIDER_TBL> PROVIDER_TBL { get; set; }
public virtual DbSet<REFERENCE_TBL> REFERENCE_TBL { get; set; }
public virtual DbSet<SCHEDULED_PAYMENT_TBL> SCHEDULED_PAYMENT_TBL { get; set; }
public virtual DbSet<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW> ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW { get; set; }
public virtual DbSet<PAYMENTS_VIEW> PAYMENTS_VIEW { get; set; }
public virtual DbSet<TOTAL_INVESTED_VS_RECOVERED_VS_SCHEDULED_VIEW> TOTAL_INVESTED_VS_RECOVERED_VS_SCHEDULED_VIEW { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_ID)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.CLI_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ITEM_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.PAYMD_ID)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_STATUS)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_PRICE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_HITCH)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_INITIAL_BALANCE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_CURRENT_BALANCE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_DISTANCE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_SELLER_ID)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_TBL>()
.Property(e => e.ACC_NOTES)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_TBL>()
.HasMany(e => e.PAYMENT_TBL)
.WithRequired(e => e.ACCOUNT_TBL)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ACCOUNT_TBL>()
.HasMany(e => e.SCHEDULED_PAYMENT_TBL)
.WithRequired(e => e.ACCOUNT_TBL)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ADDRESS_TBL>()
.Property(e => e.ADDR_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<ADDRESS_TBL>()
.Property(e => e.ADDR_STREET_NUMBER)
.IsUnicode(false);
modelBuilder.Entity<ADDRESS_TBL>()
.Property(e => e.ADDR_NEIGHBORHOOD)
.IsUnicode(false);
modelBuilder.Entity<ADDRESS_TBL>()
.Property(e => e.ADDR_CITY)
.IsUnicode(false);
modelBuilder.Entity<ADDRESS_TBL>()
.Property(e => e.ADDR_STATE)
.IsUnicode(false);
modelBuilder.Entity<ADDRESS_TBL>()
.Property(e => e.ADDR_COUNTRY)
.IsUnicode(false);
modelBuilder.Entity<ADDRESS_TBL>()
.HasMany(e => e.CLIENT_TBL)
.WithOptional(e => e.ADDRESS_TBL)
.HasForeignKey(e => e.CLI_HOME_ADDR_ID);
modelBuilder.Entity<ADDRESS_TBL>()
.HasMany(e => e.CLIENT_TBL1)
.WithOptional(e => e.ADDRESS_TBL1)
.HasForeignKey(e => e.CLI_WORK_ADDR_ID);
modelBuilder.Entity<ADDRESS_TBL>()
.HasMany(e => e.PROVIDER_TBL)
.WithOptional(e => e.ADDRESS_TBL)
.HasForeignKey(e => e.PROV_ADDR_ID);
modelBuilder.Entity<ADDRESS_TBL>()
.HasMany(e => e.REFERENCE_TBL)
.WithOptional(e => e.ADDRESS_TBL)
.HasForeignKey(e => e.REF_ADDR_ID);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_NAMES)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_FAMILY_NAME)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_HOME_PHONE)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_WORK_PHONE)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_HOME_ADDR_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_WORK_ADDR_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_OCUPATION)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_NOTES)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_PARTNER_NAMES)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_PARTNER_FAMILY_NAME)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_REFERENCE_ID1)
.HasPrecision(10, 0);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_REFERENCE_ID2)
.HasPrecision(10, 0);
modelBuilder.Entity<CLIENT_TBL>()
.Property(e => e.CLI_SCORE)
.IsUnicode(false);
modelBuilder.Entity<CLIENT_TBL>()
.HasMany(e => e.ACCOUNT_TBL)
.WithRequired(e => e.CLIENT_TBL)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.Property(e => e.EMP_ID)
.IsUnicode(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.Property(e => e.EMP_TYPE)
.IsUnicode(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.Property(e => e.EMP_NAMES)
.IsUnicode(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.Property(e => e.EMP_FAMILY_NAME)
.IsUnicode(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.HasMany(e => e.ACCOUNT_TBL)
.WithRequired(e => e.EMPLOYEE_TBL)
.HasForeignKey(e => e.ACC_SELLER_ID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.HasMany(e => e.PAYMENT_TBL)
.WithRequired(e => e.EMPLOYEE_TBL)
.HasForeignKey(e => e.PAY_COLLECTOR)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EMPLOYEE_TBL>()
.HasMany(e => e.PAYMENT_TBL1)
.WithRequired(e => e.EMPLOYEE_TBL1)
.HasForeignKey(e => e.PAY_INSPECTOR)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ITEM_TBL>()
.Property(e => e.ITEM_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<ITEM_TBL>()
.Property(e => e.PROV_ID)
.IsUnicode(false);
modelBuilder.Entity<ITEM_TBL>()
.Property(e => e.ITEM_NAME)
.IsUnicode(false);
modelBuilder.Entity<ITEM_TBL>()
.Property(e => e.ITEM_BUY_PRICE)
.HasPrecision(10, 2);
modelBuilder.Entity<ITEM_TBL>()
.HasMany(e => e.ACCOUNT_TBL)
.WithRequired(e => e.ITEM_TBL)
.WillCascadeOnDelete(false);
modelBuilder.Entity<PAYMENT_MODE_TBL>()
.Property(e => e.PAYMD_ID)
.IsUnicode(false);
modelBuilder.Entity<PAYMENT_MODE_TBL>()
.Property(e => e.PAYMD_AMOUNT)
.HasPrecision(10, 2);
modelBuilder.Entity<PAYMENT_MODE_TBL>()
.Property(e => e.PAYMD_FREQUENCY)
.IsUnicode(false);
modelBuilder.Entity<PAYMENT_MODE_TBL>()
.Property(e => e.PAYMD_DAY)
.IsFixedLength();
modelBuilder.Entity<PAYMENT_MODE_TBL>()
.HasMany(e => e.ACCOUNT_TBL)
.WithRequired(e => e.PAYMENT_MODE_TBL)
.WillCascadeOnDelete(false);
modelBuilder.Entity<PAYMENT_TBL>()
.Property(e => e.PAY_ID)
.HasPrecision(20, 0);
modelBuilder.Entity<PAYMENT_TBL>()
.Property(e => e.ACC_ID)
.IsUnicode(false);
modelBuilder.Entity<PAYMENT_TBL>()
.Property(e => e.PAY_AMOUNT)
.HasPrecision(10, 2);
modelBuilder.Entity<PAYMENT_TBL>()
.Property(e => e.PAY_COLLECTOR)
.IsUnicode(false);
modelBuilder.Entity<PAYMENT_TBL>()
.Property(e => e.PAY_INSPECTOR)
.IsUnicode(false);
modelBuilder.Entity<PROVIDER_TBL>()
.Property(e => e.PROV_ID)
.IsUnicode(false);
modelBuilder.Entity<PROVIDER_TBL>()
.Property(e => e.PROV_NAME)
.IsUnicode(false);
modelBuilder.Entity<PROVIDER_TBL>()
.Property(e => e.PROV_ADDR_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<PROVIDER_TBL>()
.Property(e => e.PROV_PHONE)
.IsUnicode(false);
modelBuilder.Entity<PROVIDER_TBL>()
.Property(e => e.PROV_WEBSITE)
.IsUnicode(false);
modelBuilder.Entity<PROVIDER_TBL>()
.Property(e => e.PROV_NOTES)
.IsUnicode(false);
modelBuilder.Entity<PROVIDER_TBL>()
.HasMany(e => e.ITEM_TBL)
.WithRequired(e => e.PROVIDER_TBL)
.WillCascadeOnDelete(false);
modelBuilder.Entity<REFERENCE_TBL>()
.Property(e => e.REF_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<REFERENCE_TBL>()
.Property(e => e.REF_NAMES)
.IsUnicode(false);
modelBuilder.Entity<REFERENCE_TBL>()
.Property(e => e.REF_FAMILY_NAME)
.IsUnicode(false);
modelBuilder.Entity<REFERENCE_TBL>()
.Property(e => e.REF_PHONE)
.IsUnicode(false);
modelBuilder.Entity<REFERENCE_TBL>()
.Property(e => e.REF_ADDR_ID)
.HasPrecision(10, 0);
modelBuilder.Entity<REFERENCE_TBL>()
.Property(e => e.REF_RELATION)
.IsUnicode(false);
modelBuilder.Entity<REFERENCE_TBL>()
.HasMany(e => e.CLIENT_TBL)
.WithOptional(e => e.REFERENCE_TBL)
.HasForeignKey(e => e.CLI_REFERENCE_ID1);
modelBuilder.Entity<REFERENCE_TBL>()
.HasMany(e => e.CLIENT_TBL1)
.WithOptional(e => e.REFERENCE_TBL1)
.HasForeignKey(e => e.CLI_REFERENCE_ID2);
modelBuilder.Entity<SCHEDULED_PAYMENT_TBL>()
.Property(e => e.SCHPAY_ID)
.HasPrecision(20, 0);
modelBuilder.Entity<SCHEDULED_PAYMENT_TBL>()
.Property(e => e.ACC_ID)
.IsUnicode(false);
modelBuilder.Entity<SCHEDULED_PAYMENT_TBL>()
.Property(e => e.SCHPAY_AMOUNT)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ACC_ID)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ITEM_NAME)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.PAYMD_ID)
.IsUnicode(false);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ACC_DISTANCE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ACC_PRICE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ACC_HITCH)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ACC_INITIAL_BALANCE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.CALCULATED_CURRENT_BALANCE)
.HasPrecision(38, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.CALCULATED_GAIN)
.HasPrecision(11, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.ITEM_BUY_PRICE)
.HasPrecision(10, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.PAYMENTS)
.HasPrecision(38, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.SUM_SCHEDULED_PAYMENTS)
.HasPrecision(38, 2);
modelBuilder.Entity<ACCOUNT_CLIENT_SCHEDULED_PAYMENTS_VIEW>()
.Property(e => e.DIFF_SCHEDULED)
.HasPrecision(38, 2);
modelBuilder.Entity<PAYMENTS_VIEW>()
.Property(e => e.ACC_ID)
.IsUnicode(false);
modelBuilder.Entity<PAYMENTS_VIEW>()
.Property(e => e.NAME)
.IsUnicode(false);
modelBuilder.Entity<PAYMENTS_VIEW>()
.Property(e => e.ITEM_NAME)
.IsUnicode(false);
modelBuilder.Entity<PAYMENTS_VIEW>()
.Property(e => e.PAY_AMOUNT)
.HasPrecision(10, 2);
modelBuilder.Entity<PAYMENTS_VIEW>()
.Property(e => e.PAY_COLLECTOR)
.IsUnicode(false);
modelBuilder.Entity<PAYMENTS_VIEW>()
.Property(e => e.PAY_INSPECTOR)
.IsUnicode(false);
modelBuilder.Entity<TOTAL_INVESTED_VS_RECOVERED_VS_SCHEDULED_VIEW>()
.Property(e => e.DESCRIPTION)
.IsUnicode(false);
modelBuilder.Entity<TOTAL_INVESTED_VS_RECOVERED_VS_SCHEDULED_VIEW>()
.Property(e => e.VALUE)
.HasPrecision(38, 2);
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// ReceivingWorksheet
/// </summary>
[DataContract]
public partial class ReceivingWorksheet : IEquatable<ReceivingWorksheet>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingWorksheet" /> class.
/// </summary>
[JsonConstructorAttribute]
protected ReceivingWorksheet() { }
/// <summary>
/// Initializes a new instance of the <see cref="ReceivingWorksheet" /> class.
/// </summary>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="PoNoId">PoNoId.</param>
/// <param name="LobId">LobId.</param>
/// <param name="VendorId">VendorId.</param>
/// <param name="ServiceLevel">ServiceLevel (required).</param>
/// <param name="CreatedBy">CreatedBy.</param>
/// <param name="WorksheetName">WorksheetName (required).</param>
/// <param name="Carrier">Carrier.</param>
/// <param name="OnTheDock">OnTheDock (default to false).</param>
/// <param name="AutoCommit">AutoCommit (required) (default to false).</param>
/// <param name="LineItems">LineItems.</param>
/// <param name="Notes">Notes.</param>
public ReceivingWorksheet(int? WarehouseId = null, int? PoNoId = null, int? LobId = null, int? VendorId = null, string ServiceLevel = null, int? CreatedBy = null, string WorksheetName = null, string Carrier = null, bool? OnTheDock = null, bool? AutoCommit = null, List<ReceivingWorksheetLineItem> LineItems = null, string Notes = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for ReceivingWorksheet and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// to ensure "ServiceLevel" is required (not null)
if (ServiceLevel == null)
{
throw new InvalidDataException("ServiceLevel is a required property for ReceivingWorksheet and cannot be null");
}
else
{
this.ServiceLevel = ServiceLevel;
}
// to ensure "WorksheetName" is required (not null)
if (WorksheetName == null)
{
throw new InvalidDataException("WorksheetName is a required property for ReceivingWorksheet and cannot be null");
}
else
{
this.WorksheetName = WorksheetName;
}
// to ensure "AutoCommit" is required (not null)
if (AutoCommit == null)
{
throw new InvalidDataException("AutoCommit is a required property for ReceivingWorksheet and cannot be null");
}
else
{
this.AutoCommit = AutoCommit;
}
this.PoNoId = PoNoId;
this.LobId = LobId;
this.VendorId = VendorId;
this.CreatedBy = CreatedBy;
this.Carrier = Carrier;
// use default value if no "OnTheDock" provided
if (OnTheDock == null)
{
this.OnTheDock = false;
}
else
{
this.OnTheDock = OnTheDock;
}
this.LineItems = LineItems;
this.Notes = Notes;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets PoNoId
/// </summary>
[DataMember(Name="poNoId", EmitDefaultValue=false)]
public int? PoNoId { get; set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets VendorId
/// </summary>
[DataMember(Name="vendorId", EmitDefaultValue=false)]
public int? VendorId { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; private set; }
/// <summary>
/// Gets or Sets ServiceLevel
/// </summary>
[DataMember(Name="serviceLevel", EmitDefaultValue=false)]
public string ServiceLevel { get; set; }
/// <summary>
/// Gets or Sets CreatedBy
/// </summary>
[DataMember(Name="createdBy", EmitDefaultValue=false)]
public int? CreatedBy { get; set; }
/// <summary>
/// Gets or Sets WorksheetName
/// </summary>
[DataMember(Name="worksheetName", EmitDefaultValue=false)]
public string WorksheetName { get; set; }
/// <summary>
/// Gets or Sets Carrier
/// </summary>
[DataMember(Name="carrier", EmitDefaultValue=false)]
public string Carrier { get; set; }
/// <summary>
/// Gets or Sets OnTheDock
/// </summary>
[DataMember(Name="onTheDock", EmitDefaultValue=false)]
public bool? OnTheDock { get; set; }
/// <summary>
/// Gets or Sets AutoCommit
/// </summary>
[DataMember(Name="autoCommit", EmitDefaultValue=false)]
public bool? AutoCommit { get; set; }
/// <summary>
/// Gets or Sets LineItems
/// </summary>
[DataMember(Name="lineItems", EmitDefaultValue=false)]
public List<ReceivingWorksheetLineItem> LineItems { get; set; }
/// <summary>
/// Gets or Sets Notes
/// </summary>
[DataMember(Name="notes", EmitDefaultValue=false)]
public string Notes { get; set; }
/// <summary>
/// Gets or Sets WorkBatchId
/// </summary>
[DataMember(Name="workBatchId", EmitDefaultValue=false)]
public int? WorkBatchId { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ReceivingWorksheet {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" PoNoId: ").Append(PoNoId).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" VendorId: ").Append(VendorId).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" ServiceLevel: ").Append(ServiceLevel).Append("\n");
sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n");
sb.Append(" WorksheetName: ").Append(WorksheetName).Append("\n");
sb.Append(" Carrier: ").Append(Carrier).Append("\n");
sb.Append(" OnTheDock: ").Append(OnTheDock).Append("\n");
sb.Append(" AutoCommit: ").Append(AutoCommit).Append("\n");
sb.Append(" LineItems: ").Append(LineItems).Append("\n");
sb.Append(" Notes: ").Append(Notes).Append("\n");
sb.Append(" WorkBatchId: ").Append(WorkBatchId).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ReceivingWorksheet);
}
/// <summary>
/// Returns true if ReceivingWorksheet instances are equal
/// </summary>
/// <param name="other">Instance of ReceivingWorksheet to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ReceivingWorksheet other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.PoNoId == other.PoNoId ||
this.PoNoId != null &&
this.PoNoId.Equals(other.PoNoId)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.VendorId == other.VendorId ||
this.VendorId != null &&
this.VendorId.Equals(other.VendorId)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.ServiceLevel == other.ServiceLevel ||
this.ServiceLevel != null &&
this.ServiceLevel.Equals(other.ServiceLevel)
) &&
(
this.CreatedBy == other.CreatedBy ||
this.CreatedBy != null &&
this.CreatedBy.Equals(other.CreatedBy)
) &&
(
this.WorksheetName == other.WorksheetName ||
this.WorksheetName != null &&
this.WorksheetName.Equals(other.WorksheetName)
) &&
(
this.Carrier == other.Carrier ||
this.Carrier != null &&
this.Carrier.Equals(other.Carrier)
) &&
(
this.OnTheDock == other.OnTheDock ||
this.OnTheDock != null &&
this.OnTheDock.Equals(other.OnTheDock)
) &&
(
this.AutoCommit == other.AutoCommit ||
this.AutoCommit != null &&
this.AutoCommit.Equals(other.AutoCommit)
) &&
(
this.LineItems == other.LineItems ||
this.LineItems != null &&
this.LineItems.SequenceEqual(other.LineItems)
) &&
(
this.Notes == other.Notes ||
this.Notes != null &&
this.Notes.Equals(other.Notes)
) &&
(
this.WorkBatchId == other.WorkBatchId ||
this.WorkBatchId != null &&
this.WorkBatchId.Equals(other.WorkBatchId)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.PoNoId != null)
hash = hash * 59 + this.PoNoId.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.VendorId != null)
hash = hash * 59 + this.VendorId.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.ServiceLevel != null)
hash = hash * 59 + this.ServiceLevel.GetHashCode();
if (this.CreatedBy != null)
hash = hash * 59 + this.CreatedBy.GetHashCode();
if (this.WorksheetName != null)
hash = hash * 59 + this.WorksheetName.GetHashCode();
if (this.Carrier != null)
hash = hash * 59 + this.Carrier.GetHashCode();
if (this.OnTheDock != null)
hash = hash * 59 + this.OnTheDock.GetHashCode();
if (this.AutoCommit != null)
hash = hash * 59 + this.AutoCommit.GetHashCode();
if (this.LineItems != null)
hash = hash * 59 + this.LineItems.GetHashCode();
if (this.Notes != null)
hash = hash * 59 + this.Notes.GetHashCode();
if (this.WorkBatchId != null)
hash = hash * 59 + this.WorkBatchId.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
return hash;
}
}
}
}
| |
// 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.IO;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class MetadataLoadContextTests
{
[Fact]
public static void NoResolver()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
{
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
Assert.Throws<FileNotFoundException>(() => t.BaseType);
}
}
[Fact]
public static void ResolverMissingCore()
{
var resolver = new ResolverReturnsNull();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver, "EmptyCore"))
{
Assert.Same(lc, resolver.Context);
Assert.Equal(1, resolver.CallCount);
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
Assert.Throws<FileNotFoundException>(() => t.BaseType);
Assert.Same(lc, resolver.Context);
Assert.Equal(resolver.AssemblyName.Name, "Foo");
Assert.Equal(2, resolver.CallCount);
}
}
[Fact]
public static void ResolverReturnsSomething()
{
var resolver = new ResolverReturnsSomething();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver))
{
Assert.Same(lc, resolver.Context);
Assert.Equal(1, resolver.CallCount);
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
Type bt = t.BaseType;
Assert.Same(lc, resolver.Context);
Assert.Equal(resolver.AssemblyName.Name, "Foo");
Assert.Equal(2, resolver.CallCount);
Assembly a = bt.Assembly;
Assert.Equal(a, resolver.Assembly);
}
}
[Fact]
public static void ResolverThrows()
{
var resolver = new ResolverThrows();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver, "EmptyCore"))
{
Assert.Null(resolver.Context);
Assert.Equal(0, resolver.CallCount);
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t = derived.GetType("Derived1", throwOnError: true);
TargetParameterCountException e = Assert.Throws<TargetParameterCountException>(() => t.BaseType);
Assert.Same(lc, resolver.Context);
Assert.Equal(1, resolver.CallCount);
Assert.Equal("Hi!", e.Message);
}
}
[Fact]
public static void ResolverNoUnnecessaryCalls()
{
int resolveHandlerCallCount = 0;
Assembly resolveEventHandlerResult = null;
var resolver = new FuncMetadataAssemblyResolver(
delegate (MetadataLoadContext context, AssemblyName name)
{
if (name.Name == "Foo")
{
resolveHandlerCallCount++;
resolveEventHandlerResult = context.LoadFromByteArray(TestData.s_BaseClassesImage);
return resolveEventHandlerResult;
}
if (name.Name == "mscorlib")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
return null;
});
// In a single-threaded scenario at least, MetadataLoadContexts shouldn't ask the resolver to bind the same name twice.
using (MetadataLoadContext lc = new MetadataLoadContext(resolver))
{
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
Type t1 = derived.GetType("Derived1", throwOnError: true);
Type bt1 = t1.BaseType;
Type t2 = derived.GetType("Derived2", throwOnError: true);
Type bt2 = t2.BaseType;
Assert.Equal(1, resolveHandlerCallCount);
Assert.Equal(resolveEventHandlerResult, bt1.Assembly);
Assert.Equal(resolveEventHandlerResult, bt2.Assembly);
}
}
[Fact]
public static void ResolverMultipleCalls()
{
var resolver = new ResolverReturnsSomething();
using (MetadataLoadContext lc = new MetadataLoadContext(resolver))
{
Assembly derived = lc.LoadFromByteArray(TestData.s_DerivedClassWithVariationsOnFooImage);
int expectedCount = 2; // Includes the initial probe for mscorelib
foreach (string typeName in new string[] { "Derived1", "Derived3", "Derived4", "Derived5", "Derived6" })
{
Type t = derived.GetType(typeName, throwOnError: true);
Type bt = t.BaseType;
Assert.Equal(bt.Assembly, resolver.Assembly);
Assert.Equal(expectedCount++, resolver.CallCount);
}
}
}
[Fact]
public static void ResolverFromReferencedAssembliesUsingFullPublicKeyReference()
{
// Ecma-335 allows an assembly reference to specify a full public key rather than the token. Ensure that those references
// still hand out usable AssemblyNames to resolve handlers.
AssemblyName assemblyNameReceivedByHandler = null;
var resolver = new FuncMetadataAssemblyResolver(
delegate (MetadataLoadContext context, AssemblyName name)
{
if (name.Name == "RedirectCore")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
assemblyNameReceivedByHandler = name;
return null;
});
using (MetadataLoadContext lc = new MetadataLoadContext(resolver, "RedirectCore"))
{
Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyRefUsingFullPublicKeyImage);
Type t = a.GetType("C", throwOnError: true);
// We expect this next to call to throw since it asks the MetadataLoadContext to resolve [mscorlib]System.Object and our
// resolve handler doesn't return anything for that.
Assert.Throws<FileNotFoundException> (() => t.BaseType);
// But it did get called with a request to resolve "mscorlib" and we got the correct PKT calculated from the PK.
// Note that the original PK is not made available (which follows prior precedent with these apis.) It's not like
// anyone binds with the full PK...
Assert.NotNull(assemblyNameReceivedByHandler);
byte[] expectedPkt = "b77a5c561934e089".HexToByteArray();
byte[] actualPkt = assemblyNameReceivedByHandler.GetPublicKeyToken();
Assert.Equal<byte>(expectedPkt, actualPkt);
}
}
}
public class ResolverReturnsNull : MetadataAssemblyResolver
{
public override Assembly Resolve(System.Reflection.MetadataLoadContext context, AssemblyName assemblyName)
{
Context = context;
AssemblyName = assemblyName;
CallCount++;
if (assemblyName.Name == "EmptyCore")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
return null;
}
public AssemblyName AssemblyName { get; private set; }
public MetadataLoadContext Context { get; private set; }
public int CallCount { get; private set; }
}
public class ResolverReturnsSomething : MetadataAssemblyResolver
{
public override Assembly Resolve(System.Reflection.MetadataLoadContext context, AssemblyName assemblyName)
{
Context = context;
AssemblyName = assemblyName;
CallCount++;
Assembly = context.LoadFromByteArray(TestData.s_BaseClassesImage);
return Assembly;
}
public Assembly Assembly { get; private set; }
public AssemblyName AssemblyName { get; private set; }
public MetadataLoadContext Context { get; private set; }
public int CallCount { get; private set; }
}
public class ResolverThrows : MetadataAssemblyResolver
{
public override Assembly Resolve(System.Reflection.MetadataLoadContext context, AssemblyName assemblyName)
{
if (assemblyName.Name == "EmptyCore")
{
return context.LoadFromByteArray(TestData.s_SimpleNameOnlyImage);
}
Context = context;
AssemblyName = assemblyName;
CallCount++;
throw new TargetParameterCountException("Hi!");
}
public AssemblyName AssemblyName { get; private set; }
public MetadataLoadContext Context { get; private set; }
public int CallCount { get; private set; }
}
}
| |
// 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.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public class WinHttpRequestStreamTest
{
public WinHttpRequestStreamTest()
{
TestControl.ResetAll();
}
[Fact]
public void CanWrite_WhenCreated_ReturnsTrue()
{
Stream stream = MakeRequestStream();
bool result = stream.CanWrite;
Assert.True(result);
}
[Fact]
public void CanWrite_WhenDisposed_ReturnsFalse()
{
Stream stream = MakeRequestStream();
stream.Dispose();
bool result = stream.CanWrite;
Assert.False(result);
}
[Fact]
public void CanSeek_Always_ReturnsFalse()
{
Stream stream = MakeRequestStream();
bool result = stream.CanSeek;
Assert.False(result);
}
[Fact]
public void CanRead_Always_ReturnsFalse()
{
Stream stream = MakeRequestStream();
bool result = stream.CanRead;
Assert.False(result);
}
[Fact]
public void Length_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeRequestStream();
Assert.Throws<NotSupportedException>(() => { long result = stream.Length; });
}
[Fact]
public void Length_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { long result = stream.Length; });
}
[Fact]
public void Position_WhenCreatedDoGet_ThrowsNotSupportedException()
{
Stream stream = MakeRequestStream();
Assert.Throws<NotSupportedException>(() => { long result = stream.Position; });
}
[Fact]
public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { long result = stream.Position; });
}
[Fact]
public void Position_WhenCreatedDoSet_ThrowsNotSupportedException()
{
Stream stream = MakeRequestStream();
Assert.Throws<NotSupportedException>(() => { stream.Position = 0; });
}
[Fact]
public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Position = 0; });
}
[Fact]
public void Seek_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeRequestStream();
Assert.Throws<NotSupportedException>(() => { stream.Seek(0, SeekOrigin.Begin); });
}
[Fact]
public void Seek_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Seek(0, SeekOrigin.Begin); });
}
[Fact]
public void SetLength_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeRequestStream();
Assert.Throws<NotSupportedException>(() => { stream.SetLength(0); });
}
[Fact]
public void SetLength_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.SetLength(0); });
}
[Fact]
public void Read_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeRequestStream();
Assert.Throws<NotSupportedException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Write_BufferIsNull_ThrowsArgumentNullException()
{
Stream stream = MakeRequestStream();
Assert.Throws<ArgumentNullException>(() => { stream.Write(null, 0, 1); });
}
[Fact]
public void Write_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeRequestStream();
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Write(new byte[1], -1, 1); });
}
[Fact]
public void Write_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeRequestStream();
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Write(new byte[1], 0, -1); });
}
[Fact]
public void Write_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
Stream stream = MakeRequestStream();
Assert.Throws<ArgumentException>(() => { stream.Write(new byte[1], 0, 3); });
}
[Fact]
public void Write_OffsetPlusCountMaxValueExceedsBufferLength_ThrowsArgumentException()
{
Stream stream = MakeRequestStream();
Assert.Throws<ArgumentException>(() => { stream.Write(new byte[1], int.MaxValue, int.MaxValue); });
}
[Fact]
public void Write_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeRequestStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Write(new byte[1], 0, 1); });
}
[Fact]
public void Write_NetworkFails_ThrowsIOException()
{
Stream stream = MakeRequestStream();
TestControl.Fail.WinHttpWriteData = true;
Assert.Throws<IOException>(() => { stream.Write(new byte[1], 0, 1); });
}
[Fact]
public void Write_NoOffset_AllDataIsWritten()
{
Stream stream = MakeRequestStream();
string data = "Test Data";
byte[] buffer = Encoding.ASCII.GetBytes(data);
stream.Write(buffer, 0, buffer.Length);
byte[] serverBytes = TestServer.RequestBody;
Assert.True(ByteArraysEqual(buffer, 0, buffer.Length, serverBytes, 0, serverBytes.Length));
}
[Fact]
public void Write_UsingOffset_DataFromOffsetIsWritten()
{
Stream stream = MakeRequestStream();
string data = "Test Data";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int offset = 5;
stream.Write(buffer, offset, buffer.Length - offset);
byte[] serverBytes = TestServer.RequestBody;
Assert.True(ByteArraysEqual(buffer, offset, buffer.Length - offset, serverBytes, 0, serverBytes.Length));
}
internal Stream MakeRequestStream()
{
SafeWinHttpHandle requestHandle = new FakeSafeWinHttpHandle(true);
return new WinHttpRequestStream(requestHandle, false);
}
private bool ByteArraysEqual(byte[] array1, int offset1, int length1, byte[] array2, int offset2, int length2)
{
if (length1 != length2)
{
return false;
}
for (int i = 0; i < length1; i++)
{
if (array1[offset1 + i] != array2[offset2 + i])
{
return false;
}
}
return true;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Concurrency;
namespace Orleans.CodeGeneration
{
internal class GrainInterfaceData
{
[Serializable]
internal class RulesViolationException : ArgumentException
{
public RulesViolationException(string message, List<string> violations)
: base(message)
{
Violations = violations;
}
public List<string> Violations { get; private set; }
}
public Type Type { get; private set; }
public bool IsGeneric { get; private set; }
public CodeTypeParameterCollection GenericTypeParams { get; private set; }
public string Name { get; private set; }
public string Namespace { get; private set; }
public string TypeName { get; private set; }
public string FactoryClassBaseName { get; private set; }
public bool IsExtension
{
get { return typeof(IGrainExtension).IsAssignableFrom(Type); }
}
public string FactoryClassName
{
get { return TypeUtils.GetParameterizedTemplateName(FactoryClassBaseName, Type, language: language); }
}
public string ReferenceClassBaseName { get; set; }
public string ReferenceClassName
{
get { return TypeUtils.GetParameterizedTemplateName(ReferenceClassBaseName, Type, language: language); }
}
public string InterfaceTypeName
{
get { return TypeUtils.GetParameterizedTemplateName(Type, language: language); }
}
public string StateClassBaseName { get; internal set; }
public string InvokerClassBaseName { get; internal set; }
public string InvokerClassName
{
get { return TypeUtils.GetParameterizedTemplateName(InvokerClassBaseName, Type, language: language); }
}
public string TypeFullName
{
get { return Namespace + "." + TypeUtils.GetParameterizedTemplateName(Type, language: language); }
}
private readonly Language language;
public GrainInterfaceData(Language language)
{
this.language = language;
}
public GrainInterfaceData(Language language, Type type) : this(language)
{
if (!IsGrainInterface(type))
throw new ArgumentException(String.Format("{0} is not a grain interface", type.FullName));
List<string> violations;
bool ok = ValidateInterfaceRules(type, out violations);
if (!ok && violations != null && violations.Count > 0)
throw new RulesViolationException(string.Format("{0} does not conform to the grain interface rules.", type.FullName), violations);
Type = type;
DefineClassNames(true);
}
public static GrainInterfaceData FromGrainClass(Type grainType, Language language)
{
if (!TypeUtils.IsConcreteGrainClass(grainType) &&
!TypeUtils.IsSystemTargetClass(grainType))
{
List<string> violations = new List<string> { String.Format("{0} implements IGrain but is not a concrete Grain Class (Hint: Extend the base Grain or Grain<T> class).", grainType.FullName) };
throw new RulesViolationException("Invalid Grain class.", violations);
}
var gi = new GrainInterfaceData(language) { Type = grainType };
gi.DefineClassNames(false);
return gi;
}
public static bool IsGrainInterface(Type t)
{
if (t.IsClass)
return false;
if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension))
return false;
if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey)
|| t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey))
return false;
if (t == typeof (ISystemTarget))
return false;
return typeof (IAddressable).IsAssignableFrom(t);
}
public static bool IsAddressable(Type t)
{
return typeof(IAddressable).IsAssignableFrom(t);
}
public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true)
{
var methodInfos = new List<MethodInfo>();
GetMethodsImpl(grainType, grainType, methodInfos);
var flags = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance;
if (!bAllMethods)
flags |= BindingFlags.DeclaredOnly;
MethodInfo[] infos = grainType.GetMethods(flags);
IEqualityComparer<MethodInfo> methodComparer = new MethodInfoComparer();
foreach (var methodInfo in infos)
if (!methodInfos.Contains(methodInfo, methodComparer))
methodInfos.Add(methodInfo);
return methodInfos.ToArray();
}
public static string GetFactoryNameBase(string typeName)
{
if (typeName.Length > 1 && typeName[0] == 'I' && Char.IsUpper(typeName[1]))
typeName = typeName.Substring(1);
return TypeUtils.GetSimpleTypeName(typeName) + "Factory";
}
public static string GetParameterName(ParameterInfo info)
{
var n = info.Name;
return string.IsNullOrEmpty(n) ? "arg" + info.Position : n;
}
public static bool IsSystemTargetType(Type interfaceType)
{
return typeof (ISystemTarget).IsAssignableFrom(interfaceType);
}
public static bool IsTaskType(Type t)
{
return t == typeof (Task)
|| (t.IsGenericType && t.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.Task`1");
}
/// <summary>
/// Whether method is read-only, i.e. does not modify grain state,
/// a method marked with [ReadOnly].
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static bool IsReadOnly(MethodInfo info)
{
return info.GetCustomAttributes(typeof (ReadOnlyAttribute), true).Length > 0;
}
public static bool IsAlwaysInterleave(MethodInfo methodInfo)
{
return methodInfo.GetCustomAttributes(typeof (AlwaysInterleaveAttribute), true).Length > 0;
}
public static bool IsUnordered(MethodInfo methodInfo)
{
return methodInfo.DeclaringType.GetCustomAttributes(typeof (UnorderedAttribute), true).Length > 0 ||
(methodInfo.DeclaringType.GetInterfaces().Any(i => i.GetCustomAttributes(typeof (UnorderedAttribute), true)
.Length > 0 && methodInfo.DeclaringType.GetInterfaceMap(i)
.TargetMethods.Contains(methodInfo))) || IsStatelessWorker(methodInfo);
}
public static bool IsStatelessWorker(Type grainType)
{
return grainType.GetCustomAttributes(typeof (StatelessWorkerAttribute), true).Length > 0 ||
grainType.GetInterfaces()
.Any(i => i.GetCustomAttributes(typeof (StatelessWorkerAttribute), true).Length > 0);
}
public static bool IsStatelessWorker(MethodInfo methodInfo)
{
return methodInfo.DeclaringType.GetCustomAttributes(typeof (StatelessWorkerAttribute), true).Length > 0 ||
(methodInfo.DeclaringType.GetInterfaces().Any(i => i.GetCustomAttributes(
typeof (StatelessWorkerAttribute), true).Length > 0 &&
methodInfo.DeclaringType.GetInterfaceMap(i).TargetMethods.Contains(methodInfo)));
}
public static Dictionary<int, Type> GetRemoteInterfaces(Type type, bool checkIsGrainInterface = true)
{
var dict = new Dictionary<int, Type>();
if (IsGrainInterface(type))
dict.Add(ComputeInterfaceId(type), type);
Type[] interfaces = type.GetInterfaces();
foreach (Type interfaceType in interfaces.Where(i => !checkIsGrainInterface || IsGrainInterface(i)))
dict.Add(ComputeInterfaceId(interfaceType), interfaceType);
return dict;
}
public static int ComputeMethodId(MethodInfo methodInfo)
{
var strMethodId = new StringBuilder(methodInfo.Name + "(");
ParameterInfo[] parameters = methodInfo.GetParameters();
bool bFirstTime = true;
foreach (ParameterInfo info in parameters)
{
if (!bFirstTime)
strMethodId.Append(",");
strMethodId.Append(info.ParameterType.Name);
if (info.ParameterType.IsGenericType)
{
Type[] args = info.ParameterType.GetGenericArguments();
foreach (Type arg in args)
strMethodId.Append(arg.Name);
}
bFirstTime = false;
}
strMethodId.Append(")");
return Utils.CalculateIdHash(strMethodId.ToString());
}
public bool IsSystemTarget
{
get { return IsSystemTargetType(Type); }
}
public static int GetGrainInterfaceId(Type grainInterface)
{
return GetTypeCode(grainInterface);
}
public static bool IsTaskBasedInterface(Type type)
{
var methods = type.GetMethods();
// An interface is task-based if it has at least one method that returns a Task or at least one parent that's task-based.
return methods.Any(m => IsTaskType(m.ReturnType)) || type.GetInterfaces().Any(IsTaskBasedInterface);
}
public static bool IsGrainType(Type grainType)
{
return typeof (IGrain).IsAssignableFrom(grainType);
}
public static int ComputeInterfaceId(Type interfaceType)
{
var ifaceName = TypeUtils.GetFullName(interfaceType);
var ifaceId = Utils.CalculateIdHash(ifaceName);
return ifaceId;
}
public static int GetGrainClassTypeCode(Type grainClass)
{
return GetTypeCode(grainClass);
}
private void DefineClassNames(bool client)
{
var typeNameBase = TypeUtils.GetSimpleTypeName(Type, t => false, language);
if (Type.IsInterface && typeNameBase.Length > 1 && typeNameBase[0] == 'I' && Char.IsUpper(typeNameBase[1]))
typeNameBase = typeNameBase.Substring(1);
Namespace = Type.Namespace;
IsGeneric = Type.IsGenericType;
if (IsGeneric)
{
Name = TypeUtils.GetParameterizedTemplateName(Type, language: language);
GenericTypeParams = TypeUtils.GenericTypeParameters(Type);
}
else
{
Name = Type.Name;
}
TypeName = client ? InterfaceTypeName : TypeUtils.GetParameterizedTemplateName(Type, language:language);
FactoryClassBaseName = GetFactoryNameBase(typeNameBase);
InvokerClassBaseName = typeNameBase + "MethodInvoker";
StateClassBaseName = typeNameBase + "State";
ReferenceClassBaseName = typeNameBase + "Reference";
}
private static bool ValidateInterfaceRules(Type type, out List<string> violations)
{
violations = new List<string>();
bool success = ValidateInterfaceMethods(type, violations);
return success && ValidateInterfaceProperties(type, violations);
}
private static bool ValidateInterfaceMethods(Type type, List<string> violations)
{
bool success = true;
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
if (method.IsSpecialName)
continue;
if (IsPureObserverInterface(method.DeclaringType))
{
if (method.ReturnType != typeof (void))
{
success = false;
violations.Add(String.Format("Method {0}.{1} must return void because it is defined within an observer interface.",
type.FullName, method.Name));
}
}
else if (!IsTaskType(method.ReturnType))
{
success = false;
violations.Add(String.Format("Method {0}.{1} must return Task or Task<T> because it is defined within a grain interface.",
type.FullName, method.Name));
}
ParameterInfo[] parameters = method.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
if (parameter.IsOut)
{
success = false;
violations.Add(String.Format("Argument {0} of method {1}.{2} is an output parameter. Output parameters are not allowed in grain interfaces.",
GetParameterName(parameter), type.FullName, method.Name));
}
if (parameter.ParameterType.IsByRef)
{
success = false;
violations.Add(String.Format("Argument {0} of method {1}.{2} is an a reference parameter. Reference parameters are not allowed.",
GetParameterName(parameter), type.FullName, method.Name));
}
}
}
return success;
}
private static bool ValidateInterfaceProperties(Type type, List<string> violations)
{
bool success = true;
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
success = false;
violations.Add(String.Format("Properties are not allowed on grain interfaces: {0}.{1}.",
type.FullName, property.Name));
}
return success;
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
private static bool IsPureObserverInterface(Type t)
{
if (!typeof (IGrainObserver).IsAssignableFrom(t))
return false;
if (t == typeof (IGrainObserver))
return true;
if (t == typeof (IAddressable))
return false;
bool pure = false;
foreach (Type iface in t.GetInterfaces())
{
if (iface == typeof (IAddressable)) // skip IAddressable that will be in the list regardless
continue;
if (iface == typeof (IGrainExtension))
// Skip IGrainExtension, it's just a marker that can go on observer or grain interfaces
continue;
pure = IsPureObserverInterface(iface);
if (!pure)
return false;
}
return pure;
}
private class MethodInfoComparer : IEqualityComparer<MethodInfo>
{
#region IEqualityComparer<InterfaceInfo> Members
public bool Equals(MethodInfo x, MethodInfo y)
{
var xString = new StringBuilder(x.Name);
var yString = new StringBuilder(y.Name);
ParameterInfo[] parms = x.GetParameters();
foreach (ParameterInfo info in parms)
{
xString.Append(info.ParameterType.Name);
if (info.ParameterType.IsGenericType)
{
Type[] args = info.ParameterType.GetGenericArguments();
foreach (Type arg in args)
xString.Append(arg.Name);
}
}
parms = y.GetParameters();
foreach (ParameterInfo info in parms)
{
yString.Append(info.ParameterType.Name);
if (info.ParameterType.IsGenericType)
{
Type[] args = info.ParameterType.GetGenericArguments();
foreach (Type arg in args)
yString.Append(arg.Name);
}
}
return String.CompareOrdinal(xString.ToString(), yString.ToString()) == 0;
}
public int GetHashCode(MethodInfo obj)
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
/// Recurses through interface graph accumulating methods
/// </summary>
/// <param name="grainType">Grain type</param>
/// <param name="serviceType">Service interface type</param>
/// <param name="methodInfos">Accumulated </param>
private static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos)
{
Type[] iTypes = GetRemoteInterfaces(serviceType, false).Values.ToArray();
IEqualityComparer<MethodInfo> methodComparer = new MethodInfoComparer();
foreach (Type iType in iTypes)
{
var mapping = new InterfaceMapping();
if (grainType.IsClass)
mapping = grainType.GetInterfaceMap(iType);
if (grainType.IsInterface || mapping.TargetType == grainType)
{
foreach (var methodInfo in iType.GetMethods())
{
if (grainType.IsClass)
{
var mi = methodInfo;
var match = mapping.TargetMethods.Any(info => methodComparer.Equals(mi, info) &&
info.DeclaringType == grainType);
if (match)
if (!methodInfos.Contains(mi, methodComparer))
methodInfos.Add(mi);
}
else if (!methodInfos.Contains(methodInfo, methodComparer))
{
methodInfos.Add(methodInfo);
}
}
}
}
}
private static int GetTypeCode(Type grainInterfaceOrClass)
{
var attrs = grainInterfaceOrClass.GetCustomAttributes(typeof(TypeCodeOverrideAttribute), false);
var attr = attrs.Length > 0 ? attrs[0] as TypeCodeOverrideAttribute : null;
var fullName = TypeUtils.GetTemplatedName(
TypeUtils.GetFullName(grainInterfaceOrClass),
grainInterfaceOrClass,
grainInterfaceOrClass.GetGenericArguments(),
t => false);
var typeCode = attr != null && attr.TypeCode > 0 ? attr.TypeCode : Utils.CalculateIdHash(fullName);
return typeCode;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataFormats.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using System.Text;
using System.Configuration.Assemblies;
using System.Diagnostics;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Globalization;
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats"]/*' />
/// <devdoc>
/// <para>Translates
/// between Win Forms text-based
/// <see cref='System.Windows.Forms.Clipboard'/> formats and <see langword='Microsoft.Win32'/> 32-bit signed integer-based
/// clipboard formats. Provides <see langword='static '/> methods to create new <see cref='System.Windows.Forms.Clipboard'/> formats and add
/// them to the Windows Registry.</para>
/// </devdoc>
public class DataFormats {
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Text"]/*' />
/// <devdoc>
/// <para>Specifies the standard ANSI text format. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string Text = "Text";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.UnicodeText"]/*' />
/// <devdoc>
/// <para>Specifies the standard Windows Unicode text format. This
/// <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string UnicodeText = "UnicodeText";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Dib"]/*' />
/// <devdoc>
/// <para>Specifies the Windows Device Independent Bitmap (DIB)
/// format. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string Dib = "DeviceIndependentBitmap";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Bitmap"]/*' />
/// <devdoc>
/// <para>Specifies a Windows bitmap format. This <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string Bitmap = "Bitmap";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.EnhancedMetafile"]/*' />
/// <devdoc>
/// <para>Specifies the Windows enhanced metafile format. This
/// <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string EnhancedMetafile = "EnhancedMetafile";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.MetafilePict"]/*' />
/// <devdoc>
/// <para>Specifies the Windows metafile format, which Win Forms
/// does not directly use. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] // Would be a breaking change to rename this
public static readonly string MetafilePict = "MetaFilePict";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.SymbolicLink"]/*' />
/// <devdoc>
/// <para>Specifies the Windows symbolic link format, which Win
/// Forms does not directly use. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string SymbolicLink = "SymbolicLink";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Dif"]/*' />
/// <devdoc>
/// <para>Specifies the Windows data interchange format, which Win
/// Forms does not directly use. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string Dif = "DataInterchangeFormat";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Tiff"]/*' />
/// <devdoc>
/// <para>Specifies the Tagged Image File Format (TIFF), which Win
/// Forms does not directly use. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string Tiff = "TaggedImageFileFormat";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.OemText"]/*' />
/// <devdoc>
/// <para>Specifies the standard Windows original equipment
/// manufacturer (OEM) text format. This <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string OemText = "OEMText";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Palette"]/*' />
/// <devdoc>
/// <para>Specifies the Windows palette format. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string Palette = "Palette";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.PenData"]/*' />
/// <devdoc>
/// <para>Specifies the Windows pen data format, which consists of
/// pen strokes for handwriting software; Win Forms does not use this format. This
/// <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string PenData = "PenData";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Riff"]/*' />
/// <devdoc>
/// <para>Specifies the Resource Interchange File Format (RIFF)
/// audio format, which Win Forms does not directly use. This <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string Riff = "RiffAudio";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.WaveAudio"]/*' />
/// <devdoc>
/// <para>Specifies the wave audio format, which Win Forms does not
/// directly use. This <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string WaveAudio = "WaveAudio";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.FileDrop"]/*' />
/// <devdoc>
/// <para>Specifies the Windows file drop format, which Win Forms
/// does not directly use. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string FileDrop = "FileDrop";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Locale"]/*' />
/// <devdoc>
/// <para>Specifies the Windows culture format, which Win Forms does
/// not directly use. This <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string Locale = "Locale";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Html"]/*' />
/// <devdoc>
/// <para>Specifies text consisting of HTML data. This
/// <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string Html = "HTML Format";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Rtf"]/*' />
/// <devdoc>
/// <para>Specifies text consisting of Rich Text Format (RTF) data. This
/// <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string Rtf = "Rich Text Format";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.CommaSeparatedValue"]/*' />
/// <devdoc>
/// <para>Specifies a comma-separated value (CSV) format, which is a
/// common interchange format used by spreadsheets. This format is not used directly
/// by Win Forms. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
public static readonly string CommaSeparatedValue = "Csv";
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.StringFormat"]/*' />
/// <devdoc>
/// <para>Specifies the Win Forms string class format, which Win
/// Forms uses to store string objects. This <see langword='static '/>
/// field is read-only.</para>
/// </devdoc>
// I'm sure upper case "String" is a reserved word in some language that matters
public static readonly string StringFormat = typeof(string).FullName;
//C#r: public static readonly String CF_STRINGCLASS = typeof(String).Name;
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Serializable"]/*' />
/// <devdoc>
/// <para>Specifies a format that encapsulates any type of Win Forms
/// object. This <see langword='static '/> field is read-only.</para>
/// </devdoc>
public static readonly string Serializable = Application.WindowsFormsVersion + "PersistentObject";
private static Format[] formatList;
private static int formatCount = 0;
private static object internalSyncObject = new object();
// not creatable...
//
private DataFormats() {
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.GetFormat"]/*' />
/// <devdoc>
/// <para>Gets a <see cref='System.Windows.Forms.DataFormats.Format'/> with the Windows Clipboard numeric ID and name for the specified format.</para>
/// </devdoc>
public static Format GetFormat(string format) {
lock(internalSyncObject) {
EnsurePredefined();
// It is much faster to do a case sensitive search here. So do
// the case sensitive compare first, then the expensive one.
//
for (int n = 0; n < formatCount; n++) {
if (formatList[n].Name.Equals(format))
return formatList[n];
}
for (int n = 0; n < formatCount; n++) {
if (String.Equals(formatList[n].Name, format, StringComparison.OrdinalIgnoreCase))
return formatList[n];
}
// need to add this format string
//
int formatId = SafeNativeMethods.RegisterClipboardFormat(format);
if (0 == formatId) {
throw new Win32Exception(Marshal.GetLastWin32Error(), SR.GetString(SR.RegisterCFFailed));
}
EnsureFormatSpace(1);
formatList[formatCount] = new Format(format, formatId);
return formatList[formatCount++];
}
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.GetFormat1"]/*' />
/// <devdoc>
/// <para>Gets a <see cref='System.Windows.Forms.DataFormats.Format'/> with the Windows Clipboard numeric
/// ID and name for the specified ID.</para>
/// </devdoc>
public static Format GetFormat(int id) {
// Win32 uses an unsigned 16 bit type as a format ID, thus stripping off the leading bits.
// Registered format IDs are in the range 0xC000 through 0xFFFF, thus it's important
// to represent format as an unsigned type.
return InternalGetFormat( null, (ushort)(id & 0xFFFF));
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.InternalGetFormat"]/*' />
/// <devdoc>
/// Allows a the new format name to be specified if the requested format is not
/// in the list
/// </devdoc>
/// <internalonly/>
private static Format InternalGetFormat(string strName, ushort id) {
lock(internalSyncObject) {
EnsurePredefined();
for (int n = 0; n < formatCount; n++) {
if (formatList[n].Id == id)
return formatList[n];
}
StringBuilder s = new StringBuilder(128);
// This can happen if windows adds a standard format that we don't know about,
// so we should play it safe.
//
if (0 == SafeNativeMethods.GetClipboardFormatName(id, s, s.Capacity)) {
s.Length = 0;
if (strName == null) {
s.Append( "Format" ).Append( id );
}
else {
s.Append( strName );
}
}
EnsureFormatSpace(1);
formatList[formatCount] = new Format(s.ToString(), id);
return formatList[formatCount++];
}
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.EnsureFormatSpace"]/*' />
/// <devdoc>
/// ensures that we have enough room in our format list
/// </devdoc>
/// <internalonly/>
private static void EnsureFormatSpace(int size) {
if (null == formatList || formatList.Length <= formatCount + size) {
int newSize = formatCount + 20;
Format[] newList = new Format[newSize];
for (int n = 0; n < formatCount; n++) {
newList[n] = formatList[n];
}
formatList = newList;
}
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.EnsurePredefined"]/*' />
/// <devdoc>
/// ensures that the Win32 predefined formats are setup in our format list. This
/// is called anytime we need to search the list
/// </devdoc>
/// <internalonly/>
private static void EnsurePredefined() {
if (0 == formatCount) {
/* not used
int standardText;
// We must handle text differently for Win 95 and NT. We should put
// UnicodeText on the clipboard for NT, and Text for Win 95.
// So, we figure it out here theh first time someone asks for format info
//
if (1 == Marshal.SystemDefaultCharSize) {
standardText = NativeMethods.CF_TEXT;
}
else {
standardText = NativeMethods.CF_UNICODETEXT;
}
*/
formatList = new Format [] {
// Text name Win32 format ID Data stored as a Win32 handle?
new Format(UnicodeText, NativeMethods.CF_UNICODETEXT),
new Format(Text, NativeMethods.CF_TEXT),
new Format(Bitmap, NativeMethods.CF_BITMAP),
new Format(MetafilePict, NativeMethods.CF_METAFILEPICT),
new Format(EnhancedMetafile, NativeMethods.CF_ENHMETAFILE),
new Format(Dif, NativeMethods.CF_DIF),
new Format(Tiff, NativeMethods.CF_TIFF),
new Format(OemText, NativeMethods.CF_OEMTEXT),
new Format(Dib, NativeMethods.CF_DIB),
new Format(Palette, NativeMethods.CF_PALETTE),
new Format(PenData, NativeMethods.CF_PENDATA),
new Format(Riff, NativeMethods.CF_RIFF),
new Format(WaveAudio, NativeMethods.CF_WAVE),
new Format(SymbolicLink, NativeMethods.CF_SYLK),
new Format(FileDrop, NativeMethods.CF_HDROP),
new Format(Locale, NativeMethods.CF_LOCALE)
};
formatCount = formatList.Length;
}
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Format"]/*' />
/// <devdoc>
/// <para>Represents a format type.</para>
/// </devdoc>
public class Format {
readonly string name;
readonly int id;
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Format.Name"]/*' />
/// <devdoc>
/// <para>
/// Specifies the
/// name of this format. This field is read-only.
///
/// </para>
/// </devdoc>
public string Name {
get {
return name;
}
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Format.Id"]/*' />
/// <devdoc>
/// <para>
/// Specifies the ID
/// number for this format. This field is read-only.
/// </para>
/// </devdoc>
public int Id {
get {
return id;
}
}
/// <include file='doc\DataFormats.uex' path='docs/doc[@for="DataFormats.Format.Format"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Windows.Forms.DataFormats.Format'/> class and specifies whether a
/// <see langword='Win32 '/>
/// handle is expected with this format.</para>
/// </devdoc>
public Format(string name, int id) {
this.name = name;
this.id = id;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
using static MicrosoftNetCoreAnalyzersResources;
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotUseWeakKDFInsufficientIterationCount : DiagnosticAnalyzer
{
internal static readonly DiagnosticDescriptor DefinitelyUseWeakKDFInsufficientIterationCountRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5387",
nameof(DefinitelyUseWeakKDFInsufficientIterationCount),
nameof(DefinitelyUseWeakKDFInsufficientIterationCountMessage),
RuleLevel.Disabled,
isPortedFxCopRule: false,
isDataflowRule: true,
isReportedAtCompilationEnd: true,
descriptionResourceStringName: nameof(DoNotUseWeakKDFInsufficientIterationCountDescription));
internal static readonly DiagnosticDescriptor MaybeUseWeakKDFInsufficientIterationCountRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5388",
nameof(MaybeUseWeakKDFInsufficientIterationCount),
nameof(MaybeUseWeakKDFInsufficientIterationCountMessage),
RuleLevel.Disabled,
isPortedFxCopRule: false,
isDataflowRule: true,
isReportedAtCompilationEnd: true,
descriptionResourceStringName: nameof(DoNotUseWeakKDFInsufficientIterationCountDescription));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
DefinitelyUseWeakKDFInsufficientIterationCountRule,
MaybeUseWeakKDFInsufficientIterationCountRule);
private const int DefaultIterationCount = 1000;
private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue)
{
return propertySetAbstractValue[0] switch
{
PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged,
PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged,
_ => HazardousUsageEvaluationResult.Unflagged,
};
}
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
HazardousUsageEvaluatorCollection hazardousUsageEvaluators = new HazardousUsageEvaluatorCollection(
new HazardousUsageEvaluator("GetBytes", HazardousUsageCallback));
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
if (!compilationStartAnalysisContext.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes,
out var rfc2898DeriveBytesTypeSymbol) ||
compilationStartAnalysisContext.Compilation.SyntaxTrees.FirstOrDefault() is not SyntaxTree tree)
{
return;
}
var sufficientIterationCount = compilationStartAnalysisContext.Options.GetUnsignedIntegralOptionValue(
optionName: EditorConfigOptionNames.SufficientIterationCountForWeakKDFAlgorithm,
rule: DefinitelyUseWeakKDFInsufficientIterationCountRule,
tree,
compilationStartAnalysisContext.Compilation,
defaultValue: 100000);
var constructorMapper = new ConstructorMapper(
(IMethodSymbol constructorMethod, IReadOnlyList<ValueContentAbstractValue> argumentValueContentAbstractValues,
IReadOnlyList<PointsToAbstractValue> argumentPointsToAbstractValues) =>
{
var kind = DefaultIterationCount >= sufficientIterationCount ? PropertySetAbstractValueKind.Unflagged : PropertySetAbstractValueKind.Flagged;
if (constructorMethod.Parameters.Length >= 3)
{
if (constructorMethod.Parameters[2].Name == "iterations" &&
constructorMethod.Parameters[2].Type.SpecialType == SpecialType.System_Int32)
{
kind = PropertySetCallbacks.EvaluateLiteralValues(argumentValueContentAbstractValues[2], o => Convert.ToInt32(o, CultureInfo.InvariantCulture) < sufficientIterationCount);
}
}
return PropertySetAbstractValue.GetInstance(kind);
});
var propertyMappers = new PropertyMapperCollection(
new PropertyMapper(
"IterationCount",
(ValueContentAbstractValue valueContentAbstractValue) =>
{
return PropertySetCallbacks.EvaluateLiteralValues(valueContentAbstractValue, o => Convert.ToInt32(o, CultureInfo.InvariantCulture) < sufficientIterationCount);
}));
var rootOperationsNeedingAnalysis = PooledHashSet<(IOperation, ISymbol)>.GetInstance();
compilationStartAnalysisContext.RegisterOperationBlockStartAction(
(OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) =>
{
// TODO: Handle case when exactly one of the below rules is configured to skip analysis.
if (operationBlockStartAnalysisContext.Options.IsConfiguredToSkipAnalysis(DefinitelyUseWeakKDFInsufficientIterationCountRule,
operationBlockStartAnalysisContext.OwningSymbol, operationBlockStartAnalysisContext.Compilation) &&
operationBlockStartAnalysisContext.Options.IsConfiguredToSkipAnalysis(MaybeUseWeakKDFInsufficientIterationCountRule,
operationBlockStartAnalysisContext.OwningSymbol, operationBlockStartAnalysisContext.Compilation))
{
return;
}
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation;
if (rfc2898DeriveBytesTypeSymbol.Equals(invocationOperation.Instance?.Type) &&
invocationOperation.TargetMethod.Name == "GetBytes")
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((invocationOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Invocation);
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var argumentOperation = (IArgumentOperation)operationAnalysisContext.Operation;
if (rfc2898DeriveBytesTypeSymbol.Equals(argumentOperation.Parameter.Type))
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((argumentOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Argument);
});
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
PooledDictionary<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult>? allResults = null;
try
{
lock (rootOperationsNeedingAnalysis)
{
if (!rootOperationsNeedingAnalysis.Any())
{
return;
}
allResults = PropertySetAnalysis.BatchGetOrComputeHazardousUsages(
compilationAnalysisContext.Compilation,
rootOperationsNeedingAnalysis,
compilationAnalysisContext.Options,
WellKnownTypeNames.SystemSecurityCryptographyRfc2898DeriveBytes,
constructorMapper,
propertyMappers,
hazardousUsageEvaluators,
InterproceduralAnalysisConfiguration.Create(
compilationAnalysisContext.Options,
SupportedDiagnostics,
rootOperationsNeedingAnalysis.First().Item1,
compilationStartAnalysisContext.Compilation,
defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive));
}
if (allResults == null)
{
return;
}
foreach (KeyValuePair<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult> kvp
in allResults)
{
DiagnosticDescriptor descriptor;
switch (kvp.Value)
{
case HazardousUsageEvaluationResult.Flagged:
descriptor = DefinitelyUseWeakKDFInsufficientIterationCountRule;
break;
case HazardousUsageEvaluationResult.MaybeFlagged:
descriptor = MaybeUseWeakKDFInsufficientIterationCountRule;
break;
default:
Debug.Fail($"Unhandled result value {kvp.Value}");
continue;
}
compilationAnalysisContext.ReportDiagnostic(
Diagnostic.Create(
descriptor,
kvp.Key.Location,
sufficientIterationCount));
}
}
finally
{
rootOperationsNeedingAnalysis.Free(compilationAnalysisContext.CancellationToken);
allResults?.Free(compilationAnalysisContext.CancellationToken);
}
});
});
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
using DockSample.Customization;
using Lextm.SharpSnmpLib;
using WeifenLuo.WinFormsUI.Docking;
namespace DockSample
{
public partial class MainForm : Form
{
private bool m_bSaveLayout = true;
private DeserializeDockContent m_deserializeDockContent;
private DummySolutionExplorer m_solutionExplorer;
private DummyPropertyWindow m_propertyWindow;
private DummyToolbox m_toolbox;
private DummyOutputWindow m_outputWindow;
private DummyTaskList m_taskList;
public MainForm()
{
InitializeComponent();
CreateStandardControls();
showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes);
RightToLeftLayout = showRightToLeft.Checked;
m_solutionExplorer.RightToLeftLayout = RightToLeftLayout;
m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
vS2012ToolStripExtender1.DefaultRenderer = _system;
vS2012ToolStripExtender1.VS2012Renderer = _custom;
}
#region Methods
private IDockContent FindDocument(string text)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
if (form.Text == text)
return form as IDockContent;
return null;
}
else
{
foreach (IDockContent content in dockPanel.Documents)
if (content.DockHandler.TabText == text)
return content;
return null;
}
}
private DummyDoc CreateNewDocument()
{
DummyDoc dummyDoc = new DummyDoc();
int count = 1;
//string text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
string text = "Document" + count.ToString();
while (FindDocument(text) != null)
{
count++;
//text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
text = "Document" + count.ToString();
}
dummyDoc.Text = text;
return dummyDoc;
}
private DummyDoc CreateNewDocument(string text)
{
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = text;
return dummyDoc;
}
private void CloseAllDocuments()
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
foreach (Form form in MdiChildren)
form.Close();
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
document.DockHandler.Close();
}
}
}
private IDockContent GetContentFromPersistString(string persistString)
{
if (persistString == typeof(DummySolutionExplorer).ToString())
return m_solutionExplorer;
else if (persistString == typeof(DummyPropertyWindow).ToString())
return m_propertyWindow;
else if (persistString == typeof(DummyToolbox).ToString())
return m_toolbox;
else if (persistString == typeof(DummyOutputWindow).ToString())
return m_outputWindow;
else if (persistString == typeof(DummyTaskList).ToString())
return m_taskList;
else
{
// DummyDoc overrides GetPersistString to add extra information into persistString.
// Any DockContent may override this value to add any needed information for deserialization.
string[] parsedStrings = persistString.Split(new char[] { ',' });
if (parsedStrings.Length != 3)
return null;
if (parsedStrings[0] != typeof(DummyDoc).ToString())
return null;
DummyDoc dummyDoc = new DummyDoc();
if (parsedStrings[1] != string.Empty)
dummyDoc.FileName = parsedStrings[1];
if (parsedStrings[2] != string.Empty)
dummyDoc.Text = parsedStrings[2];
return dummyDoc;
}
}
private void CloseAllContents()
{
// we don't want to create another instance of tool window, set DockPanel to null
m_solutionExplorer.DockPanel = null;
m_propertyWindow.DockPanel = null;
m_toolbox.DockPanel = null;
m_outputWindow.DockPanel = null;
m_taskList.DockPanel = null;
// Close all other document windows
CloseAllDocuments();
}
private readonly ToolStripRenderer _system = new ToolStripProfessionalRenderer();
private readonly ToolStripRenderer _custom = new VS2012ToolStripRenderer();
private void SetSchema(object sender, System.EventArgs e)
{
CloseAllContents();
if (sender == menuItemSchemaVS2005)
{
dockPanel.Theme = vS2005Theme1;
EnableVS2012Renderer(false);
}
else if (sender == menuItemSchemaVS2003)
{
dockPanel.Theme = vS2003Theme1;
EnableVS2012Renderer(false);
}
else if (sender == menuItemSchemaVS2012Light)
{
dockPanel.Theme = vS2012LightTheme1;
EnableVS2012Renderer(true);
}
menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005);
menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003);
menuItemSchemaVS2012Light.Checked = (sender == menuItemSchemaVS2012Light);
}
private void EnableVS2012Renderer(bool enable)
{
vS2012ToolStripExtender1.SetEnableVS2012Style(this.mainMenu, enable);
vS2012ToolStripExtender1.SetEnableVS2012Style(this.toolBar, enable);
}
private void SetDocumentStyle(object sender, System.EventArgs e)
{
DocumentStyle oldStyle = dockPanel.DocumentStyle;
DocumentStyle newStyle;
if (sender == menuItemDockingMdi)
newStyle = DocumentStyle.DockingMdi;
else if (sender == menuItemDockingWindow)
newStyle = DocumentStyle.DockingWindow;
else if (sender == menuItemDockingSdi)
newStyle = DocumentStyle.DockingSdi;
else
newStyle = DocumentStyle.SystemMdi;
if (oldStyle == newStyle)
return;
if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi)
CloseAllDocuments();
dockPanel.DocumentStyle = newStyle;
menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi);
menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow);
menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi);
menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi);
menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
}
private AutoHideStripSkin _autoHideStripSkin;
private DockPaneStripSkin _dockPaneStripSkin;
private void SetDockPanelSkinOptions(bool isChecked)
{
if (isChecked)
{
// All of these options may be set in the designer.
// This is not a complete list of possible options available in the skin.
AutoHideStripSkin autoHideSkin = new AutoHideStripSkin();
autoHideSkin.DockStripGradient.StartColor = Color.AliceBlue;
autoHideSkin.DockStripGradient.EndColor = Color.Blue;
autoHideSkin.DockStripGradient.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
autoHideSkin.TabGradient.StartColor = SystemColors.Control;
autoHideSkin.TabGradient.EndColor = SystemColors.ControlDark;
autoHideSkin.TabGradient.TextColor = SystemColors.ControlText;
autoHideSkin.TextFont = new Font("Showcard Gothic", 10);
_autoHideStripSkin = dockPanel.Skin.AutoHideStripSkin;
dockPanel.Skin.AutoHideStripSkin = autoHideSkin;
DockPaneStripSkin dockPaneSkin = new DockPaneStripSkin();
dockPaneSkin.DocumentGradient.DockStripGradient.StartColor = Color.Red;
dockPaneSkin.DocumentGradient.DockStripGradient.EndColor = Color.Pink;
dockPaneSkin.DocumentGradient.ActiveTabGradient.StartColor = Color.Green;
dockPaneSkin.DocumentGradient.ActiveTabGradient.EndColor = Color.Green;
dockPaneSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White;
dockPaneSkin.DocumentGradient.InactiveTabGradient.StartColor = Color.Gray;
dockPaneSkin.DocumentGradient.InactiveTabGradient.EndColor = Color.Gray;
dockPaneSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.Black;
dockPaneSkin.TextFont = new Font("SketchFlow Print", 10);
_dockPaneStripSkin = dockPanel.Skin.DockPaneStripSkin;
dockPanel.Skin.DockPaneStripSkin = dockPaneSkin;
}
else
{
if (_autoHideStripSkin != null)
{
dockPanel.Skin.AutoHideStripSkin = _autoHideStripSkin;
}
if (_dockPaneStripSkin != null)
{
dockPanel.Skin.DockPaneStripSkin = _dockPaneStripSkin;
}
}
menuItemLayoutByXml_Click(menuItemLayoutByXml, EventArgs.Empty);
}
#endregion
#region Event Handlers
private void menuItemExit_Click(object sender, System.EventArgs e)
{
Close();
}
private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e)
{
m_solutionExplorer.Show(dockPanel);
}
private void menuItemPropertyWindow_Click(object sender, System.EventArgs e)
{
m_propertyWindow.Show(dockPanel);
}
private void menuItemToolbox_Click(object sender, System.EventArgs e)
{
m_toolbox.Show(dockPanel);
}
private void menuItemOutputWindow_Click(object sender, System.EventArgs e)
{
m_outputWindow.Show(dockPanel);
}
private void menuItemTaskList_Click(object sender, System.EventArgs e)
{
m_taskList.Show(dockPanel);
}
private void menuItemAbout_Click(object sender, System.EventArgs e)
{
AboutDialog aboutDialog = new AboutDialog();
aboutDialog.ShowDialog(this);
}
private void menuItemNew_Click(object sender, System.EventArgs e)
{
DummyDoc dummyDoc = CreateNewDocument();
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
}
private void menuItemOpen_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = Application.ExecutablePath;
openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFile.FilterIndex = 1;
openFile.RestoreDirectory = true;
if (openFile.ShowDialog() == DialogResult.OK)
{
string fullName = openFile.FileName;
string fileName = Path.GetFileName(fullName);
if (FindDocument(fileName) != null)
{
MessageBox.Show("The document: " + fileName + " has already opened!");
return;
}
DummyDoc dummyDoc = new DummyDoc();
dummyDoc.Text = fileName;
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
dummyDoc.MdiParent = this;
dummyDoc.Show();
}
else
dummyDoc.Show(dockPanel);
try
{
dummyDoc.FileName = fullName;
}
catch (Exception exception)
{
dummyDoc.Close();
MessageBox.Show(exception.Message);
}
}
}
private void menuItemFile_Popup(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
menuItemClose.Enabled =
menuItemCloseAll.Enabled =
menuItemCloseAllButThisOne.Enabled = (ActiveMdiChild != null);
}
else
{
menuItemClose.Enabled = (dockPanel.ActiveDocument != null);
menuItemCloseAll.Enabled =
menuItemCloseAllButThisOne.Enabled = (dockPanel.DocumentsCount > 0);
}
}
private void menuItemClose_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
ActiveMdiChild.Close();
else if (dockPanel.ActiveDocument != null)
dockPanel.ActiveDocument.DockHandler.Close();
}
private void menuItemCloseAll_Click(object sender, System.EventArgs e)
{
CloseAllDocuments();
}
private void MainForm_Load(object sender, System.EventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (File.Exists(configFile))
dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
if (m_bSaveLayout)
dockPanel.SaveAsXml(configFile);
else if (File.Exists(configFile))
File.Delete(configFile);
}
private void menuItemToolBar_Click(object sender, System.EventArgs e)
{
toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked;
}
private void menuItemStatusBar_Click(object sender, System.EventArgs e)
{
statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked;
}
private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem == toolBarButtonNew)
menuItemNew_Click(null, null);
else if (e.ClickedItem == toolBarButtonOpen)
menuItemOpen_Click(null, null);
else if (e.ClickedItem == toolBarButtonSolutionExplorer)
menuItemSolutionExplorer_Click(null, null);
else if (e.ClickedItem == toolBarButtonPropertyWindow)
menuItemPropertyWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonToolbox)
menuItemToolbox_Click(null, null);
else if (e.ClickedItem == toolBarButtonOutputWindow)
menuItemOutputWindow_Click(null, null);
else if (e.ClickedItem == toolBarButtonTaskList)
menuItemTaskList_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByCode)
menuItemLayoutByCode_Click(null, null);
else if (e.ClickedItem == toolBarButtonLayoutByXml)
menuItemLayoutByXml_Click(null, null);
else if (e.ClickedItem == toolBarButtonDockPanelSkinDemo)
SetDockPanelSkinOptions(!toolBarButtonDockPanelSkinDemo.Checked);
}
private void menuItemNewWindow_Click(object sender, System.EventArgs e)
{
MainForm newWindow = new MainForm();
newWindow.Text = newWindow.Text + " - New";
newWindow.Show();
}
private void menuItemTools_Popup(object sender, System.EventArgs e)
{
menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking;
}
private void menuItemLockLayout_Click(object sender, System.EventArgs e)
{
dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking;
}
private void menuItemLayoutByCode_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
CloseAllContents();
CreateStandardControls();
m_solutionExplorer.Show(dockPanel, DockState.DockRight);
m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer);
m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383));
m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35);
m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4);
DummyDoc doc1 = CreateNewDocument("Document1");
DummyDoc doc2 = CreateNewDocument("Document2");
DummyDoc doc3 = CreateNewDocument("Document3");
DummyDoc doc4 = CreateNewDocument("Document4");
doc1.Show(dockPanel, DockState.Document);
doc2.Show(doc1.Pane, null);
doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5);
doc4.Show(doc3.Pane, DockAlignment.Right, 0.5);
dockPanel.ResumeLayout(true, true);
}
private void CreateStandardControls()
{
m_solutionExplorer = new DummySolutionExplorer();
m_propertyWindow = new DummyPropertyWindow();
m_toolbox = new DummyToolbox();
m_outputWindow = new DummyOutputWindow();
m_taskList = new DummyTaskList();
}
private void menuItemLayoutByXml_Click(object sender, System.EventArgs e)
{
dockPanel.SuspendLayout(true);
// In order to load layout from XML, we need to close all the DockContents
CloseAllContents();
CreateStandardControls();
Assembly assembly = Assembly.GetAssembly(typeof(MainForm));
Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml");
dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent);
xmlStream.Close();
dockPanel.ResumeLayout(true, true);
}
private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e)
{
if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
{
Form activeMdi = ActiveMdiChild;
foreach (Form form in MdiChildren)
{
if (form != activeMdi)
form.Close();
}
}
else
{
foreach (IDockContent document in dockPanel.DocumentsToArray())
{
if (!document.DockHandler.IsActivated)
document.DockHandler.Close();
}
}
}
private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e)
{
dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked = !menuItemShowDocumentIcon.Checked;
}
private void showRightToLeft_Click(object sender, EventArgs e)
{
CloseAllContents();
if (showRightToLeft.Checked)
{
this.RightToLeft = RightToLeft.No;
this.RightToLeftLayout = false;
}
else
{
this.RightToLeft = RightToLeft.Yes;
this.RightToLeftLayout = true;
}
m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout;
showRightToLeft.Checked = !showRightToLeft.Checked;
}
private void exitWithoutSavingLayout_Click(object sender, EventArgs e)
{
m_bSaveLayout = false;
Close();
m_bSaveLayout = true;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Filename: STUNListener.cs
//
// Description: Creates the duplex sockets to listen for STUN client requests.
//
// History:
// 27 Dec 2006 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// 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 SIP Sorcery PTY LTD.
// 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;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using SIPSorcery.Sys;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Net
{
/*public class IncomingMessage
{
public SIPChannel InSIPChannel;
public IPEndPoint InEndPoint;
public byte[] Buffer;
public IncomingMessage(SIPChannel inSIPChannel, IPEndPoint inEndPoint, byte[] buffer)
{
InSIPChannel = inSIPChannel;
InEndPoint = inEndPoint;
Buffer = buffer;
}
}*/
public delegate void STUNMessageReceived(IPEndPoint receivedEndPoint, IPEndPoint receivedOnEndPoint, byte[] buffer, int bufferLength);
public class STUNListener
{
private const string STUN_LISTENER_THREAD_NAME = "stunlistener-";
public ILog logger = AppState.logger;
private IPEndPoint m_localEndPoint = null;
private UdpClient m_stunConn = null;
private bool m_closed = false;
public event STUNMessageReceived MessageReceived;
public IPEndPoint SIPChannelEndPoint
{
get{ return m_localEndPoint; }
}
public STUNListener(IPEndPoint endPoint)
{
try
{
m_localEndPoint = InitialiseSockets(endPoint.Address, endPoint.Port);
logger.Info("STUNListener created " + endPoint.Address + ":" + endPoint.Port + ".");
}
catch(Exception excp)
{
logger.Error("Exception STUNListener (ctor). " + excp.Message);
throw excp;
}
}
public void Dispose(bool disposing)
{
try
{
this.Close();
}
catch(Exception excp)
{
logger.Error("Exception Disposing STUNListener. " + excp.Message);
}
}
private IPEndPoint InitialiseSockets(IPAddress localIPAddress, int localPort)
{
try
{
IPEndPoint localEndPoint = null;
UdpClient stunConn = null;
localEndPoint = new IPEndPoint(localIPAddress, localPort);
stunConn = new UdpClient(localEndPoint);
m_stunConn = stunConn;
Thread listenThread = new Thread(new ThreadStart(Listen));
listenThread.Start();
return localEndPoint;
}
catch(Exception excp)
{
logger.Error("Exception STUNListener InitialiseSockets. " + excp.Message);
throw excp;
}
}
private void Listen()
{
try
{
UdpClient stunConn = m_stunConn;
IPEndPoint inEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] buffer = null;
Thread.CurrentThread.Name = STUN_LISTENER_THREAD_NAME + inEndPoint.Port.ToString();
while(!m_closed)
{
try
{
buffer = stunConn.Receive(ref inEndPoint);
}
catch(Exception bufExcp)
{
logger.Error("Exception listening in STUNListener. " + bufExcp.Message + ".");
inEndPoint = new IPEndPoint(IPAddress.Any, 0);
continue;
}
if(buffer == null || buffer.Length == 0)
{
logger.Error("Unable to read from STUNListener local end point " + m_localEndPoint.Address.ToString() + ":" + m_localEndPoint.Port);
}
else
{
if(MessageReceived != null)
{
try
{
MessageReceived( m_localEndPoint, inEndPoint, buffer, buffer.Length);
}
catch (Exception excp)
{
logger.Error("Exception processing STUNListener MessageReceived. " + excp.Message);
}
}
}
}
}
catch(Exception excp)
{
logger.Error("Exception STUNListener Listen. " + excp.Message);
throw excp;
}
}
public virtual void Send(IPEndPoint destinationEndPoint, byte[] buffer)
{
try
{
if(destinationEndPoint == null)
{
logger.Error("An empty destination was specified to Send in STUNListener.");
}
m_stunConn.Send(buffer, buffer.Length, destinationEndPoint);
}
catch(ObjectDisposedException)
{
logger.Warn("The STUNListener was not accessible when attempting to send a message to, " + IPSocket.GetSocketString(destinationEndPoint) + ".");
}
catch(Exception excp)
{
logger.Error("Exception (" + excp.GetType().ToString() + ") STUNListener Send (sendto=>" + IPSocket.GetSocketString(destinationEndPoint) + "). " + excp.Message);
throw excp;
}
}
public void Close()
{
try
{
logger.Debug("Closing STUNListener.");
m_closed = true;
m_stunConn.Close();
}
catch(Exception excp)
{
logger.Warn("Exception STUNListener Close. " +excp.Message);
}
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class STUNListenerUnitTest
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void SampleTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
}
}
#endif
#endregion
}
}
| |
using System;
using NUnit.Framework;
using System.Text;
//using System.Collections.Generic;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Bluetooth.AttributeIds;
namespace InTheHand.Net.Tests.Sdp2
{
[TestFixture]
public class LanguageBaseList_Construction
{
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void BadBaseUshort()
{
ushort badBase = 0;
new LanguageBaseItem(1, 2, badBase);
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void BadBaseAttrId()
{
ServiceAttributeId badBase = 0;
new LanguageBaseItem(1, 2, badBase);
}
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangMustAsciiTwoChars)]
public void BadFromStringEmpty()
{
new LanguageBaseItem(String.Empty, 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangMustAsciiTwoChars)]
public void BadFromStringThree()
{
new LanguageBaseItem("eng", 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangMustAsciiTwoChars)]
public void BadFromStringUtf8OneCharTwoBytes()
{
new LanguageBaseItem("\u00E0", 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangMustAsciiTwoChars)]
public void BadFromStringUtf8OneCharThreeBytes()
{
new LanguageBaseItem("\u201d", 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangMustAsciiTwoChars)]
public void BadFromStringUtf8TwoCharsFourBytes()
{
new LanguageBaseItem("e\u201d", 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
}
//--------------------------------------------------------------
[Test]
public void FromStringA()
{
LanguageBaseItem item = new LanguageBaseItem("en", 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
Assert.AreEqual(Data_LanguageBaseList.LangStringEn, item.NaturalLanguage);
Assert.AreEqual(Data_LanguageBaseList.LangEn, item.NaturalLanguageAsUInt16);
Assert.AreEqual((Int16)Data_LanguageBaseList.LangEn, item.NaturalLanguageAsInt16);
}
[Test]
public void FromStringB()
{
LanguageBaseItem item = new LanguageBaseItem("fr", 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
Assert.AreEqual(Data_LanguageBaseList.LangStringFr, item.NaturalLanguage);
Assert.AreEqual(Data_LanguageBaseList.LangFr, item.NaturalLanguageAsUInt16);
Assert.AreEqual((Int16)Data_LanguageBaseList.LangFr, item.NaturalLanguageAsInt16);
}
[Test]
public void FromNumberA()
{
LanguageBaseItem item = new LanguageBaseItem(Data_LanguageBaseList.LangEn, 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
Assert.AreEqual(Data_LanguageBaseList.LangEn, item.NaturalLanguageAsUInt16);
Assert.AreEqual((Int16)Data_LanguageBaseList.LangEn, item.NaturalLanguageAsInt16);
Assert.AreEqual(Data_LanguageBaseList.LangStringEn, item.NaturalLanguage);
}
[Test]
public void FromNumberB()
{
LanguageBaseItem item = new LanguageBaseItem(Data_LanguageBaseList.LangFr, 2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
Assert.AreEqual(Data_LanguageBaseList.LangFr, item.NaturalLanguageAsUInt16);
Assert.AreEqual((Int16)Data_LanguageBaseList.LangFr, item.NaturalLanguageAsInt16);
Assert.AreEqual(Data_LanguageBaseList.LangStringFr, item.NaturalLanguage);
}
[Test]
public void FromNumberBSignedValues()
{
LanguageBaseItem item = new LanguageBaseItem((Int16)Data_LanguageBaseList.LangFr, (Int16)2252, LanguageBaseItem.PrimaryLanguageBaseAttributeId);
Assert.AreEqual(Data_LanguageBaseList.LangFr, item.NaturalLanguageAsUInt16);
Assert.AreEqual((Int16)Data_LanguageBaseList.LangFr, item.NaturalLanguageAsInt16);
Assert.AreEqual(Data_LanguageBaseList.LangStringFr, item.NaturalLanguage);
}
}
public
#if ! FX1_1
static
#endif
class Data_LanguageBaseList
{
public const UInt16 LangBaseAttrId = 0x0006;
//
public const UInt16 LangEn = 0x656e; // "en"
public const UInt16 LangFr = 0x6672; // "fr"
public const String LangStringEn = "en";
public const String LangStringFr = "fr";
//
public const UInt16 EncUtf8 = 0x006a;
public const UInt16 EncWindows1252 = 0x08cc;
//
public const UInt16 DefaultBaseId = 0x0100;
public static readonly ServiceAttribute AttrOneItem = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement[] {
new ServiceElement(ElementType.UInt16, LangEn),
new ServiceElement(ElementType.UInt16, EncUtf8),
new ServiceElement(ElementType.UInt16, (UInt16)0x0100),
})
);
public static readonly ServiceAttribute AttrTwoItems = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement[] {
new ServiceElement(ElementType.UInt16, LangEn),
new ServiceElement(ElementType.UInt16, EncUtf8),
new ServiceElement(ElementType.UInt16, (UInt16)0x0100),
new ServiceElement(ElementType.UInt16, LangFr),
new ServiceElement(ElementType.UInt16, EncWindows1252),
new ServiceElement(ElementType.UInt16, (UInt16)0x0110),
})
);
public static readonly ServiceAttribute AttrOneItemBadBaseZero = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement[] {
new ServiceElement(ElementType.UInt16, LangEn),
new ServiceElement(ElementType.UInt16, EncUtf8),
new ServiceElement(ElementType.UInt16, (UInt16)00),
})
);
public static readonly ServiceAttribute AttrOneItemBadHasUInt32 = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement[] {
new ServiceElement(ElementType.UInt16, LangEn),
new ServiceElement(ElementType.UInt32, (UInt32)EncUtf8),
new ServiceElement(ElementType.UInt16, (UInt16)0x0100),
})
);
public static readonly ServiceAttribute AttrOneItemBadNotSeq = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementAlternative,
new ServiceElement[] {
new ServiceElement(ElementType.UInt16, LangEn),
new ServiceElement(ElementType.UInt32, (UInt32)EncUtf8),
new ServiceElement(ElementType.UInt16, (UInt16)0x0100),
})
);
public static readonly byte[] RecordTwoItemsAsBytes = {
0x35, 23,
0x09, (LangBaseAttrId >> 8), (LangBaseAttrId & 0xFF), // attrId
0x35, 18,
0x09, (byte)'e',(byte)'n',/**/0x09, 0x00, 0x6A,/**/0x09, 0x01, 0x00,
0x09, (byte)'f',(byte)'r',/**/0x09, 0x08, 0xcc,/**/0x09, 0x01, 0x10,
};
public static readonly ServiceAttribute AttrZeroElements = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement[] { //oops...
})
);
public static readonly ServiceAttribute AttrFourElements = new ServiceAttribute(LangBaseAttrId,
new ServiceElement(ElementType.ElementSequence,
new ServiceElement[] {
new ServiceElement(ElementType.UInt16, LangEn),
new ServiceElement(ElementType.UInt16, EncUtf8),
new ServiceElement(ElementType.UInt16, (UInt16)0x0100),
// oops...
new ServiceElement(ElementType.UInt16, LangEn),
})
);
}//class
[TestFixture]
public class LanguageBaseList_Parse
{
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "LanguageBaseAttributeIdList must contain items in groups of three.")]
public void ZeroElements()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrZeroElements.Value);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "LanguageBaseAttributeIdList must contain items in groups of three.")]
public void FourElements()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrFourElements.Value);
}
//--------------------------------------------------------------
[Test]
public void OneItem()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrOneItem.Value);
Assert.AreEqual(1, items.Length);
Assert.AreEqual(Data_LanguageBaseList.LangStringEn, items[0].NaturalLanguage, "NaturalLanguage");
Assert.AreEqual(Data_LanguageBaseList.LangEn, items[0].NaturalLanguageAsUInt16, "NaturalLanguageUInt16");
Assert.AreEqual(Data_LanguageBaseList.EncUtf8, items[0].EncodingId, "EncodingId");
Assert.AreEqual(Data_LanguageBaseList.EncUtf8, items[0].EncodingIdAsInt16, "EncodingId");
Assert.AreEqual((ServiceAttributeId)0x0100, items[0].AttributeIdBase, "AttributeIdBase");
}
[Test]
public void TwoItems()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrTwoItems.Value);
Assert.AreEqual(2, items.Length);
Assert.AreEqual(Data_LanguageBaseList.LangStringEn, items[0].NaturalLanguage, "NaturalLanguage");
Assert.AreEqual(Data_LanguageBaseList.LangEn, items[0].NaturalLanguageAsUInt16, "NaturalLanguageUInt16");
Assert.AreEqual(Data_LanguageBaseList.EncUtf8, items[0].EncodingId, "EncodingId");
Assert.AreEqual((ServiceAttributeId)0x0100, items[0].AttributeIdBase, "AttributeIdBase");
//
Assert.AreEqual(Data_LanguageBaseList.LangStringFr, items[1].NaturalLanguage, "NaturalLanguage");
Assert.AreEqual(Data_LanguageBaseList.LangFr, items[1].NaturalLanguageAsUInt16, "NaturalLanguageUInt16");
Assert.AreEqual(Data_LanguageBaseList.EncWindows1252, items[1].EncodingId, "EncodingId");
Assert.AreEqual((ServiceAttributeId)0x0110, items[1].AttributeIdBase, "AttributeIdBase");
}
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangBaseListParseBaseInvalid)]
public void OneItemBadBaseZero()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrOneItemBadBaseZero.Value);
}
[Test]
[ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = LanguageBaseItem.ErrorMsgLangBaseListParseNotU16)]
public void OneItemBadHasUInt32()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrOneItemBadHasUInt32.Value);
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "LanguageBaseAttributeIdList elementSequence not an ElementSequence.")]
public void OneItemBadNotSeq()
{
LanguageBaseItem[] items = LanguageBaseItem.ParseListFromElementSequence(Data_LanguageBaseList.AttrOneItemBadNotSeq.Value);
}
}//class
[TestFixture]
public class LanguageBaseList_EncodingFromIetfCharsetId
{
/// <summary>
/// Check that the expected Encoding is mapped from the given IETF charset id,
/// as are used in the LanguageBaseList Attribute.
/// </summary>
private void DoTest(Encoding expectedEncoding, ushort ietfCharsetId)
{
LanguageBaseItem item =
new LanguageBaseItem(/*"en"*/Data_LanguageBaseList.LangEn, ietfCharsetId, (ServiceAttributeId)0x0100);
Encoding encResult = item.GetEncoding();
Assert.AreEqual(expectedEncoding, encResult);
}
//--------------------------------------------------------------
[Test]
[ExpectedException(typeof(NotSupportedException),
ExpectedMessage = "Unrecognized character encoding (1); add to LanguageBaseItem mapping table.")]
public void Unknown_1()
{
DoTest(null, 1);
}
[Test]
public void UTF8_0x006a()
{
DoTest(Encoding.UTF8, 0x006a);
}
[Test]
public void Windows1252_0x08cc()
{
DoTest(Encoding.GetEncoding(1252), 0x08cc);
}
#if ! PocketPC
[Test]
public void Windows1258_0x08D2()
{
DoTest(Encoding.GetEncoding(1258), 0x08d2);
}
[Test]
public void Latin1_iso1_4()
{
DoTest(Encoding.GetEncoding(28591), 4);
}
[Test]
public void Latin5_iso9_12()
{
DoTest(Encoding.GetEncoding(28599), 12);
}
[Test]
public void Latin9_iso15_111()
{
DoTest(Encoding.GetEncoding(28605), 111);
}
#endif
[Test]
public void TestAllDefinedCharsetMappingRows()
{
int numberSuccessful, numberFailed;
String resultText =
LanguageBaseItem.TestAllDefinedEncodingMappingRows(out numberSuccessful, out numberFailed);
int successExpected = 16;
int failedExpected = 3;
#if NETCF
successExpected = 10;
failedExpected = 9;
#endif
Assert.AreEqual(successExpected, numberSuccessful, "numberSuccessful");
Assert.AreEqual(failedExpected, numberFailed, "numberFailed");
//-Console.WriteLine(resultText);
}
}//class
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using GitTfs.Core.TfsInterop;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Setup.Configuration;
using StructureMap;
using WindowsCredential = Microsoft.VisualStudio.Services.Common.WindowsCredential;
namespace GitTfs.VsCommon
{
/// <summary>
/// Base class for TfsHelper targeting VS versions greater or equal to VS2017.
/// </summary>
public abstract class TfsHelperVS2017Base : TfsHelperBase
{
private const string myPrivateAssembliesFolder =
@"Common7\IDE\PrivateAssemblies";
private const string myTeamExplorerFolder =
@"Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer";
private readonly List<string> myAssemblySearchPaths;
/// <summary>
/// Caches the found VS installation path.
/// </summary>
private string myVisualStudioInstallationPath;
private const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154);
private readonly int myMajorVersion;
/// <summary>
/// Loading the ExternalSettingsManager and then GetReadOnlySettingsStore ensures
/// that also the private Visual Studio registry hive which is usually found
/// in a path looking similar to
/// C:\Users\USER\AppData\Local\Microsoft\VisualStudio\15.0_xxxxxx\privateregistry.bin
/// is loaded.
/// Without loading that private VS registry hive, private CheckinPolicies will not work,
/// as the assemblies are simply not found.
/// </summary>
private ExternalSettingsManager myExternalSettingsManager;
public TfsHelperVS2017Base(TfsApiBridge bridge, IContainer container, int majorVersion)
: base(bridge, container)
{
myMajorVersion = majorVersion;
myVisualStudioInstallationPath = GetVsInstallDir();
myAssemblySearchPaths = new List<string>();
if (!string.IsNullOrEmpty(myVisualStudioInstallationPath))
{
// Calling LoadAssemblySearchPathFromVisualStudioPrivateRegistry would immediately
// crash with BadImageException in a 64Bit process therefore put it behind a check
if (!Environment.Is64BitProcess)
{
var devenvPath = Path.Combine(myVisualStudioInstallationPath, @"Common7\IDE\devenv.exe");
LoadAssemblySearchPathFromVisualStudioPrivateRegistry(devenvPath);
}
myAssemblySearchPaths.Add(Path.Combine(myVisualStudioInstallationPath, myPrivateAssembliesFolder));
}
}
/// <summary>
/// Loads the Visual Studio private registry, which is implicitly done when creating
/// a new ExternalSettingsManager. The private registry contains the search paths to the
/// extensions which is required for the Check-In Policies to work.
///
/// Calling this method on a 64bit process will not work, as a BadImageException is thrown.
/// </summary>
/// <param name="devenvPath">Path to the Visual Studio installation for which the private registry shall be loaded</param>
private void LoadAssemblySearchPathFromVisualStudioPrivateRegistry(string devenvPath)
{
Trace.WriteLine($"Loading VS private registry for '{devenvPath}");
myExternalSettingsManager = ExternalSettingsManager.CreateForApplication(devenvPath);
Trace.WriteLine("ApplicationExtensions:" + myExternalSettingsManager.GetApplicationDataFolder(ApplicationDataFolder.ApplicationExtensions));
Trace.WriteLine("Configuration :" + myExternalSettingsManager.GetApplicationDataFolder(ApplicationDataFolder.Configuration));
Trace.WriteLine("LocalSettings :" + myExternalSettingsManager.GetApplicationDataFolder(ApplicationDataFolder.LocalSettings));
Trace.WriteLine("RoamingSettings :" + myExternalSettingsManager.GetApplicationDataFolder(ApplicationDataFolder.RoamingSettings));
Trace.WriteLine("UserExtensions :" + myExternalSettingsManager.GetApplicationDataFolder(ApplicationDataFolder.UserExtensions));
foreach (string searchPath in myExternalSettingsManager.GetCommonExtensionsSearchPaths()) {
Trace.WriteLine("CommonExtensionsPath :" + searchPath);
}
myAssemblySearchPaths.AddRange(myExternalSettingsManager.GetCommonExtensionsSearchPaths());
string userExtensions = myExternalSettingsManager.GetApplicationDataFolder(ApplicationDataFolder.UserExtensions);
if (!userExtensions.IsNullOrEmpty())
{
myAssemblySearchPaths.Add(Path.Combine(myVisualStudioInstallationPath, userExtensions));
}
myAssemblySearchPaths.Add(Path.Combine(myVisualStudioInstallationPath, myTeamExplorerFolder));
}
/// <summary>
/// Enumerates the list of installed VS instances and returns the first one
/// matching <see cref="MajorVersion"/>. Right now there is no way for the user to influence
/// which version to choose if multiple installed version have the same major,
/// e.g. VS2017 installed as Enterprise and Professional.
/// </summary>
/// <returns>
/// Path to the top level directory of the Visual studio installation directory,
/// e.g. <c>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise</c>
/// </returns>
protected string GetVsInstallDir()
{
if (myVisualStudioInstallationPath != null)
return myVisualStudioInstallationPath;
var setupConfiguration = (ISetupConfiguration2)GetSetupConfiguration();
IEnumSetupInstances instancesEnumerator = setupConfiguration.EnumAllInstances();
int fetched;
var instances = new ISetupInstance[1];
while (true)
{
instancesEnumerator.Next(1, instances, out fetched);
if (fetched <= 0)
break;
var instance = (ISetupInstance2)instances[0];
if (!Version.TryParse(instance.GetInstallationVersion(), out Version version))
{
Trace.TraceError("Failed to retrieve version. Skipping VS instance.");
continue;
}
if (version.Major != myMajorVersion)
{
continue;
}
if (myVisualStudioInstallationPath != null)
{
Trace.TraceWarning("Already found a Visual Studio version. Ignoring version at {0}", instance.GetInstallationPath());
continue;
}
var state = instance.GetState();
if (state.HasFlag(InstanceState.Local) && state.HasFlag(InstanceState.Registered))
{
myVisualStudioInstallationPath = instance.GetInstallationPath();
Trace.TraceInformation("Found matching Visual Studio version at {0}", myVisualStudioInstallationPath);
}
else
{
Trace.TraceWarning("Ignoring incomplete Visual Studio version at {0}", instance.GetInstallationPath());
}
}
return myVisualStudioInstallationPath;
}
protected override IBuildDetail GetSpecificBuildFromQueuedBuild(IQueuedBuild queuedBuild, string shelvesetName)
{
var build = queuedBuild.Builds.FirstOrDefault(b => b.ShelvesetName == shelvesetName);
return build != null ? build : queuedBuild.Build;
}
#pragma warning disable 618
private IGroupSecurityService GroupSecurityService
{
get { return GetService<IGroupSecurityService>(); }
}
public override IIdentity GetIdentity(string username)
{
return _bridge.Wrap<WrapperForIdentity, Identity>(Retry.Do(() => GroupSecurityService.ReadIdentity(SearchFactor.AccountName, username, QueryMembership.None)));
}
protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
{
var vssCred = HasCredentials
? new VssClientCredentials(new WindowsCredential(GetCredential()))
: VssClientCredentials.LoadCachedCredentials(uri, false, CredentialPromptType.PromptIfNeeded);
return new TfsTeamProjectCollection(uri, vssCred);
#pragma warning restore 618
}
protected override string GetDialogAssemblyPath()
{
return Path.Combine(GetVsInstallDir(), myTeamExplorerFolder, DialogAssemblyName + ".dll");
}
protected override Assembly LoadFromVsFolder(object sender, ResolveEventArgs args)
{
Trace.WriteLine("Looking for assembly " + args.Name + " ...");
foreach (var dir in myAssemblySearchPaths)
{
string assemblyPath = Path.Combine(dir, new AssemblyName(args.Name).Name + ".dll");
if (File.Exists(assemblyPath))
{
Trace.WriteLine("... loading " + args.Name + " from " + assemblyPath);
return Assembly.LoadFrom(assemblyPath);
}
}
return null;
}
private static ISetupConfiguration GetSetupConfiguration()
{
try
{
// Try to CoCreate the class object.
return new SetupConfiguration();
}
catch (COMException ex)
{
if (ex.HResult == REGDB_E_CLASSNOTREG)
{
// Attempt to get the class object using an app-local call.
ISetupConfiguration setupConfiguration;
var result = GetSetupConfiguration(out setupConfiguration, IntPtr.Zero);
if (result < 0)
{
throw new COMException("Failed to get setup configuration query.", result);
}
return setupConfiguration;
}
throw ex;
}
}
[DllImport("Microsoft.VisualStudio.Setup.Configuration.Native.dll", ExactSpelling = true, PreserveSig = true)]
static extern int GetSetupConfiguration([MarshalAs(UnmanagedType.Interface), Out] out ISetupConfiguration configuration, IntPtr reserved);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using System.Drawing;
using System.Threading.Tasks;
using CoreGraphics;
using CoreAnimation;
namespace XamarinStore.iOS
{
public class ProductDetailViewController : UITableViewController
{
public event Action<Product> AddToBasket = delegate {};
Product CurrentProduct;
ProductSize[] sizeOptions;
BottomButtonView BottomView;
ProductColor[] colorOptions;
StringSelectionCell colorCell, sizeCell;
JBKenBurnsView imageView;
UIImage tshirtIcon;
public ProductDetailViewController (Product product)
{
CurrentProduct = product;
Title = CurrentProduct.Name;
LoadProductData ();
TableView.TableFooterView = new UIView (new RectangleF (0, 0, 0, BottomButtonView.Height));
View.AddSubview (BottomView = new BottomButtonView () {
ButtonText = "Add to Basket",
Button = {
Image = (tshirtIcon = UIImage.FromBundle("t-shirt")),
},
ButtonTapped = async () => await addToBasket ()
});
}
async Task addToBasket()
{
var center = BottomView.Button.ConvertPointToView (BottomView.Button.ImageView.Center, NavigationController.View);
var imageView = new UIImageView (tshirtIcon) {
Center = center,
ContentMode = UIViewContentMode.ScaleAspectFill
};
var backgroundView = new UIImageView (UIImage.FromBundle("circle")) {
Center = center,
};
NavigationController.View.AddSubview (backgroundView);
NavigationController.View.AddSubview (imageView);
await Task.WhenAll (new [] {
animateView (imageView),
animateView (backgroundView),
});
NavigationItem.RightBarButtonItem = AppDelegate.Shared.CreateBasketButton ();
AddToBasket (CurrentProduct);
}
async Task animateView(UIView view)
{
var size = view.Frame.Size;
var grow = new SizeF((float)size.Width * 1.7f, (float)size.Height * 1.7f);
var shrink = new SizeF((float)size.Width * .4f, (float)size.Height * .4f);
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool> ();
//Set the animation path
var pathAnimation = CAKeyFrameAnimation.GetFromKeyPath("position");
pathAnimation.CalculationMode = CAAnimation.AnimationPaced;
pathAnimation.FillMode = CAFillMode.Forwards;
pathAnimation.RemovedOnCompletion = false;
pathAnimation.Duration = .5;
UIBezierPath path = new UIBezierPath ();
path.MoveTo (view.Center);
path.AddQuadCurveToPoint (new CGPoint (290, 34), new CGPoint(view.Center.X,View.Center.Y));
pathAnimation.Path = path.CGPath;
//Set size change
var growAnimation = CABasicAnimation.FromKeyPath("bounds.size");
growAnimation.To = NSValue.FromSizeF (grow);
growAnimation.FillMode = CAFillMode.Forwards;
growAnimation.Duration = .1;
growAnimation.RemovedOnCompletion = false;
var shrinkAnimation = CABasicAnimation.FromKeyPath("bounds.size");
shrinkAnimation.To = NSValue.FromSizeF (shrink);
shrinkAnimation.FillMode = CAFillMode.Forwards;
shrinkAnimation.Duration = .4;
shrinkAnimation.RemovedOnCompletion = false;
shrinkAnimation.BeginTime = .1;
CAAnimationGroup animations = new CAAnimationGroup ();
animations.FillMode = CAFillMode.Forwards;
animations.RemovedOnCompletion = false;
animations.Animations = new CAAnimation[] {
pathAnimation,
growAnimation,
shrinkAnimation,
};
animations.Duration = .5;
animations.AnimationStopped += (sender, e) => {
tcs.TrySetResult(true);
};
view.Layer.AddAnimation (animations,"movetocart");
NSTimer.CreateScheduledTimer (.5, (timer) => view.RemoveFromSuperview ());
await tcs.Task;
}
string[] imageUrls = new string[0];
public void LoadProductData ()
{
// Add spinner while loading data.
TableView.Source = new ProductDetailPageSource (new [] {
new SpinnerCell(),
});
colorOptions = CurrentProduct.Colors;
sizeOptions = CurrentProduct.Sizes;
imageUrls = CurrentProduct.ImageUrls.ToArray().Shuffle();
imageView = new JBKenBurnsView {
Frame = new RectangleF (0, -60, 320, 400),
Images = Enumerable.Range(0,imageUrls.Length).Select(x=> new UIImage()).ToList(),
UserInteractionEnabled = false,
};
loadImages ();
var productDescriptionView = new ProductDescriptionView (CurrentProduct) {
Frame = new RectangleF (0, 0, 320, 120),
};
TableView.TableHeaderView = new UIView(new CGRect(0,0,imageView.Frame.Width,imageView.Frame.Bottom)){imageView};
var tableItems = new List<UITableViewCell> () {
new CustomViewCell (productDescriptionView),
};
tableItems.AddRange (GetOptionsCells ());
TableView.Source = new ProductDetailPageSource (tableItems.ToArray ());
TableView.ReloadData ();
}
async void loadImages()
{
for (int i = 0; i < imageUrls.Length; i++) {
var path = await FileCache.Download (Product.ImageForSize (imageUrls [i], 320 * (float)UIScreen.MainScreen.Scale));
imageView.Images [i] = UIImage.FromFile (path);
}
}
IEnumerable<UITableViewCell> GetOptionsCells ()
{
yield return sizeCell = new StringSelectionCell (View) {
Text = "Size",
Items = sizeOptions.Select (x => x.Description),
DetailText = CurrentProduct.Size.Description,
SelectionChanged = () => {
var size = sizeOptions [sizeCell.SelectedIndex];
CurrentProduct.Size = size;
}
};
yield return colorCell = new StringSelectionCell (View) {
Text = "Color",
Items = colorOptions.Select (x => x.Name),
DetailText = CurrentProduct.Color.Name,
SelectionChanged = () => {
var color = colorOptions [colorCell.SelectedIndex];
CurrentProduct.Color = color;
},
};
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
NavigationItem.RightBarButtonItem = AppDelegate.Shared.CreateBasketButton ();
imageView.Animate();
var bottomRow = NSIndexPath.FromRowSection (TableView.NumberOfRowsInSection (0) - 1, 0);
TableView.ScrollToRow (bottomRow,UITableViewScrollPosition.Top, false);
}
public override void ViewDidLayoutSubviews ()
{
base.ViewDidLayoutSubviews ();
var bound = View.Bounds;
bound.Y = bound.Bottom - BottomButtonView.Height;
bound.Height = BottomButtonView.Height;
BottomView.Frame = bound;
}
}
public class ProductDetailPageSource : UITableViewSource
{
UITableViewCell[] tableItems;
public ProductDetailPageSource (UITableViewCell[] items)
{
tableItems = items;
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return tableItems.Length;
}
public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
{
return tableItems [indexPath.Row];
}
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
return tableItems [indexPath.Row].Frame.Height;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
if (tableItems [indexPath.Row] is StringSelectionCell)
((StringSelectionCell)tableItems [indexPath.Row]).Tap ();
tableView.DeselectRow (indexPath, true);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using log4net;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public class LLImageManager
{
private sealed class J2KImageComparer : IComparer<J2KImage>
{
public int Compare(J2KImage x, J2KImage y)
{
return x.Priority.CompareTo(y.Priority);
}
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_shuttingdown;
private AssetBase m_missingImage;
private LLClientView m_client; //Client we're assigned to
private IAssetService m_assetCache; //Asset Cache
private IJ2KDecoder m_j2kDecodeModule; //Our J2K module
private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());
private object m_syncRoot = new object();
public LLClientView Client { get { return m_client; } }
public AssetBase MissingImage { get { return m_missingImage; } }
public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
{
m_client = client;
m_assetCache = pAssetCache;
if (pAssetCache != null)
m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
if (m_missingImage == null)
m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
m_j2kDecodeModule = pJ2kDecodeModule;
}
/// <summary>
/// Handles an incoming texture request or update to an existing texture request
/// </summary>
/// <param name="newRequest"></param>
public void EnqueueReq(TextureRequestArgs newRequest)
{
//Make sure we're not shutting down..
if (!m_shuttingdown)
{
J2KImage imgrequest;
// Do a linear search for this texture download
lock (m_syncRoot)
m_priorityQueue.Find(delegate(J2KImage img) { return img.TextureID == newRequest.RequestedAssetID; }, out imgrequest);
if (imgrequest != null)
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//m_log.Debug("[TEX]: (CAN) ID=" + newRequest.RequestedAssetID);
try
{
lock (m_syncRoot)
m_priorityQueue.Delete(imgrequest.PriorityQueueHandle);
}
catch (Exception) { }
}
else
{
//m_log.DebugFormat("[TEX]: (UPD) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
//Check the packet sequence to make sure this isn't older than
//one we've already received
if (newRequest.requestSequence > imgrequest.LastSequence)
{
//Update the sequence number of the last RequestImage packet
imgrequest.LastSequence = newRequest.requestSequence;
//Update the requested discard level
imgrequest.DiscardLevel = newRequest.DiscardLevel;
//Update the requested packet number
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Update the requested priority
imgrequest.Priority = newRequest.Priority;
UpdateImageInQueue(imgrequest);
//Run an update
imgrequest.RunUpdate();
}
}
}
else
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//m_log.DebugFormat("[TEX]: (IGN) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
}
else
{
//m_log.DebugFormat("[TEX]: (NEW) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
imgrequest = new J2KImage(this);
imgrequest.J2KDecoder = m_j2kDecodeModule;
imgrequest.AssetService = m_assetCache;
imgrequest.AgentID = m_client.AgentId;
imgrequest.InventoryAccessModule = m_client.Scene.RequestModuleInterface<IInventoryAccessModule>();
imgrequest.DiscardLevel = newRequest.DiscardLevel;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
imgrequest.Priority = newRequest.Priority;
imgrequest.TextureID = newRequest.RequestedAssetID;
imgrequest.Priority = newRequest.Priority;
//Add this download to the priority queue
AddImageToQueue(imgrequest);
//Run an update
imgrequest.RunUpdate();
}
}
}
}
public bool ProcessImageQueue(int packetsToSend)
{
int packetsSent = 0;
while (packetsSent < packetsToSend)
{
J2KImage image = GetHighestPriorityImage();
// If null was returned, the texture priority queue is currently empty
if (image == null)
return false;
if (image.IsDecoded)
{
int sent;
bool imageDone = image.SendPackets(m_client, packetsToSend - packetsSent, out sent);
packetsSent += sent;
// If the send is complete, destroy any knowledge of this transfer
if (imageDone)
RemoveImageFromQueue(image);
}
else
{
// TODO: This is a limitation of how LLImageManager is currently
// written. Undecoded textures should not be going into the priority
// queue, because a high priority undecoded texture will clog up the
// pipeline for a client
return true;
}
}
return m_priorityQueue.Count > 0;
}
/// <summary>
/// Faux destructor
/// </summary>
public void Close()
{
m_shuttingdown = true;
}
#region Priority Queue Helpers
J2KImage GetHighestPriorityImage()
{
J2KImage image = null;
lock (m_syncRoot)
{
if (m_priorityQueue.Count > 0)
{
try { image = m_priorityQueue.FindMax(); }
catch (Exception) { }
}
}
return image;
}
void AddImageToQueue(J2KImage image)
{
image.PriorityQueueHandle = null;
lock (m_syncRoot)
try { m_priorityQueue.Add(ref image.PriorityQueueHandle, image); }
catch (Exception) { }
}
void RemoveImageFromQueue(J2KImage image)
{
lock (m_syncRoot)
try { m_priorityQueue.Delete(image.PriorityQueueHandle); }
catch (Exception) { }
}
void UpdateImageInQueue(J2KImage image)
{
lock (m_syncRoot)
{
try { m_priorityQueue.Replace(image.PriorityQueueHandle, image); }
catch (Exception)
{
image.PriorityQueueHandle = null;
m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
}
}
}
#endregion Priority Queue Helpers
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Game.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace BloomPostprocess
{
/// <summary>
/// Sample showing how to implement a bloom postprocess,
/// adding a glowing effect over the top of an existing scene.
/// </summary>
public class BloomPostprocessGame : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
BloomComponent bloom;
int bloomSettingsIndex = 0;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
Texture2D background;
Model model;
KeyboardState lastKeyboardState = new KeyboardState();
GamePadState lastGamePadState = new GamePadState();
KeyboardState currentKeyboardState = new KeyboardState();
GamePadState currentGamePadState = new GamePadState();
#endregion
#region Initialization
public BloomPostprocessGame()
{
Content.RootDirectory = "Content";
graphics = new GraphicsDeviceManager(this);
bloom = new BloomComponent(this);
Components.Add(bloom);
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
spriteFont = Content.Load<SpriteFont>("hudFont");
background = Content.Load<Texture2D>("sunset");
model = Content.Load<Model>("tank");
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
HandleInput();
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice device = graphics.GraphicsDevice;
Viewport viewport = device.Viewport;
bloom.BeginDraw();
device.Clear(Color.Black);
// Draw the background image.
spriteBatch.Begin(0, BlendState.Opaque);
spriteBatch.Draw(background,
new Rectangle(0, 0, viewport.Width, viewport.Height),
Color.White);
spriteBatch.End();
// Draw the spinning model.
device.DepthStencilState = DepthStencilState.Default;
DrawModel(gameTime);
// Draw other components (which includes the bloom).
base.Draw(gameTime);
// Display some text over the top. Note how we draw this after the bloom,
// because we don't want the text to be affected by the postprocessing.
DrawOverlayText();
}
/// <summary>
/// Helper for drawing the spinning 3D model.
/// </summary>
void DrawModel(GameTime gameTime)
{
float time = (float)gameTime.TotalGameTime.TotalSeconds;
Viewport viewport = graphics.GraphicsDevice.Viewport;
float aspectRatio = (float)viewport.Width / (float)viewport.Height;
// Create camera matrices.
Matrix world = Matrix.CreateRotationY(time * 0.42f);
Matrix view = Matrix.CreateLookAt(new Vector3(750, 100, 0),
new Vector3(0, 300, 0),
Vector3.Up);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(1, aspectRatio,
1, 10000);
// Look up the bone transform matrices.
Matrix[] transforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(transforms);
// Draw the model.
foreach (ModelMesh mesh in model.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = transforms[mesh.ParentBone.Index] * world;
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
// Override the default specular color to make it nice and bright,
// so we'll get some decent glints that the bloom can key off.
effect.SpecularColor = Vector3.One;
}
mesh.Draw();
}
}
/// <summary>
/// Displays an overlay showing what the controls are,
/// and which settings are currently selected.
/// </summary>
void DrawOverlayText()
{
string text = "A = settings (" + bloom.Settings.Name + ")\n" +
"B = toggle bloom (" + (bloom.Visible ? "on" : "off") + ")\n" +
"X = show buffer (" + bloom.ShowBuffer.ToString() + ")";
spriteBatch.Begin();
// Draw the string twice to create a drop shadow, first colored black
// and offset one pixel to the bottom right, then again in white at the
// intended position. This makes text easier to read over the background.
spriteBatch.DrawString(spriteFont, text, new Vector2(65, 65), Color.Black);
spriteBatch.DrawString(spriteFont, text, new Vector2(64, 64), Color.White);
spriteBatch.End();
}
#endregion
#region Handle Input
/// <summary>
/// Handles input for quitting or changing the bloom settings.
/// </summary>
private void HandleInput()
{
lastKeyboardState = currentKeyboardState;
lastGamePadState = currentGamePadState;
currentKeyboardState = Keyboard.GetState();
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Check for exit.
if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
currentGamePadState.Buttons.Back == ButtonState.Pressed)
{
Exit();
}
// Switch to the next bloom settings preset?
if ((currentGamePadState.Buttons.A == ButtonState.Pressed &&
lastGamePadState.Buttons.A != ButtonState.Pressed) ||
(currentKeyboardState.IsKeyDown(Keys.A) &&
lastKeyboardState.IsKeyUp(Keys.A)))
{
bloomSettingsIndex = (bloomSettingsIndex + 1) %
BloomSettings.PresetSettings.Length;
bloom.Settings = BloomSettings.PresetSettings[bloomSettingsIndex];
bloom.Visible = true;
}
// Toggle bloom on or off?
if ((currentGamePadState.Buttons.B == ButtonState.Pressed &&
lastGamePadState.Buttons.B != ButtonState.Pressed) ||
(currentKeyboardState.IsKeyDown(Keys.B) &&
lastKeyboardState.IsKeyUp(Keys.B)))
{
bloom.Visible = !bloom.Visible;
}
// Cycle through the intermediate buffer debug display modes?
if ((currentGamePadState.Buttons.X == ButtonState.Pressed &&
lastGamePadState.Buttons.X != ButtonState.Pressed) ||
(currentKeyboardState.IsKeyDown(Keys.X) &&
lastKeyboardState.IsKeyUp(Keys.X)))
{
bloom.Visible = true;
bloom.ShowBuffer++;
if (bloom.ShowBuffer > BloomComponent.IntermediateBuffer.FinalResult)
bloom.ShowBuffer= 0;
}
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (BloomPostprocessGame game = new BloomPostprocessGame())
{
game.Run();
}
}
}
#endregion
}
| |
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Linq;
using UnityEngine;
namespace TiltBrush {
static public class VideoRecorderUtils {
static private float m_VideoCaptureResolutionScale = 1.0f;
static private int m_DebugVideoCaptureQualityLevel = -1;
static private int m_PreCaptureQualityLevel = -1;
// [Range(RenderWrapper.SSAA_MIN, RenderWrapper.SSAA_MAX)]
static private float m_SuperSampling = 2.0f;
static private float m_PreCaptureSuperSampling = 1.0f;
#if USD_SUPPORTED
static private UsdPathSerializer m_UsdPathSerializer;
static private System.Diagnostics.Stopwatch m_RecordingStopwatch;
static private string m_UsdPath;
#endif
static private VideoRecorder m_ActiveVideoRecording;
static public VideoRecorder ActiveVideoRecording {
get { return m_ActiveVideoRecording; }
}
static public int NumFramesInUsdSerializer {
get {
#if USD_SUPPORTED
if (m_UsdPathSerializer != null && !m_UsdPathSerializer.IsRecording) {
return Mathf.CeilToInt((float)m_UsdPathSerializer.Duration *
(int)m_ActiveVideoRecording.FPS);
}
#endif
return 0;
}
}
static public bool UsdPathSerializerIsBlocking {
get {
#if USD_SUPPORTED
return (m_UsdPathSerializer != null &&
!m_UsdPathSerializer.IsRecording &&
!m_UsdPathSerializer.IsFinished);
#else
return false;
#endif
}
}
static public bool UsdPathIsFinished {
get {
#if USD_SUPPORTED
return (m_UsdPathSerializer != null && m_UsdPathSerializer.IsFinished);
#else
return true;
#endif
}
}
static public Transform AdvanceAndDeserializeUsd() {
#if USD_SUPPORTED
if (m_UsdPathSerializer != null) {
m_UsdPathSerializer.Time += Time.deltaTime;
m_UsdPathSerializer.Deserialize();
return m_UsdPathSerializer.transform;
}
#endif
return null;
}
static public void SerializerNewUsdFrame() {
#if USD_SUPPORTED
if (m_UsdPathSerializer != null && m_UsdPathSerializer.IsRecording) {
m_UsdPathSerializer.Time = (float)m_RecordingStopwatch.Elapsed.TotalSeconds;
m_UsdPathSerializer.Serialize();
}
#endif
}
static public bool StartVideoCapture(string filePath, VideoRecorder recorder,
UsdPathSerializer usdPathSerializer, bool offlineRender = false) {
// Only one video at a time.
if (m_ActiveVideoRecording != null) {
return false;
}
// Don't start recording unless there is enough space left.
if (!FileUtils.InitializeDirectoryWithUserError(
Path.GetDirectoryName(filePath),
"Failed to start video capture")) {
return false;
}
// Vertical video is disabled.
recorder.IsPortrait = false;
// Start the capture first, which may fail, so do this before toggling any state.
// While the state below is important for the actual frame capture, starting the capture process
// does not require it.
int sampleRate = 0;
if (AudioCaptureManager.m_Instance.IsCapturingAudio) {
sampleRate = AudioCaptureManager.m_Instance.SampleRate;
}
if (!recorder.StartCapture(filePath, sampleRate,
AudioCaptureManager.m_Instance.IsCapturingAudio, offlineRender,
offlineRender ? App.UserConfig.Video.OfflineFPS : App.UserConfig.Video.FPS)) {
OutputWindowScript.ReportFileSaved("Failed to start capture!", null,
OutputWindowScript.InfoCardSpawnPos.Brush);
return false;
}
m_ActiveVideoRecording = recorder;
// Perform any necessary VR camera rendering optimizations to reduce CPU & GPU workload
// Debug reduce quality for capture.
// XXX This should just be ADAPTIVE RENDERING
if (m_DebugVideoCaptureQualityLevel != -1) {
m_PreCaptureQualityLevel = QualityControls.m_Instance.QualityLevel;
QualityControls.m_Instance.QualityLevel = m_DebugVideoCaptureQualityLevel;
}
App.VrSdk.SetHmdScalingFactor(m_VideoCaptureResolutionScale);
// Setup SSAA
RenderWrapper wrapper = recorder.gameObject.GetComponent<RenderWrapper>();
m_PreCaptureSuperSampling = wrapper.SuperSampling;
wrapper.SuperSampling = m_SuperSampling;
#if USD_SUPPORTED
// Read from the Usd serializer if we're recording offline. Write to it otherwise.
m_UsdPathSerializer = usdPathSerializer;
if (!offlineRender) {
m_UsdPath = SaveLoadScript.m_Instance.SceneFile.Valid ?
Path.ChangeExtension(filePath, "usda") : null;
m_RecordingStopwatch = new System.Diagnostics.Stopwatch();
m_RecordingStopwatch.Start();
if (!m_UsdPathSerializer.StartRecording()) {
UnityEngine.Object.Destroy(m_UsdPathSerializer);
m_UsdPathSerializer = null;
}
} else {
recorder.SetCaptureFramerate(Mathf.RoundToInt(App.UserConfig.Video.OfflineFPS));
m_UsdPath = null;
if (m_UsdPathSerializer.Load(App.Config.m_VideoPathToRender)) {
m_UsdPathSerializer.StartPlayback();
} else {
UnityEngine.Object.Destroy(m_UsdPathSerializer);
m_UsdPathSerializer = null;
}
}
#endif
return true;
}
static public void StopVideoCapture(bool saveCapture) {
// Debug reset changes to quality settings.
if (m_DebugVideoCaptureQualityLevel != -1) {
QualityControls.m_Instance.QualityLevel = m_PreCaptureQualityLevel;
}
App.VrSdk.SetHmdScalingFactor(1.0f);
// Stop capturing, reset colors
m_ActiveVideoRecording.gameObject.GetComponent<RenderWrapper>().SuperSampling =
m_PreCaptureSuperSampling;
m_ActiveVideoRecording.StopCapture(save: saveCapture);
#if USD_SUPPORTED
if (m_UsdPathSerializer != null) {
bool wasRecording = m_UsdPathSerializer.IsRecording;
m_UsdPathSerializer.Stop();
if (wasRecording) {
m_RecordingStopwatch.Stop();
if (!string.IsNullOrEmpty(m_UsdPath)) {
if (App.UserConfig.Video.SaveCameraPath && saveCapture) {
m_UsdPathSerializer.Save(m_UsdPath);
CreateOfflineRenderBatchFile(SaveLoadScript.m_Instance.SceneFile.FullPath, m_UsdPath);
}
}
}
}
m_UsdPathSerializer = null;
m_RecordingStopwatch = null;
#endif
m_ActiveVideoRecording = null;
App.Switchboard.TriggerVideoRecordingStopped();
}
/// Creates a batch file the user can execute to make a high quality re-render of the video that
/// has just been recorded.
static void CreateOfflineRenderBatchFile(string sketchFile, string usdaFile) {
string batFile = Path.ChangeExtension(usdaFile, ".HQ_Render.bat");
var pathSections = Application.dataPath.Split('/').ToArray();
var exePath = String.Join("/", pathSections.Take(pathSections.Length - 1).ToArray());
// For the reader:
// In order for this function to generate a functional .bat file, this string needs to be
// updated to reflect the path to the application. For example, if you've distributed your
// app to Steam, this might be:
// "C:/Program Files (x86)/Steam/steamapps/common/Tilt Brush/TiltBrush.exe"
// But if you're building locally, this should point to your standalone executable that you
// created, something like:
// "C:/src/Builds/Windows_SteamVR_Release/TiltBrush.exe"
string offlineRenderExePath = "Change me to the path to the .exe";
string batText = string.Format(
"@\"{0}/Support/bin/renderVideo.cmd\" ^\n\t\"{1}\" ^\n\t\"{2}\" ^\n\t\"{3}\"",
exePath, sketchFile, usdaFile, offlineRenderExePath);
File.WriteAllText(batFile, batText);
}
}
} // namespace TiltBrush
| |
using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Globalization;
namespace DotNet.Xdt
{
class XmlAttributePreservingWriter : XmlWriter
{
readonly XmlTextWriter _xmlWriter;
readonly AttributeTextWriter _textWriter;
public XmlAttributePreservingWriter(string fileName, Encoding? encoding)
: this(encoding is null ? new StreamWriter(fileName) : new StreamWriter(fileName, false, encoding))
{ }
public XmlAttributePreservingWriter(Stream w, Encoding? encoding)
: this(encoding is null ? new StreamWriter(w) : new StreamWriter(w, encoding))
{ }
public XmlAttributePreservingWriter(TextWriter textWriter)
{
_textWriter = new AttributeTextWriter(textWriter);
_xmlWriter = new XmlTextWriter(_textWriter);
}
public void WriteAttributeWhitespace(string whitespace)
{
Debug.Assert(IsOnlyWhitespace(whitespace));
// Make sure we're in the right place to write
// whitespace between attributes
if (WriteState == WriteState.Attribute)
WriteEndAttribute();
else if (WriteState != WriteState.Element)
throw new InvalidOperationException();
// We don't write right away. We're going to wait until an
// attribute is being written
_textWriter.AttributeLeadingWhitespace = whitespace;
}
public void WriteAttributeTrailingWhitespace(string whitespace)
{
Debug.Assert(IsOnlyWhitespace(whitespace));
if (WriteState == WriteState.Attribute)
WriteEndAttribute();
else if (WriteState != WriteState.Element)
throw new InvalidOperationException();
_textWriter.Write(whitespace);
}
public string SetAttributeNewLineString(string newLineString)
{
string old = _textWriter.AttributeNewLineString;
if (newLineString is null && _xmlWriter.Settings is not null)
newLineString = _xmlWriter.Settings.NewLineChars;
newLineString ??= "\r\n";
_textWriter.AttributeNewLineString = newLineString;
return old;
}
static bool IsOnlyWhitespace(string whitespace)
{
foreach (char whitespaceCharacter in whitespace)
if (!char.IsWhiteSpace(whitespaceCharacter)) return false;
return true;
}
class AttributeTextWriter : TextWriter
{
enum State
{
Writing,
WaitingForAttributeLeadingSpace,
ReadingAttribute,
Buffering,
FlushingBuffer,
}
State _state = State.Writing;
StringBuilder? _writeBuffer;
readonly TextWriter _baseWriter;
int _lineNumber = 1;
int _linePosition = 1;
public AttributeTextWriter(TextWriter baseWriter)
: base(CultureInfo.InvariantCulture)
=> _baseWriter = baseWriter;
public string? AttributeLeadingWhitespace { get; set; }
public string AttributeNewLineString { get; set; } = "\r\n";
public void StartAttribute()
{
Debug.Assert(_state == State.Writing);
ChangeState(State.WaitingForAttributeLeadingSpace);
}
public void EndAttribute()
{
Debug.Assert(_state == State.ReadingAttribute);
WriteQueuedAttribute();
}
int MaxLineLength { get; } = 160;
public override void Write(char value)
{
UpdateState(value);
switch (_state)
{
case State.WaitingForAttributeLeadingSpace:
if (value == ' ')
{
ChangeState(State.ReadingAttribute);
break;
}
goto case State.Writing;
case State.Writing:
case State.FlushingBuffer:
ReallyWriteCharacter(value);
break;
case State.ReadingAttribute:
case State.Buffering:
_writeBuffer?.Append(value);
break;
}
}
void UpdateState(char value)
{
// This logic prevents writing the leading space that
// XmlTextWriter wants to put before "/>".
switch (value)
{
case ' ':
if (_state == State.Writing)
ChangeState(State.Buffering);
break;
case '/':
break;
case '>':
if (_state == State.Buffering)
{
string currentBuffer = _writeBuffer?.ToString() ?? "";
if (currentBuffer.EndsWith(" /", StringComparison.Ordinal))
{
// We've identified the string " />" at the
// end of the buffer, so remove the space
_writeBuffer?.Remove(currentBuffer.LastIndexOf(' '), 1);
}
ChangeState(State.Writing);
}
break;
default:
if (_state == State.Buffering)
ChangeState(State.Writing);
break;
}
}
void ChangeState(State newState)
{
if (_state != newState)
{
State oldState = _state;
_state = newState;
// Handle buffer management for different states
if (StateRequiresBuffer(newState))
CreateBuffer();
else if (StateRequiresBuffer(oldState))
FlushBuffer();
}
}
static bool StateRequiresBuffer(State state)
=> state == State.Buffering || state == State.ReadingAttribute;
void CreateBuffer()
{
Debug.Assert(_writeBuffer is null);
if (_writeBuffer is null)
_writeBuffer = new StringBuilder();
}
void FlushBuffer()
{
Debug.Assert(_writeBuffer is not null);
if (_writeBuffer is null) return;
State oldState = _state;
try
{
_state = State.FlushingBuffer;
Write(_writeBuffer.ToString());
_writeBuffer = null;
}
finally
{
_state = oldState;
}
}
void ReallyWriteCharacter(char value)
{
_baseWriter.Write(value);
if (value == '\n')
{
_lineNumber++;
_linePosition = 1;
}
else
_linePosition++;
}
void WriteQueuedAttribute()
{
// Write leading whitespace
if (AttributeLeadingWhitespace is not null)
{
_writeBuffer?.Insert(0, AttributeLeadingWhitespace);
AttributeLeadingWhitespace = null;
}
else
{
int lineLength = _linePosition + _writeBuffer!.Length + 1;
if (lineLength > MaxLineLength)
_writeBuffer.Insert(0, AttributeNewLineString);
else
_writeBuffer.Insert(0, ' ');
}
// Flush the buffer and start writing characters again
ChangeState(State.Writing);
}
public override Encoding Encoding => _baseWriter.Encoding;
public override void Flush() => _baseWriter.Flush();
public override void Close() => _baseWriter.Close();
protected override void Dispose(bool disposing)
{
_baseWriter.Dispose();
base.Dispose(disposing);
}
}
public override void Close()
=> _xmlWriter.Close();
protected override void Dispose(bool disposing)
{
_xmlWriter.Dispose();
base.Dispose(disposing);
}
public override void Flush()
=> _xmlWriter.Flush();
public override string LookupPrefix(string ns)
=> _xmlWriter.LookupPrefix(ns);
public override void WriteBase64(byte[] buffer, int index, int count)
=> _xmlWriter.WriteBase64(buffer, index, count);
public override void WriteCData(string text)
=> _xmlWriter.WriteCData(text);
public override void WriteCharEntity(char ch)
=> _xmlWriter.WriteCharEntity(ch);
public override void WriteChars(char[] buffer, int index, int count)
=> _xmlWriter.WriteChars(buffer, index, count);
public override void WriteComment(string text)
=> _xmlWriter.WriteComment(text);
public override void WriteDocType(string name, string pubid, string sysid, string subset)
=> _xmlWriter.WriteDocType(name, pubid, sysid, subset);
public override void WriteEndAttribute()
{
_xmlWriter.WriteEndAttribute();
_textWriter.EndAttribute();
}
public override void WriteEndDocument()
=> _xmlWriter.WriteEndDocument();
public override void WriteEndElement()
=> _xmlWriter.WriteEndElement();
public override void WriteEntityRef(string name)
=> _xmlWriter.WriteEntityRef(name);
public override void WriteFullEndElement()
=> _xmlWriter.WriteFullEndElement();
public override void WriteProcessingInstruction(string name, string text)
=> _xmlWriter.WriteProcessingInstruction(name, text);
public override void WriteRaw(string data)
=> _xmlWriter.WriteRaw(data);
public override void WriteRaw(char[] buffer, int index, int count)
=> _xmlWriter.WriteRaw(buffer, index, count);
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
_textWriter.StartAttribute();
_xmlWriter.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteStartDocument(bool standalone)
=> _xmlWriter.WriteStartDocument(standalone);
public override void WriteStartDocument()
=> _xmlWriter.WriteStartDocument();
public override void WriteStartElement(string prefix, string localName, string ns)
=> _xmlWriter.WriteStartElement(prefix, localName, ns);
public override WriteState WriteState
=> _xmlWriter.WriteState;
public override void WriteString(string text)
=> _xmlWriter.WriteString(text);
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
=> _xmlWriter.WriteSurrogateCharEntity(lowChar, highChar);
public override void WriteWhitespace(string ws)
=> _xmlWriter.WriteWhitespace(ws);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using EnvDTE;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Interop;
#endif
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio.Resources;
namespace NuGet.VisualStudio
{
public class VsPackageManager : PackageManager, IVsPackageManager
{
private readonly ISharedPackageRepository _sharedRepository;
private readonly IDictionary<string, IProjectManager> _projects;
private readonly ISolutionManager _solutionManager;
protected readonly IFileSystemProvider _fileSystemProvider;
private readonly IDeleteOnRestartManager _deleteOnRestartManager;
private readonly VsPackageInstallerEvents _packageEvents;
private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting;
private bool _repositoryOperationPending;
public VsPackageManager(ISolutionManager solutionManager,
IPackageRepository sourceRepository,
IFileSystemProvider fileSystemProvider,
IFileSystem fileSystem,
ISharedPackageRepository sharedRepository,
IDeleteOnRestartManager deleteOnRestartManager,
VsPackageInstallerEvents packageEvents,
IVsFrameworkMultiTargeting frameworkMultiTargeting = null)
: base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository)
{
_solutionManager = solutionManager;
_sharedRepository = sharedRepository;
_packageEvents = packageEvents;
_fileSystemProvider = fileSystemProvider;
_deleteOnRestartManager = deleteOnRestartManager;
_frameworkMultiTargeting = frameworkMultiTargeting;
_projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase);
}
public ISolutionManager SolutionManager
{
get
{
return _solutionManager;
}
}
internal void EnsureCached(Project project)
{
string projectUniqueName = project.GetUniqueName();
if (_projects.ContainsKey(projectUniqueName))
{
return;
}
_projects[projectUniqueName] = CreateProjectManager(project);
}
public VsPackageInstallerEvents PackageEvents
{
get
{
return _packageEvents;
}
}
public virtual IProjectManager GetProjectManager(Project project)
{
EnsureCached(project);
IProjectManager projectManager;
bool projectExists = _projects.TryGetValue(project.GetUniqueName(), out projectManager);
Debug.Assert(projectExists, "Unknown project");
return projectManager;
}
private IProjectManager CreateProjectManager(Project project)
{
// Create the project system
IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider);
#if VS14
if (projectSystem is INuGetPackageManager)
{
var nugetAwareRepo = new NuGetAwareProjectPackageRepository((INuGetPackageManager)projectSystem, _sharedRepository);
return new ProjectManager(this, PathResolver, projectSystem, nugetAwareRepo);
}
#endif
PackageReferenceRepository repository = new PackageReferenceRepository(projectSystem, project.GetProperName(), _sharedRepository);
// Ensure the logger is null while registering the repository
FileSystem.Logger = null;
Logger = null;
// Ensure that this repository is registered with the shared repository if it needs to be
if (repository != null)
{
repository.RegisterIfNecessary();
}
var projectManager = new VsProjectManager(this, PathResolver, projectSystem, repository);
// The package reference repository also provides constraints for packages (via the allowedVersions attribute)
projectManager.ConstraintProvider = repository;
return projectManager;
}
protected override void ExecuteUninstall(IPackage package)
{
// Check if the package is in use before removing it
if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
base.ExecuteUninstall(package);
}
}
public IPackage FindLocalPackage(IProjectManager projectManager,
string packageId,
SemanticVersion version,
Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException)
{
IPackage package = null;
bool existsInProject = false;
bool appliesToProject = false;
if (projectManager != null)
{
// Try the project repository first
package = projectManager.LocalRepository.FindPackage(packageId, version);
existsInProject = package != null;
}
// Fallback to the solution repository (it might be a solution only package)
if (package == null)
{
if (version != null)
{
// Get the exact package
package = LocalRepository.FindPackage(packageId, version);
}
else
{
// Get all packages by this name to see if we find an ambiguous match
var packages = LocalRepository.FindPackagesById(packageId).ToList();
if (packages.Count > 1)
{
throw getAmbiguousMatchException(projectManager, packages);
}
// Pick the only one of default if none match
package = packages.SingleOrDefault();
}
}
// Can't find the package in the solution or in the project then fail
if (package == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
#if VS14
bool isNuGetAwareProjectSystem = (projectManager != null && projectManager.Project is NuGetAwareProjectSystem);
#else
bool isNuGetAwareProjectSystem = false;
#endif
appliesToProject = isNuGetAwareProjectSystem || IsProjectLevel(package);
if (appliesToProject)
{
if (!existsInProject)
{
if (_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If the package doesn't exist in the project and is referenced by other projects
// then fail.
if (projectManager != null)
{
if (version == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.Id,
projectManager.Project.ProjectName));
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.GetFullName(),
projectManager.Project.ProjectName));
}
}
else
{
// The operation applies to solution level since it's not installed in the current project
// but it is installed in some other project
appliesToProject = false;
}
}
}
// Can't have a project level operation if no project was specified
if (appliesToProject && projectManager == null)
{
throw new InvalidOperationException(VsResources.ProjectNotSpecified);
}
return package;
}
public IPackage FindLocalPackage(string packageId, out bool appliesToProject)
{
// It doesn't matter if there are multiple versions of the package installed at solution level,
// we just want to know that one exists.
var packages = LocalRepository.FindPackagesById(packageId).OrderByDescending(p => p.Version).ToList();
// Can't find the package in the solution.
if (!packages.Any())
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
foreach (IPackage package in packages)
{
appliesToProject = IsProjectLevel(package);
if (!appliesToProject)
{
if (packages.Count > 1)
{
throw CreateAmbiguousUpdateException(projectManager: null, packages: packages);
}
}
else if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture,
VsResources.Warning_PackageNotReferencedByAnyProject, package.Id, package.Version));
// Try next package
continue;
}
// Found a package with package Id as 'packageId' which is installed in at least 1 project
return package;
}
// There are one or more packages with package Id as 'packageId'
// BUT, none of them is installed in a project
// it's probably a borked install.
throw new PackageNotInstalledException(
String.Format(CultureInfo.CurrentCulture,
VsResources.PackageNotInstalledInAnyProject, packageId));
}
public Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUpdate,
packages[0].Id));
}
public Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousProjectLevelUninstal,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUninstall,
packages[0].Id));
}
public Project GetProject(IProjectManager projectManager)
{
// We only support project systems that implement IVsProjectSystem
var vsProjectSystem = projectManager.Project as IVsProjectSystem;
if (vsProjectSystem == null)
{
return null;
}
// Find the project by it's unique name
return _solutionManager.GetProject(vsProjectSystem.UniqueName);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")]
public override void AddBindingRedirects(IProjectManager projectManager)
{
// Find the project by it's unique name
Project project = GetProject(projectManager);
// If we can't find the project or it doesn't support binding redirects then don't add any redirects
if (project == null || !project.SupportsBindingRedirects())
{
return;
}
try
{
RuntimeHelpers.AddBindingRedirects(_solutionManager, project, _fileSystemProvider, _frameworkMultiTargeting);
}
catch (Exception e)
{
// If there was an error adding binding redirects then print a warning and continue
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message));
}
}
protected override void OnUninstalled(PackageOperationEventArgs e)
{
base.OnUninstalled(e);
PackageEvents.NotifyUninstalled(e);
_deleteOnRestartManager.MarkPackageDirectoryForDeletion(e.Package);
}
private IDisposable StartInstallOperation(string packageId, string packageVersion)
{
return StartOperation(RepositoryOperationNames.Install, packageId, packageVersion);
}
private IDisposable StartUpdateOperation(string packageId, string packageVersion)
{
return StartOperation(RepositoryOperationNames.Update, packageId, packageVersion);
}
private IDisposable StartReinstallOperation(string packageId, string packageVersion)
{
return StartOperation(RepositoryOperationNames.Reinstall, packageId, packageVersion);
}
private IDisposable StartOperation(string operation, string packageId, string mainPackageVersion)
{
// If there's a pending operation, don't allow another one to start.
// This is for the Reinstall case. Because Reinstall just means
// uninstalling and installing, we don't want the child install operation
// to override Reinstall value.
if (_repositoryOperationPending)
{
return DisposableAction.NoOp;
}
_repositoryOperationPending = true;
return DisposableAction.All(
SourceRepository.StartOperation(operation, packageId, mainPackageVersion),
new DisposableAction(() => _repositoryOperationPending = false));
}
protected override void OnInstalling(PackageOperationEventArgs e)
{
PackageEvents.NotifyInstalling(e);
base.OnInstalling(e);
}
protected override void OnInstalled(PackageOperationEventArgs e)
{
base.OnInstalled(e);
PackageEvents.NotifyInstalled(e);
}
protected override void OnUninstalling(PackageOperationEventArgs e)
{
PackageEvents.NotifyUninstalling(e);
base.OnUninstalling(e);
}
public override IPackage LocatePackageToUninstall(IProjectManager projectManager, string id, SemanticVersion version)
{
return FindLocalPackage(
projectManager,
id,
version,
CreateAmbiguousUninstallException);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.ServiceModel;
using System.Reflection;
namespace System.Collections.Generic
{
[System.Runtime.InteropServices.ComVisible(false)]
public class SynchronizedCollection<T> : IList<T>, IList
{
private List<T> _items;
private object _sync;
public SynchronizedCollection()
{
_items = new List<T>();
_sync = new Object();
}
public SynchronizedCollection(object syncRoot)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
_items = new List<T>();
_sync = syncRoot;
}
public SynchronizedCollection(object syncRoot, IEnumerable<T> list)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
if (list == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list"));
_items = new List<T>(list);
_sync = syncRoot;
}
public SynchronizedCollection(object syncRoot, params T[] list)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
if (list == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list"));
_items = new List<T>(list.Length);
for (int i = 0; i < list.Length; i++)
_items.Add(list[i]);
_sync = syncRoot;
}
public int Count
{
get { lock (_sync) { return _items.Count; } }
}
protected List<T> Items
{
get { return _items; }
}
public object SyncRoot
{
get { return _sync; }
}
public T this[int index]
{
get
{
lock (_sync)
{
return _items[index];
}
}
set
{
lock (_sync)
{
if (index < 0 || index >= _items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
SR.Format(SR.ValueMustBeInRange, 0, _items.Count - 1)));
this.SetItem(index, value);
}
}
}
public void Add(T item)
{
lock (_sync)
{
int index = _items.Count;
this.InsertItem(index, item);
}
}
public void Clear()
{
lock (_sync)
{
this.ClearItems();
}
}
public void CopyTo(T[] array, int index)
{
lock (_sync)
{
_items.CopyTo(array, index);
}
}
public bool Contains(T item)
{
lock (_sync)
{
return _items.Contains(item);
}
}
public IEnumerator<T> GetEnumerator()
{
lock (_sync)
{
return _items.GetEnumerator();
}
}
public int IndexOf(T item)
{
lock (_sync)
{
return this.InternalIndexOf(item);
}
}
public void Insert(int index, T item)
{
lock (_sync)
{
if (index < 0 || index > _items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
SR.Format(SR.ValueMustBeInRange, 0, _items.Count)));
this.InsertItem(index, item);
}
}
private int InternalIndexOf(T item)
{
int count = _items.Count;
for (int i = 0; i < count; i++)
{
if (object.Equals(_items[i], item))
{
return i;
}
}
return -1;
}
public bool Remove(T item)
{
lock (_sync)
{
int index = this.InternalIndexOf(item);
if (index < 0)
return false;
this.RemoveItem(index);
return true;
}
}
public void RemoveAt(int index)
{
lock (_sync)
{
if (index < 0 || index >= _items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
SR.Format(SR.ValueMustBeInRange, 0, _items.Count - 1)));
this.RemoveItem(index);
}
}
protected virtual void ClearItems()
{
_items.Clear();
}
protected virtual void InsertItem(int index, T item)
{
_items.Insert(index, item);
}
protected virtual void RemoveItem(int index)
{
_items.RemoveAt(index);
}
protected virtual void SetItem(int index, T item)
{
_items[index] = item;
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)_items).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get { return true; }
}
object ICollection.SyncRoot
{
get { return _sync; }
}
void ICollection.CopyTo(Array array, int index)
{
lock (_sync)
{
((IList)_items).CopyTo(array, index);
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
VerifyValueType(value);
this[index] = (T)value;
}
}
bool IList.IsReadOnly
{
get { return false; }
}
bool IList.IsFixedSize
{
get { return false; }
}
int IList.Add(object value)
{
VerifyValueType(value);
lock (_sync)
{
this.Add((T)value);
return this.Count - 1;
}
}
bool IList.Contains(object value)
{
VerifyValueType(value);
return this.Contains((T)value);
}
int IList.IndexOf(object value)
{
VerifyValueType(value);
return this.IndexOf((T)value);
}
void IList.Insert(int index, object value)
{
VerifyValueType(value);
this.Insert(index, (T)value);
}
void IList.Remove(object value)
{
VerifyValueType(value);
this.Remove((T)value);
}
private static void VerifyValueType(object value)
{
if (value == null)
{
if (typeof(T).GetTypeInfo().IsValueType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SynchronizedCollectionWrongTypeNull));
}
}
else if (!(value is T))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SynchronizedCollectionWrongType1, value.GetType().FullName)));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Base class for all value classes.
**
**
===========================================================*/
using System.Runtime;
using Internal.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Debug = System.Diagnostics.Debug;
namespace System
{
// CONTRACT with Runtime
// Place holder type for type hierarchy, Compiler/Runtime requires this class
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class ValueType
{
public override string ToString()
{
return this.GetType().ToString();
}
#if PROJECTN
public override bool Equals(object obj)
{
return RuntimeAugments.Callbacks.ValueTypeEqualsUsingReflection(this, obj);
}
public override int GetHashCode()
{
return RuntimeAugments.Callbacks.ValueTypeGetHashCodeUsingReflection(this);
}
#else
private const int UseFastHelper = -1;
private const int GetNumFields = -1;
// An override of this method will be injected by the compiler into all valuetypes that cannot be compared
// using a simple memory comparison.
// This API is a bit awkward because we want to avoid burning more than one vtable slot on this.
// When index == GetNumFields, this method is expected to return the number of fields of this
// valuetype. Otherwise, it returns the offset and type handle of the index-th field on this type.
internal virtual int __GetFieldHelper(int index, out EETypePtr eeType)
{
// Value types that don't override this method will use the fast path that looks at bytes, not fields.
Debug.Assert(index == GetNumFields);
eeType = default;
return UseFastHelper;
}
public override bool Equals(object obj)
{
if (obj == null || obj.EETypePtr != this.EETypePtr)
return false;
int numFields = __GetFieldHelper(GetNumFields, out _);
ref byte thisRawData = ref this.GetRawData();
ref byte thatRawData = ref obj.GetRawData();
if (numFields == UseFastHelper)
{
// Sanity check - if there are GC references, we should not be comparing bytes
Debug.Assert(!this.EETypePtr.HasPointers);
// Compare the memory
int valueTypeSize = (int)this.EETypePtr.ValueTypeSize;
for (int i = 0; i < valueTypeSize; i++)
{
if (Unsafe.Add(ref thisRawData, i) != Unsafe.Add(ref thatRawData, i))
return false;
}
}
else
{
// Foreach field, box and call the Equals method.
for (int i = 0; i < numFields; i++)
{
int fieldOffset = __GetFieldHelper(i, out EETypePtr fieldType);
// Fetch the value of the field on both types
object thisField = RuntimeImports.RhBoxAny(ref Unsafe.Add(ref thisRawData, fieldOffset), fieldType);
object thatField = RuntimeImports.RhBoxAny(ref Unsafe.Add(ref thatRawData, fieldOffset), fieldType);
// Compare the fields
if (thisField == null)
{
if (thatField != null)
return false;
}
else if (!thisField.Equals(thatField))
{
return false;
}
}
}
return true;
}
public override int GetHashCode()
{
int hashCode = this.EETypePtr.GetHashCode();
hashCode ^= GetHashCodeImpl();
return hashCode;
}
private int GetHashCodeImpl()
{
int numFields = __GetFieldHelper(GetNumFields, out _);
if (numFields == UseFastHelper)
return FastGetValueTypeHashCodeHelper(this.EETypePtr, ref this.GetRawData());
return RegularGetValueTypeHashCode(this.EETypePtr, ref this.GetRawData(), numFields);
}
private static int FastGetValueTypeHashCodeHelper(EETypePtr type, ref byte data)
{
// Sanity check - if there are GC references, we should not be hashing bytes
Debug.Assert(!type.HasPointers);
int size = (int)type.ValueTypeSize;
int hashCode = 0;
for (int i = 0; i < size / 4; i++)
{
hashCode ^= Unsafe.As<byte, int>(ref Unsafe.Add(ref data, i * 4));
}
return hashCode;
}
private int RegularGetValueTypeHashCode(EETypePtr type, ref byte data, int numFields)
{
int hashCode = 0;
// We only take the hashcode for the first non-null field. That's what the CLR does.
for (int i = 0; i < numFields; i++)
{
int fieldOffset = __GetFieldHelper(i, out EETypePtr fieldType);
ref byte fieldData = ref Unsafe.Add(ref data, fieldOffset);
Debug.Assert(!fieldType.IsPointer);
if (fieldType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4)
{
hashCode = Unsafe.Read<float>(ref fieldData).GetHashCode();
}
else if (fieldType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)
{
hashCode = Unsafe.Read<double>(ref fieldData).GetHashCode();
}
else if (fieldType.IsPrimitive)
{
hashCode = FastGetValueTypeHashCodeHelper(fieldType, ref fieldData);
}
else if (fieldType.IsValueType)
{
// We have no option but to box since this value type could have
// GC pointers (we could find out if we want though), or fields of type Double/Single (we can't
// really find out). Double/Single have weird requirements around -0.0 and +0.0.
// If this boxing becomes a problem, we could build a piece of infrastructure that determines the slot
// of __GetFieldHelper, decodes the unboxing stub pointed to by the slot to the real target
// (we already have that part), and calls the entrypoint that expects a byref `this`, and use the
// data to decide between calling fast or regular hashcode helper.
var fieldValue = (ValueType)RuntimeImports.RhBox(fieldType, ref fieldData);
hashCode = fieldValue.GetHashCodeImpl();
}
else
{
object fieldValue = Unsafe.Read<object>(ref fieldData);
if (fieldValue != null)
{
hashCode = fieldValue.GetHashCode();
}
else
{
// null object reference, try next
continue;
}
}
break;
}
return hashCode;
}
#endif
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitPeeringsOperations operations.
/// </summary>
public partial interface IExpressRouteCircuitPeeringsOperations
{
/// <summary>
/// Deletes the specified peering from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified express route
/// circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit
/// peering operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified peering from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified express route
/// circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit
/// peering operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
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 Injector.UI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.PhysicsModule.BasicPhysics
{
/// <summary>
/// This is an incomplete extremely basic physics implementation
/// </summary>
/// <remarks>
/// Not useful for anything at the moment apart from some regression testing in other components where some form
/// of physics plugin is needed.
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicPhysicsScene")]
public class BasicScene : PhysicsScene, INonSharedRegionModule
{
private List<BasicActor> _actors = new List<BasicActor>();
private List<BasicPhysicsPrim> _prims = new List<BasicPhysicsPrim>();
private float[] _heightMap;
private Vector3 m_regionExtent;
private bool m_Enabled = false;
//protected internal string sceneIdentifier;
#region INonSharedRegionModule
public string Name
{
get { return "basicphysics"; }
}
public string Version
{
get { return "1.0"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
// TODO: Move this out of Startup
IConfig config = source.Configs["Startup"];
if (config != null)
{
string physics = config.GetString("physics", string.Empty);
if (physics == Name)
m_Enabled = true;
}
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
EngineType = Name;
PhysicsSceneName = EngineType + "/" + scene.RegionInfo.RegionName;
EngineName = Name + " " + Version;
scene.RegisterModuleInterface<PhysicsScene>(this);
m_regionExtent = new Vector3(scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY, scene.RegionInfo.RegionSizeZ);
base.Initialise(scene.PhysicsRequestAsset,
(scene.Heightmap != null ? scene.Heightmap.GetFloatsSerialised() : new float[scene.RegionInfo.RegionSizeX * scene.RegionInfo.RegionSizeY]),
(float)scene.RegionInfo.RegionSettings.WaterHeight);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
#endregion
public override void Dispose() {}
public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, uint localid)
{
BasicPhysicsPrim prim = new BasicPhysicsPrim(primName, localid, position, size, rotation, pbs);
prim.IsPhysical = isPhysical;
_prims.Add(prim);
return prim;
}
public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying)
{
BasicActor act = new BasicActor(size);
act.Position = position;
act.Velocity = velocity;
act.Flying = isFlying;
_actors.Add(act);
return act;
}
public override void RemovePrim(PhysicsActor actor)
{
BasicPhysicsPrim prim = (BasicPhysicsPrim)actor;
if (_prims.Contains(prim))
_prims.Remove(prim);
}
public override void RemoveAvatar(PhysicsActor actor)
{
BasicActor act = (BasicActor)actor;
if (_actors.Contains(act))
_actors.Remove(act);
}
public override void AddPhysicsActorTaint(PhysicsActor prim)
{
}
public override float Simulate(float timeStep)
{
// Console.WriteLine("Simulating");
float fps = 1.0f / timeStep;
for (int i = 0; i < _actors.Count; ++i)
{
BasicActor actor = _actors[i];
Vector3 actorPosition = actor.Position;
Vector3 actorVelocity = actor.Velocity;
//Console.WriteLine(
// "Processing actor {0}, starting pos {1}, starting vel {2}", i, actorPosition, actorVelocity);
actorPosition.X += actor.Velocity.X * timeStep;
actorPosition.Y += actor.Velocity.Y * timeStep;
if (actor.Position.Y < 0)
{
actorPosition.Y = 0.1F;
}
else if (actor.Position.Y >= m_regionExtent.Y)
{
actorPosition.Y = (m_regionExtent.Y - 0.1f);
}
if (actor.Position.X < 0)
{
actorPosition.X = 0.1F;
}
else if (actor.Position.X >= m_regionExtent.X)
{
actorPosition.X = (m_regionExtent.X - 0.1f);
}
float terrainHeight = 0;
if (_heightMap != null)
terrainHeight = _heightMap[(int)actor.Position.Y * (int)m_regionExtent.Y + (int)actor.Position.X];
float height = terrainHeight + actor.Size.Z;
// Console.WriteLine("height {0}, actorPosition {1}", height, actorPosition);
if (actor.Flying)
{
if (actor.Position.Z + (actor.Velocity.Z * timeStep) < terrainHeight + 2)
{
actorPosition.Z = height;
actorVelocity.Z = 0;
actor.IsColliding = true;
}
else
{
actorPosition.Z += actor.Velocity.Z * timeStep;
actor.IsColliding = false;
}
}
else
{
actorPosition.Z = height;
actorVelocity.Z = 0;
actor.IsColliding = true;
}
actor.Position = actorPosition;
actor.Velocity = actorVelocity;
}
return fps;
}
public override void GetResults()
{
}
public override bool IsThreaded
{
get { return (false); // for now we won't be multithreaded
}
}
public override void SetTerrain(float[] heightMap)
{
_heightMap = heightMap;
}
public override void DeleteTerrain()
{
}
public override void SetWaterLevel(float baseheight)
{
}
public override Dictionary<uint, float> GetTopColliders()
{
Dictionary<uint, float> returncolliders = new Dictionary<uint, float>();
return returncolliders;
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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 UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if UNITY_2017_2_OR_NEWER
using InputTracking = UnityEngine.XR.InputTracking;
using Node = UnityEngine.XR.XRNode;
using NodeState = UnityEngine.XR.XRNodeState;
using Device = UnityEngine.XR.XRDevice;
#elif UNITY_2017_1_OR_NEWER
using InputTracking = UnityEngine.VR.InputTracking;
using Node = UnityEngine.VR.VRNode;
using NodeState = UnityEngine.VR.VRNodeState;
using Device = UnityEngine.VR.VRDevice;
#else
using InputTracking = UnityEngine.VR.InputTracking;
using Node = UnityEngine.VR.VRNode;
using Device = UnityEngine.VR.VRDevice;
#endif
/// <summary>
/// Miscellaneous extension methods that any script can use.
/// </summary>
public static class OVRExtensions
{
/// <summary>
/// Converts the given world-space transform to an OVRPose in tracking space.
/// </summary>
public static OVRPose ToTrackingSpacePose(this Transform transform, Camera camera)
{
OVRPose headPose;
headPose.position = InputTracking.GetLocalPosition(Node.Head);
headPose.orientation = InputTracking.GetLocalRotation(Node.Head);
var ret = headPose * transform.ToHeadSpacePose(camera);
return ret;
}
/// <summary>
/// Converts the given pose from tracking-space to world-space.
/// </summary>
public static OVRPose ToWorldSpacePose(OVRPose trackingSpacePose)
{
OVRPose headPose;
headPose.position = InputTracking.GetLocalPosition(Node.Head);
headPose.orientation = InputTracking.GetLocalRotation(Node.Head);
// Transform from tracking-Space to head-Space
OVRPose poseInHeadSpace = headPose.Inverse() * trackingSpacePose;
// Transform from head space to world space
OVRPose ret = Camera.main.transform.ToOVRPose() * poseInHeadSpace;
return ret;
}
/// <summary>
/// Converts the given world-space transform to an OVRPose in head space.
/// </summary>
public static OVRPose ToHeadSpacePose(this Transform transform, Camera camera)
{
return camera.transform.ToOVRPose().Inverse() * transform.ToOVRPose();
}
internal static OVRPose ToOVRPose(this Transform t, bool isLocal = false)
{
OVRPose pose;
pose.orientation = (isLocal) ? t.localRotation : t.rotation;
pose.position = (isLocal) ? t.localPosition : t.position;
return pose;
}
internal static void FromOVRPose(this Transform t, OVRPose pose, bool isLocal = false)
{
if (isLocal)
{
t.localRotation = pose.orientation;
t.localPosition = pose.position;
}
else
{
t.rotation = pose.orientation;
t.position = pose.position;
}
}
internal static OVRPose ToOVRPose(this OVRPlugin.Posef p)
{
return new OVRPose()
{
position = new Vector3(p.Position.x, p.Position.y, -p.Position.z),
orientation = new Quaternion(-p.Orientation.x, -p.Orientation.y, p.Orientation.z, p.Orientation.w)
};
}
internal static OVRTracker.Frustum ToFrustum(this OVRPlugin.Frustumf f)
{
return new OVRTracker.Frustum()
{
nearZ = f.zNear,
farZ = f.zFar,
fov = new Vector2()
{
x = Mathf.Rad2Deg * f.fovX,
y = Mathf.Rad2Deg * f.fovY
}
};
}
internal static Color FromColorf(this OVRPlugin.Colorf c)
{
return new Color() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static OVRPlugin.Colorf ToColorf(this Color c)
{
return new OVRPlugin.Colorf() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static Vector3 FromVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = v.z };
}
internal static Vector3 FromFlippedZVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = -v.z };
}
internal static OVRPlugin.Vector3f ToVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = v.z };
}
internal static OVRPlugin.Vector3f ToFlippedZVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = -v.z };
}
internal static Quaternion FromQuatf(this OVRPlugin.Quatf q)
{
return new Quaternion() { x = q.x, y = q.y, z = q.z, w = q.w };
}
internal static Quaternion FromFlippedZQuatf(this OVRPlugin.Quatf q)
{
return new Quaternion() { x = -q.x, y = -q.y, z = q.z, w = q.w };
}
internal static OVRPlugin.Quatf ToQuatf(this Quaternion q)
{
return new OVRPlugin.Quatf() { x = q.x, y = q.y, z = q.z, w = q.w };
}
internal static OVRPlugin.Quatf ToFlippedZQuatf(this Quaternion q)
{
return new OVRPlugin.Quatf() { x = -q.x, y = -q.y, z = q.z, w = q.w };
}
}
//4 types of node state properties that can be queried with UnityEngine.XR
public enum NodeStatePropertyType
{
Acceleration,
AngularAcceleration,
Velocity,
AngularVelocity,
}
public static class OVRNodeStateProperties
{
#if UNITY_2017_1_OR_NEWER
private static List<NodeState> nodeStateList = new List<NodeState>();
#endif
public static bool IsHmdPresent()
{
return Device.isPresent;
}
public static Vector3 GetNodeStateProperty(Node nodeType, NodeStatePropertyType propertyType, OVRPlugin.Node ovrpNodeType, OVRPlugin.Step stepType)
{
switch (propertyType)
{
case NodeStatePropertyType.Acceleration:
#if UNITY_2017_1_OR_NEWER
return GetUnityXRNodeState(nodeType, NodeStatePropertyType.Acceleration);
#else
return OVRPlugin.GetNodeAcceleration(ovrpNodeType, stepType).FromFlippedZVector3f();
#endif
case NodeStatePropertyType.AngularAcceleration:
#if UNITY_2017_2_OR_NEWER
return GetUnityXRNodeState(nodeType, NodeStatePropertyType.AngularAcceleration);
#else
return OVRPlugin.GetNodeAngularAcceleration(ovrpNodeType, stepType).FromFlippedZVector3f() * Mathf.Rad2Deg;
#endif
case NodeStatePropertyType.Velocity:
#if UNITY_2017_1_OR_NEWER
return GetUnityXRNodeState(nodeType, NodeStatePropertyType.Velocity);
#else
return OVRPlugin.GetNodeVelocity(ovrpNodeType, stepType).FromFlippedZVector3f();
#endif
case NodeStatePropertyType.AngularVelocity:
#if UNITY_2017_2_OR_NEWER
return GetUnityXRNodeState(nodeType, NodeStatePropertyType.AngularVelocity);
#else
return OVRPlugin.GetNodeAngularVelocity(ovrpNodeType, stepType).FromFlippedZVector3f() * Mathf.Rad2Deg;
#endif
}
return Vector3.zero;
}
#if UNITY_2017_1_OR_NEWER
private static Vector3 GetUnityXRNodeState(Node nodeType, NodeStatePropertyType propertyType)
{
InputTracking.GetNodeStates(nodeStateList);
if (nodeStateList.Count == 0)
return Vector3.zero;
bool nodeStateFound = false;
NodeState requestedNodeState = nodeStateList[0];
for (int i = 0; i < nodeStateList.Count; i++)
{
if (nodeStateList[i].nodeType == nodeType)
{
requestedNodeState = nodeStateList[i];
nodeStateFound = true;
break;
}
}
if (!nodeStateFound)
return Vector3.zero;
Vector3 retVec;
if (propertyType == NodeStatePropertyType.Acceleration)
{
if (requestedNodeState.TryGetAcceleration(out retVec))
{
return retVec;
}
}
else if (propertyType == NodeStatePropertyType.AngularAcceleration)
{
#if UNITY_2017_2_OR_NEWER
if (requestedNodeState.TryGetAngularAcceleration(out retVec))
{
retVec = retVec * Mathf.Rad2Deg;
return retVec;
}
#endif
}
else if (propertyType == NodeStatePropertyType.Velocity)
{
if (requestedNodeState.TryGetVelocity(out retVec))
{
return retVec;
}
}
else if (propertyType == NodeStatePropertyType.AngularVelocity)
{
#if UNITY_2017_2_OR_NEWER
if (requestedNodeState.TryGetAngularVelocity(out retVec))
{
retVec = retVec * Mathf.Rad2Deg;
return retVec;
}
#endif
}
return Vector3.zero;
}
#endif
}
/// <summary>
/// An affine transformation built from a Unity position and orientation.
/// </summary>
[System.Serializable]
public struct OVRPose
{
/// <summary>
/// A pose with no translation or rotation.
/// </summary>
public static OVRPose identity
{
get {
return new OVRPose()
{
position = Vector3.zero,
orientation = Quaternion.identity
};
}
}
public override bool Equals(System.Object obj)
{
return obj is OVRPose && this == (OVRPose)obj;
}
public override int GetHashCode()
{
return position.GetHashCode() ^ orientation.GetHashCode();
}
public static bool operator ==(OVRPose x, OVRPose y)
{
return x.position == y.position && x.orientation == y.orientation;
}
public static bool operator !=(OVRPose x, OVRPose y)
{
return !(x == y);
}
/// <summary>
/// The position.
/// </summary>
public Vector3 position;
/// <summary>
/// The orientation.
/// </summary>
public Quaternion orientation;
/// <summary>
/// Multiplies two poses.
/// </summary>
public static OVRPose operator*(OVRPose lhs, OVRPose rhs)
{
var ret = new OVRPose();
ret.position = lhs.position + lhs.orientation * rhs.position;
ret.orientation = lhs.orientation * rhs.orientation;
return ret;
}
/// <summary>
/// Computes the inverse of the given pose.
/// </summary>
public OVRPose Inverse()
{
OVRPose ret;
ret.orientation = Quaternion.Inverse(orientation);
ret.position = ret.orientation * -position;
return ret;
}
/// <summary>
/// Converts the pose from left- to right-handed or vice-versa.
/// </summary>
internal OVRPose flipZ()
{
var ret = this;
ret.position.z = -ret.position.z;
ret.orientation.z = -ret.orientation.z;
ret.orientation.w = -ret.orientation.w;
return ret;
}
internal OVRPlugin.Posef ToPosef()
{
return new OVRPlugin.Posef()
{
Position = position.ToVector3f(),
Orientation = orientation.ToQuatf()
};
}
}
/// <summary>
/// Encapsulates an 8-byte-aligned of unmanaged memory.
/// </summary>
public class OVRNativeBuffer : IDisposable
{
private bool disposed = false;
private int m_numBytes = 0;
private IntPtr m_ptr = IntPtr.Zero;
/// <summary>
/// Creates a buffer of the specified size.
/// </summary>
public OVRNativeBuffer(int numBytes)
{
Reallocate(numBytes);
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the <see cref="OVRNativeBuffer"/> is
/// reclaimed by garbage collection.
/// </summary>
~OVRNativeBuffer()
{
Dispose(false);
}
/// <summary>
/// Reallocates the buffer with the specified new size.
/// </summary>
public void Reset(int numBytes)
{
Reallocate(numBytes);
}
/// <summary>
/// The current number of bytes in the buffer.
/// </summary>
public int GetCapacity()
{
return m_numBytes;
}
/// <summary>
/// A pointer to the unmanaged memory in the buffer, starting at the given offset in bytes.
/// </summary>
public IntPtr GetPointer(int byteOffset = 0)
{
if (byteOffset < 0 || byteOffset >= m_numBytes)
return IntPtr.Zero;
return (byteOffset == 0) ? m_ptr : new IntPtr(m_ptr.ToInt64() + byteOffset);
}
/// <summary>
/// Releases all resource used by the <see cref="OVRNativeBuffer"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="OVRNativeBuffer"/>. The <see cref="Dispose"/>
/// method leaves the <see cref="OVRNativeBuffer"/> in an unusable state. After calling <see cref="Dispose"/>, you must
/// release all references to the <see cref="OVRNativeBuffer"/> so the garbage collector can reclaim the memory that
/// the <see cref="OVRNativeBuffer"/> was occupying.</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// dispose managed resources
}
// dispose unmanaged resources
Release();
disposed = true;
}
private void Reallocate(int numBytes)
{
Release();
if (numBytes > 0)
{
m_ptr = Marshal.AllocHGlobal(numBytes);
m_numBytes = numBytes;
}
else
{
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
private void Release()
{
if (m_ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_ptr);
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
}
| |
namespace android.graphics.drawable
{
[global::MonoJavaBridge.JavaClass()]
public partial class GradientDrawable : android.graphics.drawable.Drawable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected GradientDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Orientation : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Orientation(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::android.graphics.drawable.GradientDrawable.Orientation[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.graphics.drawable.GradientDrawable.Orientation._m0.native == global::System.IntPtr.Zero)
global::android.graphics.drawable.GradientDrawable.Orientation._m0 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "values", "()[Landroid/graphics/drawable/GradientDrawable/Orientation;");
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.drawable.GradientDrawable.Orientation>(@__env.CallStaticObjectMethod(android.graphics.drawable.GradientDrawable.Orientation.staticClass, global::android.graphics.drawable.GradientDrawable.Orientation._m0)) as android.graphics.drawable.GradientDrawable.Orientation[];
}
private static global::MonoJavaBridge.MethodId _m1;
public static global::android.graphics.drawable.GradientDrawable.Orientation valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.graphics.drawable.GradientDrawable.Orientation._m1.native == global::System.IntPtr.Zero)
global::android.graphics.drawable.GradientDrawable.Orientation._m1 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/drawable/GradientDrawable$Orientation;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.CallStaticObjectMethod(android.graphics.drawable.GradientDrawable.Orientation.staticClass, global::android.graphics.drawable.GradientDrawable.Orientation._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.GradientDrawable.Orientation;
}
internal static global::MonoJavaBridge.FieldId _BL_TR2422;
public static global::android.graphics.drawable.GradientDrawable.Orientation BL_TR
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _BL_TR2422)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _BOTTOM_TOP2423;
public static global::android.graphics.drawable.GradientDrawable.Orientation BOTTOM_TOP
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _BOTTOM_TOP2423)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _BR_TL2424;
public static global::android.graphics.drawable.GradientDrawable.Orientation BR_TL
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _BR_TL2424)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _LEFT_RIGHT2425;
public static global::android.graphics.drawable.GradientDrawable.Orientation LEFT_RIGHT
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _LEFT_RIGHT2425)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _RIGHT_LEFT2426;
public static global::android.graphics.drawable.GradientDrawable.Orientation RIGHT_LEFT
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _RIGHT_LEFT2426)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _TL_BR2427;
public static global::android.graphics.drawable.GradientDrawable.Orientation TL_BR
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _TL_BR2427)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _TOP_BOTTOM2428;
public static global::android.graphics.drawable.GradientDrawable.Orientation TOP_BOTTOM
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _TOP_BOTTOM2428)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
internal static global::MonoJavaBridge.FieldId _TR_BL2429;
public static global::android.graphics.drawable.GradientDrawable.Orientation TR_BL
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.drawable.GradientDrawable.Orientation>(@__env.GetStaticObjectField(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, _TR_BL2429)) as android.graphics.drawable.GradientDrawable.Orientation;
}
}
static Orientation()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.GradientDrawable.Orientation.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/GradientDrawable$Orientation"));
global::android.graphics.drawable.GradientDrawable.Orientation._BL_TR2422 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "BL_TR", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._BOTTOM_TOP2423 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "BOTTOM_TOP", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._BR_TL2424 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "BR_TL", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._LEFT_RIGHT2425 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "LEFT_RIGHT", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._RIGHT_LEFT2426 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "RIGHT_LEFT", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._TL_BR2427 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "TL_BR", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._TOP_BOTTOM2428 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "TOP_BOTTOM", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
global::android.graphics.drawable.GradientDrawable.Orientation._TR_BL2429 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.drawable.GradientDrawable.Orientation.staticClass, "TR_BL", "Landroid/graphics/drawable/GradientDrawable$Orientation;");
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual void setSize(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setSize", "(II)V", ref global::android.graphics.drawable.GradientDrawable._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m1;
public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V", ref global::android.graphics.drawable.GradientDrawable._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m2;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V", ref global::android.graphics.drawable.GradientDrawable._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int ChangingConfigurations
{
get
{
return getChangingConfigurations();
}
}
private static global::MonoJavaBridge.MethodId _m3;
public override int getChangingConfigurations()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "getChangingConfigurations", "()I", ref global::android.graphics.drawable.GradientDrawable._m3);
}
public new bool Dither
{
set
{
setDither(value);
}
}
private static global::MonoJavaBridge.MethodId _m4;
public override void setDither(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setDither", "(Z)V", ref global::android.graphics.drawable.GradientDrawable._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Alpha
{
set
{
setAlpha(value);
}
}
private static global::MonoJavaBridge.MethodId _m5;
public override void setAlpha(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setAlpha", "(I)V", ref global::android.graphics.drawable.GradientDrawable._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.graphics.ColorFilter ColorFilter
{
set
{
setColorFilter(value);
}
}
private static global::MonoJavaBridge.MethodId _m6;
public override void setColorFilter(android.graphics.ColorFilter arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V", ref global::android.graphics.drawable.GradientDrawable._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Opacity
{
get
{
return getOpacity();
}
}
private static global::MonoJavaBridge.MethodId _m7;
public override int getOpacity()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "getOpacity", "()I", ref global::android.graphics.drawable.GradientDrawable._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
protected override bool onLevelChange(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "onLevelChange", "(I)Z", ref global::android.graphics.drawable.GradientDrawable._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
protected override void onBoundsChange(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V", ref global::android.graphics.drawable.GradientDrawable._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int IntrinsicWidth
{
get
{
return getIntrinsicWidth();
}
}
private static global::MonoJavaBridge.MethodId _m10;
public override int getIntrinsicWidth()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "getIntrinsicWidth", "()I", ref global::android.graphics.drawable.GradientDrawable._m10);
}
public new int IntrinsicHeight
{
get
{
return getIntrinsicHeight();
}
}
private static global::MonoJavaBridge.MethodId _m11;
public override int getIntrinsicHeight()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "getIntrinsicHeight", "()I", ref global::android.graphics.drawable.GradientDrawable._m11);
}
private static global::MonoJavaBridge.MethodId _m12;
public override bool getPadding(android.graphics.Rect arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z", ref global::android.graphics.drawable.GradientDrawable._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public override global::android.graphics.drawable.Drawable mutate()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;", ref global::android.graphics.drawable.GradientDrawable._m13) as android.graphics.drawable.Drawable;
}
public new global::android.graphics.drawable.Drawable.ConstantState ConstantState
{
get
{
return getConstantState();
}
}
private static global::MonoJavaBridge.MethodId _m14;
public override global::android.graphics.drawable.Drawable.ConstantState getConstantState()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;", ref global::android.graphics.drawable.GradientDrawable._m14) as android.graphics.drawable.Drawable.ConstantState;
}
public new int Color
{
set
{
setColor(value);
}
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setColor(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setColor", "(I)V", ref global::android.graphics.drawable.GradientDrawable._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float[] CornerRadii
{
set
{
setCornerRadii(value);
}
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setCornerRadii(float[] arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setCornerRadii", "([F)V", ref global::android.graphics.drawable.GradientDrawable._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float CornerRadius
{
set
{
setCornerRadius(value);
}
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setCornerRadius(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setCornerRadius", "(F)V", ref global::android.graphics.drawable.GradientDrawable._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual void setStroke(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setStroke", "(II)V", ref global::android.graphics.drawable.GradientDrawable._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void setStroke(int arg0, int arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setStroke", "(IIFF)V", ref global::android.graphics.drawable.GradientDrawable._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
public new int Shape
{
set
{
setShape(value);
}
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setShape(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setShape", "(I)V", ref global::android.graphics.drawable.GradientDrawable._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int GradientType
{
set
{
setGradientType(value);
}
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void setGradientType(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setGradientType", "(I)V", ref global::android.graphics.drawable.GradientDrawable._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setGradientCenter(float arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setGradientCenter", "(FF)V", ref global::android.graphics.drawable.GradientDrawable._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new float GradientRadius
{
set
{
setGradientRadius(value);
}
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void setGradientRadius(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setGradientRadius", "(F)V", ref global::android.graphics.drawable.GradientDrawable._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new bool UseLevel
{
set
{
setUseLevel(value);
}
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual void setUseLevel(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.GradientDrawable.staticClass, "setUseLevel", "(Z)V", ref global::android.graphics.drawable.GradientDrawable._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation arg0, int[] arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.graphics.drawable.GradientDrawable._m25.native == global::System.IntPtr.Zero)
global::android.graphics.drawable.GradientDrawable._m25 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "<init>", "(Landroid/graphics/drawable/GradientDrawable$Orientation;[I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m26;
public GradientDrawable() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.graphics.drawable.GradientDrawable._m26.native == global::System.IntPtr.Zero)
global::android.graphics.drawable.GradientDrawable._m26 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.GradientDrawable.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.GradientDrawable.staticClass, global::android.graphics.drawable.GradientDrawable._m26);
Init(@__env, handle);
}
public static int RECTANGLE
{
get
{
return 0;
}
}
public static int OVAL
{
get
{
return 1;
}
}
public static int LINE
{
get
{
return 2;
}
}
public static int RING
{
get
{
return 3;
}
}
public static int LINEAR_GRADIENT
{
get
{
return 0;
}
}
public static int RADIAL_GRADIENT
{
get
{
return 1;
}
}
public static int SWEEP_GRADIENT
{
get
{
return 2;
}
}
static GradientDrawable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.GradientDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/GradientDrawable"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace FunctionalCSharp.Tests
{
using FunctionalCSharp.Extensions;
using FunctionalCSharp.Types;
using static FunctionalCSharp.Types.Option;
using static FunctionalCSharp.Extensions.GeneralExtensions;
using static FunctionalCSharp.Extensions.MaybeExtensions;
using HelperFSharp;
[Collection("PatternMatching")]
public class PatternMatchingTests
{
public int GetInt(object o)
=> (o is int i || (o is string s && int.TryParse(s, out i))) ? i: throw new ArgumentException(nameof(o));
[Fact]
public void TestIsExpressionsWithPatterns()
{
int i1 = GetInt(5);
int i2 = GetInt("23");
Assert.Equal(5, i1);
Assert.Equal(23, i2);
Assert.Throws<ArgumentException>(() => GetInt("Alex"));
Assert.Throws<ArgumentException>(() => GetInt(new {Name = "Alejandro", Age = 40}));
}
public class Circle
{
public double Radius { get; }
public Circle(double radius) => Radius = radius;
}
public class Rectangle
{
public double Height { get; }
public double Width { get; }
public Rectangle(double height, double width)
{
Height = height;
Width = width;
}
}
public double CalculateArea(object shape)
{
switch(shape)
{
case Circle c:
return Math.PI * c.Radius * c.Radius;
case Rectangle s when (s.Height == s.Width):
Console.WriteLine("This is a square!");
return s.Height * s.Height;
case Rectangle r:
return r.Height * r.Width;
case null:
throw new ArgumentNullException(nameof(shape));
default:
throw new ArgumentException("Unknown shape", nameof(shape));
}
}
[Fact]
public void TestSwitchStatementWithPatterns()
{
var circleArea = CalculateArea(new Circle(3.0));
var squareArea = CalculateArea(new Rectangle(2.0, 2.0));
var rectangleArea = CalculateArea(new Rectangle(3.0, 2.0));
Assert.Equal(Math.PI * 9.0, circleArea);
Assert.Equal(4, squareArea);
Assert.Equal(6, rectangleArea);
Assert.Throws<ArgumentNullException>(() => CalculateArea(null));
Assert.Throws<ArgumentException>(() => CalculateArea("some string"));
}
}
[Collection("RefactoringIntoPureFunctions")]
public class RefactoringIntoPureFunctionsTests
{
private string aMember = "StringOne";
public void HyphenatedConcat(string appendStr) => aMember += '-' + appendStr;
public void HyphenatedConcat(StringBuilder sb, string appendStr) => sb.Append('-' + appendStr);
public string HyphenatedConcat(string s, string appendStr) => $"{s}-{appendStr}";
[Fact]
public void TestImpureAndPureFunctions()
{
// Impure
HyphenatedConcat("StringTwo");
Assert.Equal("StringOne-StringTwo", aMember);
// Impure
var sb1 = new StringBuilder("StringOne");
HyphenatedConcat(sb1, "StringTwo");
Assert.Equal("StringOne-StringTwo", sb1.ToString());
// Pure
var s1 = "StringOne";
var s2 = HyphenatedConcat(s1, "StringTwo");
Assert.Equal("StringOne", s1);
Assert.Equal("StringOne-StringTwo", s2);
}
}
[Collection("BuildingImmutableTypes")]
public class BuildingImmutableTypesTests
{
public class ProductPile
{
public string ProductName { get; }
public int Amount { get; }
public decimal Price { get; }
public ProductPile(string productName, int amount, decimal price)
{
productName.Require(p => !string.IsNullOrWhiteSpace(p));
amount.Require(a => a >= 0);
price.Require(p => p > 0);
ProductName = productName;
Amount = amount;
Price = price;
}
public ProductPile SubtractOne()
=> new ProductPile(ProductName, Amount - 1, Price);
}
[Fact]
public void TestImmutability()
{
Assert.Throws<ArgumentException>(() => new ProductPile(null, 3, 13));
}
[Fact]
public void TestImmutabilityWithInvalidArgument()
{
var product = new ProductPile("Milk", 3, 13);
Assert.Equal(3, product.Amount);
var newProduct = product.SubtractOne();
Assert.Equal(3, product.Amount);
Assert.Equal(2, newProduct.Amount);
}
}
[Collection("ImmutableTypesOptions")]
public class ImmutableTypesOptionsTests
{
[Fact]
public void TestOption()
{
var optInt1 = new Option<int>(10);
var optInt2 = 10.ToOption();
var optInt3 = Some(10);
Assert.Equal(true, optInt1.IsSome);
Assert.Equal(10, optInt1.Value);
Assert.Equal(true, optInt1 == optInt2);
Assert.Equal(true, optInt2 == optInt3);
var optString1 = Some("test");
var optString2 = Some<string>(null);
Assert.Equal(true, optString1.IsSome);
Assert.Equal("test", optString1.Value);
Assert.Equal(true, optString2.IsSome);
Assert.Equal(null, optString2.Value);
optString1 = None;
Assert.Equal(true, optString1.IsNone);
}
}
[Collection("RecursionWithLambdas")]
public class RecursionWithLambdasTests
{
public IEnumerable<int> InfiniteNumbers()
{
for (int i = 0; true; i++)
{
Console.WriteLine($"Number is {i}");
yield return i;
}
}
[Fact]
public void TestRecursionWithLambdas()
{
var results = InfiniteNumbers().Take(10).Select(
num =>
{
Func<int, int> factorial = null;
factorial = n => n == 0 ? 1 : n * factorial(n - 1);
return factorial(num);
});
results.ForEach(result => Console.WriteLine($"Factorial is {result}"));
Assert.Equal(new[] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }, results.ToList());
}
}
[Collection("LazyEvaluation")]
public class LazyEvaluationTests
{
public Lazy<int> LazySum(Lazy<int> a, Lazy<int> b)
{
Console.WriteLine("LazySum");
return new Lazy<int>(() => { Console.WriteLine("a + b"); return a.Value + b.Value; });
}
[Fact]
public void TestLazyEvaluation()
{
var a = new Lazy<int>(() => { Console.WriteLine("a"); return 10 * 2; });
var b = new Lazy<int>(() => { Console.WriteLine("b"); return 5; });
var result = LazySum(a, b);
Console.WriteLine("Result:");
Console.WriteLine(result.Value);
Assert.Equal(25, result.Value);
}
}
[Collection("PartialFunctions")]
public class PartialFunctionsTests
{
public double Distance(double x, double y, double z) => Math.Sqrt(x * x + y * y + z * z);
[Fact]
public void TestPartialFunctions()
{
Func<double, double, double, double> distance3D = Distance;
Func<double, double, double> distance2D = distance3D.SetDefaultArgument(0);
var d1 = distance2D(3, 6); // distance3D(3, 6, 0);
var d2 = distance2D(3, 4); // distance3D(3, 4, 0);
var d3 = distance2D(1, 2); // distance3D(1, 2, 0);
Assert.Equal(6.7082039324993694, d1);
Assert.Equal(5, d2);
Assert.Equal(2.23606797749979, d3);
}
}
[Collection("CurryFunctions")]
public class CurryFunctionsTests
{
public double Distance(double x, double y, double z) => Math.Sqrt(x * x + y * y + z * z);
[Fact]
public void TestCurryFunction()
{
Func<double, double, double, double> distance3D = Distance;
var curriedDistance = distance3D.Curry();
var d = curriedDistance(3)(4)(12);
Assert.Equal(13, d);
}
}
[Collection("UncurryFunctions")]
public class UncurryFunctionsTests
{
public double Distance(double x, double y, double z) => Math.Sqrt(x * x + y * y + z * z);
[Fact]
public void TestUnCurryFunction()
{
Func<double, double, double, double> distance3D = Distance;
var curriedDistance = distance3D.Curry();
Func<double, double, double, double> originalDistance = curriedDistance.UnCurry();
Assert.Equal(13, curriedDistance(3)(4)(12));
Assert.Equal(13, originalDistance(3, 4, 12));
}
}
[Collection("Composition")]
public class CompositionTests
{
public Func<X, Z> Compose<X, Y, Z>(Func<X, Y> f, Func<Y, Z> g)
{
return (x) => g(f(x));
}
[Fact]
public void TestComposition()
{
Func<int, int> calcBwithA = a => a * 3;
Func<int, int> calcCwithB = b => b + 27;
var calcCWithA = Compose(calcBwithA, calcCwithB);
Assert.Equal(39, calcCWithA(4));
// or...
calcCWithA = calcBwithA.Compose(calcCwithB);
Assert.Equal(39, calcCWithA(4));
}
}
[Collection("Map")]
public class MapTests
{
[Fact]
public void TestMap()
{
var people = new List<dynamic> {
new {Name = "Harry", Age = 32},
new {Name = "Anna", Age = 45},
new {Name = "Willy", Age = 43},
new {Name = "Rose", Age = 37}
};
people.Map(p => p.Name).ForEach(Console.WriteLine);
Console.WriteLine("Same thing with LinQ:");
people.Select(p => p.Name).ForEach(Console.WriteLine);
}
}
[Collection("Filter")]
public class FilterTests
{
[Fact]
public void TestFilter()
{
var people = new List<dynamic> {
new {Name = "Harry", Age = 32},
new {Name = "Anna", Age = 45},
new {Name = "Willy", Age = 43},
new {Name = "Rose", Age = 37}
};
people.Filter(p => p.Age > 40).ForEach(Console.WriteLine);
Console.WriteLine("Same thing with LinQ:");
people.Where(p => p.Age > 40).ForEach(Console.WriteLine);
}
}
[Collection("FoldLeft")]
public class FoldLeftTests
{
[Fact]
public void TestFoldLeft()
{
var sumOf1to10 = Enumerable.Range(1, 10).FoldLeft("0", (acc, value) => $"({acc}+{value})");
Assert.Equal("((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)", sumOf1to10);
var people = new List<dynamic> {
new {Name = "Harry", Age = 32},
new {Name = "Anna", Age = 45},
new {Name = "Willy", Age = 43},
new {Name = "Rose", Age = 37}
};
var result = people.FoldLeft(
(totalAge: 0, count: 0),
(acc, value) => (acc.totalAge + value.Age, acc.count + 1));
var averageAge = result.totalAge / result.count;
Assert.Equal(39, averageAge);
// Same thing with LinQ
sumOf1to10 = Enumerable.Range(1, 10).Aggregate("0", (acc, value) => $"({acc}+{value})");
Assert.Equal("((((((((((0+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)", sumOf1to10);
result = people.Aggregate(
(totalAge: 0, count: 0),
(acc, value) => (acc.totalAge + value.Age, acc.count + 1));
averageAge = result.totalAge / result.count;
Assert.Equal(39, averageAge);
}
}
[Collection("FoldRight")]
public class FoldRightTests
{
[Fact]
public void TestFoldRight()
{
var sumOf1to10 = Enumerable.Range(1, 10).FoldRight("0", (value, acc) => $"({value}+{acc})");
Assert.Equal("(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+0))))))))))", sumOf1to10);
var people = new List<dynamic> {
new {Name = "Harry", Age = 32},
new {Name = "Anna", Age = 45},
new {Name = "Willy", Age = 43},
new {Name = "Rose", Age = 37}
};
var result = people.FoldRight(
(totalAge: 0, count: 0),
(value, acc) => (value.Age + acc.totalAge, 1 + acc.count));
var averageAge = result.totalAge / result.count;
Assert.Equal(39, averageAge);
// In LinQ, Aggregate is a left folding operator
sumOf1to10 =
Enumerable.Range(1, 10).
Aggregate<int, Func<string, string>>(x => x, (f, value) => acc => f($"({value}+{acc})"))("0");
Assert.Equal("(1+(2+(3+(4+(5+(6+(7+(8+(9+(10+0))))))))))", sumOf1to10);
result =
people.
Aggregate<dynamic, Func<(int totalAge, int count), (int, int)>>(
x => x,
(f, value) => acc => f((value.Age + acc.totalAge, 1 + acc.count)))((totalAge: 0, count: 0));
averageAge = result.totalAge / result.count;
Assert.Equal(39, averageAge);
}
}
[Collection("Memoization")]
public class MemoizationTests
{
[Fact]
public void TestMemoization()
{
Func<long, long> fib = null;
fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
var res = MeasureTime(() => fib(40));
Assert.Equal(102334155, res.result);
Console.WriteLine($"Standard version took {res.time} milliseconds");
fib = fib.Memoize();
res = MeasureTime(() => fib(40));
Assert.Equal(102334155, res.result);
Console.WriteLine($"Memoized version took {res.time} milliseconds");
}
}
[Collection("Monads")]
public class MonadsTests
{
public Maybe<int> Add4(int x) => (x + 4).ToMaybe();
public Maybe<int> MultBy2(int x) => (x * 2).ToMaybe();
public Maybe<int> JustFail(int x) => new Nothing<int>();
[Fact]
public void TestMaybeMonad()
{
var result = 3.ToMaybe().Bind(Add4).Bind(MultBy2);
Assert.Equal("14", result.ToString());
result = 3.ToMaybe().Bind(Add4).Bind(JustFail).Bind(MultBy2);
Assert.Equal("Nothing", result.ToString());
}
public Maybe<int> DoSomeDivision(int denominator)
=> from a in 12.Div(denominator)
from b in a.Div(2)
select b;
[Fact]
public void TestMaybeMonadWithLinQ()
{
var result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(2)
from c in (new DateTime(2016, 2, 24)).ToMaybe()
select $"{a} {b} {c.ToShortDateString()}";
Assert.Equal("Hello World! 3 24/02/2016", result.ToString());
result = from a in "Hello World!".ToMaybe()
from b in DoSomeDivision(0)
from c in (new DateTime(2016, 2, 24)).ToMaybe()
select $"{a} {b} {c.ToShortDateString()}";
Assert.Equal("Nothing", result.ToString());
}
}
[Collection("CSharpAndFSharpInterop")]
public class CSharpAndFSharpInteropTests
{
[Fact]
public void TestDiscriminatedUnionsWithPatternMatching()
{
var shapes = new List<Shape>
{
Shape.NewCircle(15.0),
Shape.NewSquare(10.0),
Shape.NewRectangle(5.0, 10.0),
Shape.NewEquilateralTriangle(10.0)
};
var areas = shapes.Select(s => s.Area()).ToArray();
Assert.Equal(new[] { 706.85834715, 100, 50, 43.301270189221924 }, areas);
}
}
[Collection("ImperativeVSFunctionalStyle")]
public class ImperativeVSFunctionalStyleTests
{
private void NonFunctionalExample(string text)
{
using (StringReader rdr = new StringReader(text))
{
string contents = rdr.ReadToEnd();
string[] words = contents.Split(' ');
for (int i = 0; i < words.Length; i++)
{
words[i] = words[i].Trim();
}
Dictionary<string, int> d = new Dictionary<string, int>();
foreach (string word in words)
{
if (d.ContainsKey(word))
{
d[word]++;
}
else
{
d.Add(word, 1);
}
}
foreach (KeyValuePair<string, int> kvp in d)
{
Console.WriteLine(string.Format("({0}, {1})", kvp.Key, kvp.Value.ToString()));
}
}
}
private void FunctionalExample(string text)
=> new StringReader(text).Use(stream => stream
.ReadToEnd()
.Split(' ')
.Select(str => str.Trim())
.GroupBy(str => str)
.Select(group => $"({group.Key}, {group.Count()})")
.ForEach(Console.WriteLine));
[Fact]
public void Test()
{
Console.WriteLine("NON FUNCTIONAL SAMPLE:");
NonFunctionalExample("En un lugar de la mancha de cuyo nombre no puedo acordarme");
Console.WriteLine("FUNCTIONAL SAMPLE:");
FunctionalExample("En un lugar de la mancha de cuyo nombre no puedo acordarme");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading.Tasks;
using AdventureWorks.UILogic.Models;
using AdventureWorks.UILogic.Repositories;
using AdventureWorks.UILogic.Tests.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AdventureWorks.UILogic.Tests.Repositories
{
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
[TestClass]
public class ProductCatalogRepositoryFixture
{
[TestMethod]
public async Task GetCategories_Calls_Service_When_Cache_Miss()
{
var cacheService = new MockCacheService
{
GetDataDelegate = s => { throw new FileNotFoundException(); },
SaveDataAsyncDelegate =
(s, c) => Task.FromResult(new Uri("http://test.org"))
};
var productCatalogService = new MockProductCatalogService();
var categories = new List<Category> { new Category { Id = 1 }, new Category { Id = 2 } };
productCatalogService.GetSubcategoriesAsyncDelegate =
(parentId, maxProducts) =>
Task.FromResult((ICollection<Category>)(new Collection<Category>(categories)));
var target = new ProductCatalogRepository(productCatalogService, cacheService);
var returnedCategories = (await target.GetRootCategoriesAsync(0)).ToList();
Assert.AreEqual(2, returnedCategories.Count);
Assert.AreEqual(1, returnedCategories[0].Id);
Assert.AreEqual(2, returnedCategories[1].Id);
}
[TestMethod]
public async Task GetCategories_Uses_Cache_When_Data_Available()
{
var cacheService = new MockCacheService();
// cacheService.DataExistsAndIsValidAsyncDelegate = s => Task.FromResult(true);
var categories = new List<Category>
{
new Category{ Id = 1},
new Category{ Id = 2}
};
cacheService.GetDataDelegate = (string s) =>
{
if (s == "Categories-0-0")
return new ReadOnlyCollection<Category>(categories);
return new ReadOnlyCollection<Category>(null);
};
var productCatalogService = new MockProductCatalogService
{
GetSubcategoriesAsyncDelegate =
(parentId, maxProducts) =>
Task.FromResult<ICollection<Category>>(
new Collection<Category>(null))
};
var target = new ProductCatalogRepository(productCatalogService, cacheService);
var returnedCategories = (await target.GetRootCategoriesAsync(0)).ToList();
Assert.AreEqual(2, returnedCategories.Count);
Assert.AreEqual(1, returnedCategories[0].Id);
Assert.AreEqual(2, returnedCategories[1].Id);
}
[TestMethod]
public async Task GetCategories_Saves_Data_To_Cache()
{
var cacheService = new MockCacheService
{
GetDataDelegate = s => { throw new FileNotFoundException(); },
SaveDataAsyncDelegate = (s, o) =>
{
var collection = (Collection<Category>)o;
Assert.AreEqual("Categories-0-0", s);
Assert.AreEqual(2, collection.Count);
Assert.AreEqual(1, collection[0].Id);
Assert.AreEqual(2, collection[1].Id);
return Task.FromResult(new Uri("http://test.org"));
}
};
var productCatalogService = new MockProductCatalogService();
var categories = new List<Category>
{
new Category{ Id = 1},
new Category{ Id = 2}
};
productCatalogService.GetSubcategoriesAsyncDelegate =
(parentId, maxProducts) => Task.FromResult<ICollection<Category>>(new Collection<Category>(categories));
var target = new ProductCatalogRepository(productCatalogService, cacheService);
await target.GetRootCategoriesAsync(0);
}
[TestMethod]
public async Task GetSubcategories_Calls_Service_When_Cache_Miss()
{
var cacheService = new MockCacheService();
cacheService.GetDataDelegate = s => { throw new FileNotFoundException(); };
cacheService.SaveDataAsyncDelegate = (s, c) => Task.FromResult(new Uri("http://test.org"));
var productCatalogService = new MockProductCatalogService();
var subCategories = new List<Category>
{
new Category{ Id = 10},
new Category{ Id = 11}
};
productCatalogService.GetSubcategoriesAsyncDelegate =
(parentId, maxProducts) =>
Task.FromResult<ICollection<Category>>(new Collection<Category>(subCategories));
var target = new ProductCatalogRepository(productCatalogService, cacheService);
var returnedSubcategories = (await target.GetSubcategoriesAsync(1, 10)).ToList();
Assert.AreEqual(2, returnedSubcategories.Count);
Assert.AreEqual(10, returnedSubcategories[0].Id);
Assert.AreEqual(11, returnedSubcategories[1].Id);
}
[TestMethod]
public async Task GetSubcategories_Uses_Cache_When_Data_Available()
{
var cacheService = new MockCacheService();
var categories = new List<Category>
{
new Category{ Id = 10},
new Category{ Id = 11}
};
cacheService.GetDataDelegate = s =>
{
if (s == "Categories-1-10")
return new ReadOnlyCollection<Category>(categories);
return new ReadOnlyCollection<Category>(null);
};
var productCatalogService = new MockProductCatalogService();
productCatalogService.GetSubcategoriesAsyncDelegate =
(parentId, maxProducts) => Task.FromResult<ICollection<Category>>(new Collection<Category>(null));
var target = new ProductCatalogRepository(productCatalogService, cacheService);
var returnedCategories = (await target.GetSubcategoriesAsync(1, 10)).ToList();
Assert.AreEqual(2, returnedCategories.Count);
Assert.AreEqual(10, returnedCategories[0].Id);
Assert.AreEqual(11, returnedCategories[1].Id);
}
[TestMethod]
public async Task GetSubcategories_Saves_Data_To_Cache()
{
var cacheService = new MockCacheService();
cacheService.GetDataDelegate = s => { throw new FileNotFoundException(); };
cacheService.SaveDataAsyncDelegate = (s, o) =>
{
var collection = (Collection<Category>)o;
Assert.AreEqual("Categories-1-10", s);
Assert.AreEqual(2, collection.Count);
Assert.AreEqual(10, collection[0].Id);
Assert.AreEqual(11, collection[1].Id);
return Task.FromResult(new Uri("http://test.org"));
};
var productCatalogService = new MockProductCatalogService();
var subCategories = new List<Category>
{
new Category{ Id = 10},
new Category{ Id = 11}
};
productCatalogService.GetSubcategoriesAsyncDelegate =
(parentId, maxProducts) =>
Task.FromResult<ICollection<Category>>(new Collection<Category>(subCategories));
var target = new ProductCatalogRepository(productCatalogService, cacheService);
await target.GetSubcategoriesAsync(1,10);
}
}
}
| |
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.SqlUtils;
namespace Orleans.Runtime.MembershipService
{
internal class SqlMembershipTable: IMembershipTable, IGatewayListProvider
{
private string deploymentId;
private TimeSpan maxStaleness;
private Logger logger;
private RelationalOrleansQueries orleansQueries;
public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitTableVersion, Logger traceLogger)
{
logger = traceLogger;
deploymentId = config.DeploymentId;
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.InitializeMembershipTable called.");
//This initializes all of Orleans operational queries from the database using a well known view
//and assumes the database with appropriate defintions exists already.
orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);
// even if I am not the one who created the table,
// try to insert an initial table version if it is not already there,
// so we always have a first table version row, before this silo starts working.
if(tryInitTableVersion)
{
var wasCreated = await InitTableAsync();
if(wasCreated)
{
logger.Info("Created new table version row.");
}
}
}
public async Task InitializeGatewayListProvider(ClientConfiguration config, Logger traceLogger)
{
logger = traceLogger;
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.InitializeGatewayListProvider called.");
deploymentId = config.DeploymentId;
maxStaleness = config.GatewayListRefreshPeriod;
orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);
}
public TimeSpan MaxStaleness
{
get { return maxStaleness; }
}
public bool IsUpdatable
{
get { return true; }
}
public async Task<IList<Uri>> GetGateways()
{
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.GetGateways called.");
try
{
return await orleansQueries.ActiveGatewaysAsync(deploymentId);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.Gateways failed {0}", ex);
throw;
}
}
public async Task<MembershipTableData> ReadRow(SiloAddress key)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("SqlMembershipTable.ReadRow called with key: {0}.", key));
try
{
return await orleansQueries.MembershipReadRowAsync(deploymentId, key);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.ReadRow failed: {0}", ex);
throw;
}
}
public async Task<MembershipTableData> ReadAll()
{
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.ReadAll called.");
try
{
return await orleansQueries.MembershipReadAllAsync(deploymentId);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.ReadAll failed: {0}", ex);
throw;
}
}
public async Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("SqlMembershipTable.InsertRow called with entry {0} and tableVersion {1}.", entry, tableVersion));
//The "tableVersion" parameter should always exist when inserting a row as Init should
//have been called and membership version created and read. This is an optimization to
//not to go through all the way to database to fail a conditional check on etag (which does
//exist for the sake of robustness) as mandated by Orleans membership protocol.
//Likewise, no update can be done without membership entry.
if (entry == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.InsertRow aborted due to null check. MembershipEntry is null.");
throw new ArgumentNullException("entry");
}
if (tableVersion == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.InsertRow aborted due to null check. TableVersion is null ");
throw new ArgumentNullException("tableVersion");
}
try
{
return await orleansQueries.InsertMembershipRowAsync(deploymentId, entry, tableVersion.VersionEtag);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.InsertRow failed: {0}", ex);
throw;
}
}
public async Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("IMembershipTable.UpdateRow called with entry {0}, etag {1} and tableVersion {2}.", entry, etag, tableVersion));
//The "tableVersion" parameter should always exist when updating a row as Init should
//have been called and membership version created and read. This is an optimization to
//not to go through all the way to database to fail a conditional check (which does
//exist for the sake of robustness) as mandated by Orleans membership protocol.
//Likewise, no update can be done without membership entry or an etag.
if (entry == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateRow aborted due to null check. MembershipEntry is null.");
throw new ArgumentNullException("entry");
}
if (tableVersion == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateRow aborted due to null check. TableVersion is null ");
throw new ArgumentNullException("tableVersion");
}
try
{
return await orleansQueries.UpdateMembershipRowAsync(deploymentId, entry, tableVersion.VersionEtag);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateRow failed: {0}", ex);
throw;
}
}
public async Task UpdateIAmAlive(MembershipEntry entry)
{
if(logger.IsVerbose3) logger.Verbose3(string.Format("IMembershipTable.UpdateIAmAlive called with entry {0}.", entry));
if (entry == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateIAmAlive aborted due to null check. MembershipEntry is null.");
throw new ArgumentNullException("entry");
}
try
{
await orleansQueries.UpdateIAmAliveTimeAsync(deploymentId, entry.SiloAddress, entry.IAmAliveTime);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateIAmAlive failed: {0}", ex);
throw;
}
}
public async Task DeleteMembershipTableEntries(string deploymentId)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("IMembershipTable.DeleteMembershipTableEntries called with deploymentId {0}.", deploymentId));
try
{
await orleansQueries.DeleteMembershipTableEntriesAsync(deploymentId);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.DeleteMembershipTableEntries failed: {0}", ex);
throw;
}
}
private async Task<bool> InitTableAsync()
{
try
{
return await orleansQueries.InsertMembershipVersionRowAsync(deploymentId);
}
catch(Exception ex)
{
if(logger.IsVerbose2) logger.Verbose2("Insert silo membership version failed: {0}", ex.ToString());
throw;
}
}
}
}
| |
// CRC32.cs - Computes CRC32 data checksum of a data stream
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace Orvid.Compression.Checksums
{
/// <summary>
/// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
/// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
///
/// Polynomials over GF(2) are represented in binary, one bit per coefficient,
/// with the lowest powers in the most significant bit. Then adding polynomials
/// is just exclusive-or, and multiplying a polynomial by x is a right shift by
/// one. If we call the above polynomial p, and represent a byte as the
/// polynomial q, also with the lowest power in the most significant bit (so the
/// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
/// where a mod b means the remainder after dividing a by b.
///
/// This calculation is done using the shift-register method of multiplying and
/// taking the remainder. The register is initialized to zero, and for each
/// incoming bit, x^32 is added mod p to the register if the bit is a one (where
/// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
/// x (which is shifting right by one and adding x^32 mod p if the bit shifted
/// out is a one). We start with the highest power (least significant bit) of
/// q and repeat for all eight bits of q.
///
/// The table is simply the CRC of all possible eight bit values. This is all
/// the information needed to generate CRC's on data a byte at a time for all
/// combinations of CRC register values and incoming bytes.
/// </summary>
public sealed class Crc32
{
const uint CrcSeed = 0xFFFFFFFF;
readonly static uint[] CrcTable = new uint[] {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
0x2D02EF8D
};
internal static uint ComputeCrc32(uint oldCrc, byte value)
{
return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8));
}
/// <summary>
/// The crc data checksum so far.
/// </summary>
uint crc;
/// <summary>
/// Returns the CRC32 data checksum computed so far.
/// </summary>
public long Value {
get {
return (long)crc;
}
set {
crc = (uint)value;
}
}
/// <summary>
/// Resets the CRC32 data checksum as if no update was ever called.
/// </summary>
public void Reset()
{
crc = 0;
}
/// <summary>
/// Updates the checksum with the int bval.
/// </summary>
/// <param name = "value">
/// the byte is taken as the lower 8 bits of value
/// </param>
public void Update(int value)
{
crc ^= CrcSeed;
crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8);
crc ^= CrcSeed;
}
/// <summary>
/// Updates the checksum with the bytes taken from the array.
/// </summary>
/// <param name="buffer">
/// buffer an array of bytes
/// </param>
public void Update(byte[] buffer)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Adds the byte array to the data checksum.
/// </summary>
/// <param name = "buffer">
/// The buffer which contains the data
/// </param>
/// <param name = "offset">
/// The offset in the buffer where the data starts
/// </param>
/// <param name = "count">
/// The number of data bytes to update the CRC with.
/// </param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if ( count < 0 ) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero");
#endif
}
if (offset < 0 || offset + count > buffer.Length) {
throw new ArgumentOutOfRangeException("offset");
}
crc ^= CrcSeed;
while (--count >= 0) {
crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8);
}
crc ^= CrcSeed;
}
}
}
| |
//
// VideoStreamTile.cs
//
// Author:
// Kevin Duffus <KevinDuffus@gmail.com>
//
// Copyright (C) 2009 Kevin Duffus
//
// 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 Mono.Unix;
using Gtk;
using Banshee.Base;
using Banshee.Web;
using Banshee.Collection;
using Banshee.ServiceStack;
using Hyena;
using Hyena.Widgets;
/*
Tile layout:
+===========================+====+
| +-------+ | |
| | | Primary Text | |
| | Image | Secondary Text | \/ |
| | | * * * * * | |
| +-------+ | |
+===========================+----+
| Play in Banshee... |
| Play in Web Browser... |
|------------------------|
| Add to Play Queue... |
| Import video... |
+------------------------+
*/
namespace Banshee.YouTube.Gui
{
public class VideoStreamTile : MenuButton
{
private Button button = new Button ();
private Menu menu = new Menu ();
private ActionGroup action_group;
private TrackInfo track_info;
private HBox hbox = new HBox ();
private VBox vbox = new VBox ();
private Image image = new Image ();
private Label primary_label = new Label ();
private Label secondary_label = new Label ();
private RatingEntry rating = new RatingEntry ();
private string video_title;
private string video_uploader;
private string primary_text;
private string secondary_text;
public VideoStreamTile ()
{
hbox.BorderWidth = 2;
hbox.Spacing = 6;
vbox.PackStart (primary_label, true, true, 0);
vbox.PackStart (secondary_label, true, true, 0);
vbox.PackStart (rating, true, true, 0);
hbox.PackStart (image, true, true, 0);
hbox.PackStart (vbox, true, false, 0);
hbox.ShowAll ();
button.Add (hbox);
button.Clicked += new EventHandler (OnButtonClicked);
primary_label.WidthChars = 24;
secondary_label.WidthChars = 24;
primary_label.Ellipsize = Pango.EllipsizeMode.End;
secondary_label.Ellipsize = Pango.EllipsizeMode.End;
rating.Sensitive = false;
rating.HasFrame = false;
rating.AlwaysShowEmptyStars = true;
try {
StyleSet += delegate {
primary_label.ModifyFg (StateType.Normal, Style.Text (StateType.Normal));
secondary_label.ModifyFg (StateType.Normal, Hyena.Gui.GtkUtilities.ColorBlend (
Style.Foreground (StateType.Normal), Style.Background (StateType.Normal)));
};
} catch (Exception e) {
Log.DebugException (e);
}
button.Relief = ReliefStyle.None;
ConstructTile ();
}
public string BansheePlaybackUri { get; set; }
public string BrowserPlaybackUri { get; set; }
public string Title {
get { return primary_text; }
set {
video_title = value;
primary_text = video_title;
primary_label.Text = video_title;
}
}
public string Uploader {
get { return secondary_text; }
set {
video_uploader = value;
secondary_text = video_uploader;
secondary_label.Markup = String.Format ("<small>{0} {1}</small>",
Catalog.GetString ("Uploaded by"),
GLib.Markup.EscapeText (video_uploader));
}
}
public Gdk.Pixbuf Pixbuf {
get { return image.Pixbuf; }
set {
if (value == null) {
return;
}
image.Pixbuf = value;
}
}
public int RatingValue {
get { return rating.Value; }
set { rating.Value = value; }
}
public new Menu Menu {
get { return menu; }
set { menu = value; }
}
public void AppendMenuItem (Widget menu_item)
{
menu.Append (menu_item);
}
private Menu CreateMenu ()
{
bool separator = false;
foreach (Gtk.Action action in action_group.ListActions ()) {
AppendMenuItem (action.CreateMenuItem ());
if (!separator) {
separator = true;
AppendMenuItem (new SeparatorMenuItem ());
}
}
menu.ShowAll ();
return menu;
}
private void SetTrackInfo ()
{
if (track_info == null) {
try {
track_info = new TrackInfo () {
TrackTitle = video_title,
ArtistName = video_uploader,
AlbumTitle = "YouTube",
Uri = new SafeUri (BansheePlaybackUri)
};
} catch (Exception e) {
Log.DebugException (e);
}
}
}
private void OnButtonClicked (object o, EventArgs args)
{
if (String.IsNullOrEmpty (BansheePlaybackUri)) {
Log.Debug ("Banshee supported playback Uri not set");
return;
}
SetTrackInfo ();
if (track_info != null) {
ServiceManager.PlayerEngine.OpenPlay (track_info);
}
}
private void OnBansheePlaybackAction (object o, EventArgs args)
{
OnButtonClicked (o, args);
}
private void OnBrowserPlaybackAction (object o, EventArgs args)
{
if (String.IsNullOrEmpty (BrowserPlaybackUri)) {
Log.Debug ("Browser playback Uri not set");
return;
}
Browser.Open (BrowserPlaybackUri);
}
private void ConstructTile ()
{
action_group = new ActionGroup ("VideoStreamTileMenuActionGroup");
action_group.Add (new ActionEntry [] {
new ActionEntry ("VideoStreamTileBansheePlaybackAction", null,
Catalog.GetString ("Play in Banshee..."), null,
Catalog.GetString ("Play in Banshee..."), OnBansheePlaybackAction),
new ActionEntry ("VideoStreamTileBrowserPlaybackAction", null,
Catalog.GetString ("Play in Web Browser..."), null,
Catalog.GetString ("Play in Web Browser..."), OnBrowserPlaybackAction),
});
CreateMenu ();
Construct (button, menu, true);
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReactNative.Tracing;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using static System.FormattableString;
namespace ReactNative.Bridge
{
/// <summary>
/// A set of native APIs exposed to a particular JavaScript instance.
/// </summary>
public sealed class NativeModuleRegistry
{
private readonly ReactContext _reactContext;
private readonly IReadOnlyList<ModuleDefinition> _moduleTable;
private readonly IReadOnlyDictionary<Type, INativeModule> _moduleInstances;
private readonly IList<IOnBatchCompleteListener> _batchCompleteListenerModules;
private NativeModuleRegistry(
ReactContext reactContext,
IReadOnlyList<ModuleDefinition> moduleTable,
IReadOnlyDictionary<Type, INativeModule> moduleInstances)
{
_reactContext = reactContext;
_moduleTable = moduleTable;
_moduleInstances = moduleInstances;
_batchCompleteListenerModules = _moduleTable
.Select(moduleDefinition => moduleDefinition.Target)
.OfType<IOnBatchCompleteListener>()
.ToList();
}
/// <summary>
/// The set of native modules exposed.
/// </summary>
public IEnumerable<INativeModule> Modules
{
get
{
return _moduleInstances.Values;
}
}
/// <summary>
/// Gets a module instance of a specific type.
/// </summary>
/// <typeparam name="T">Type of module instance.</typeparam>
/// <returns>The module instance.</returns>
public T GetModule<T>() where T : INativeModule
{
var instance = default(INativeModule);
if (_moduleInstances.TryGetValue(typeof(T), out instance))
{
return (T)instance;
}
throw new InvalidOperationException("No module instance for type '{0}'.");
}
/// <summary>
/// Triggers the batch completion event for all modules.
/// </summary>
public void OnBatchComplete()
{
foreach (var module in _batchCompleteListenerModules)
{
Dispatch((INativeModule)module, module.OnBatchComplete);
}
}
/// <summary>
/// Write the module descriptions to the given <see cref="JsonWriter"/>.
/// </summary>
/// <param name="writer">The JSON writer.</param>
internal void WriteModuleDescriptions(JsonWriter writer)
{
using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "CreateJSON").Start())
{
writer.WriteStartArray();
foreach (var moduleDef in _moduleTable)
{
moduleDef.WriteModuleDescription(writer);
}
writer.WriteEndArray();
}
}
/// <summary>
/// Invoke a method on a native module.
/// </summary>
/// <param name="reactInstance">The React instance.</param>
/// <param name="moduleId">The module ID.</param>
/// <param name="methodId">The method ID.</param>
/// <param name="parameters">The parameters.</param>
internal void Invoke(
IReactInstance reactInstance,
int moduleId,
int methodId,
JArray parameters)
{
if (moduleId < 0)
throw new ArgumentOutOfRangeException(nameof(moduleId), "Invalid module ID: " + moduleId);
if (_moduleTable.Count < moduleId)
throw new ArgumentOutOfRangeException(nameof(moduleId), "Call to unknown module: " + moduleId);
var actionQueue = _moduleTable[moduleId].Target.ActionQueue;
if (actionQueue != null)
{
actionQueue.Dispatch(() => _moduleTable[moduleId].Invoke(reactInstance, methodId, parameters));
}
else
{
_moduleTable[moduleId].Invoke(reactInstance, methodId, parameters);
}
}
/// <summary>
/// Hook to notify modules that the <see cref="IReactInstance"/> has
/// been initialized.
/// </summary>
internal void NotifyReactInstanceInitialize()
{
_reactContext.AssertOnNativeModulesQueueThread();
using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "NativeModuleRegistry_NotifyReactInstanceInitialize").Start())
{
foreach (var module in _moduleInstances.Values)
{
Dispatch(module, module.Initialize);
}
}
}
/// <summary>
/// Hook to notify modules that the <see cref="IReactInstance"/> has
/// been disposed.
/// </summary>
internal void NotifyReactInstanceDispose()
{
_reactContext.AssertOnNativeModulesQueueThread();
using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "NativeModuleRegistry_NotifyReactInstanceDestroy").Start())
{
foreach (var module in _moduleInstances.Values)
{
Dispatch(module, module.OnReactInstanceDispose);
module.ActionQueue?.Dispose();
}
}
}
private static void Dispatch(INativeModule module, Action action)
{
// If the module has an action queue, dispatch there;
// otherwise execute inline.
if (module.ActionQueue != null)
{
module.ActionQueue.Dispatch(action);
}
else
{
action();
}
}
class ModuleDefinition
{
private readonly IList<MethodRegistration> _methods;
public ModuleDefinition(string name, INativeModule target)
{
Name = name;
Target = target;
_methods = new List<MethodRegistration>(target.Methods.Count);
foreach (var entry in target.Methods)
{
_methods.Add(
new MethodRegistration(
entry.Key,
"NativeCall__" + target.Name + "_" + entry.Key,
entry.Value));
}
}
public int Id { get; }
public string Name { get; }
public INativeModule Target { get; }
public void Invoke(IReactInstance reactInstance, int methodId, JArray parameters)
{
var method = _methods[methodId];
using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, method.TracingName).Start())
{
method.Method.Invoke(reactInstance, parameters);
}
}
public void WriteModuleDescription(JsonWriter writer)
{
writer.WriteStartArray();
writer.WriteValue(Name);
JObject.FromObject(Target.Constants).WriteTo(writer);
if (_methods.Count > 0)
{
var syncMethodIds = new List<int>();
var promiseMethodIds = new List<int>();
writer.WriteStartArray();
for (var i = 0; i < _methods.Count; ++i)
{
var method = _methods[i];
writer.WriteValue(method.Name);
if (method.Method.Type == ReactDelegateFactoryBase.PromiseMethodType)
{
promiseMethodIds.Add(i);
}
else if (method.Method.Type == ReactDelegateFactoryBase.SyncMethodType)
{
syncMethodIds.Add(i);
}
}
writer.WriteEndArray();
if (promiseMethodIds.Count > 0 || syncMethodIds.Count > 0)
{
WriteList(writer, promiseMethodIds);
if (syncMethodIds.Count > 0)
{
WriteList(writer, syncMethodIds);
}
}
}
writer.WriteEndArray();
}
private static void WriteList(JsonWriter writer, IList<int> values)
{
writer.WriteStartArray();
for (var i = 0; i < values.Count; ++i)
{
writer.WriteValue(values[i]);
}
writer.WriteEndArray();
}
class MethodRegistration
{
public MethodRegistration(string name, string tracingName, INativeMethod method)
{
Name = name;
TracingName = tracingName;
Method = method;
}
public string Name { get; }
public string TracingName { get; }
public INativeMethod Method { get; }
}
}
/// <summary>
/// Builder for <see cref="NativeModuleRegistry"/>.
/// </summary>
public sealed class Builder
{
private readonly IDictionary<string, INativeModule> _modules =
new Dictionary<string, INativeModule>();
private readonly ReactContext _reactContext;
/// <summary>
/// Instantiates the <see cref="Builder"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
public Builder(ReactContext reactContext)
{
if (reactContext == null)
throw new ArgumentNullException(nameof(reactContext));
_reactContext = reactContext;
}
/// <summary>
/// Add a native module to the builder.
/// </summary>
/// <param name="module">The native module.</param>
/// <returns>The builder instance.</returns>
public Builder Add(INativeModule module)
{
if (module == null)
throw new ArgumentNullException(nameof(module));
if (module.Name == null)
throw new ArgumentException(
Invariant($"Native module '{module.GetType()}' cannot have a null `Name`."),
nameof(module));
var existing = default(INativeModule);
if (_modules.TryGetValue(module.Name, out existing) && !module.CanOverrideExistingModule)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
"Native module '{0}' tried to override '{1}' for module name '{2}'. " +
"If this was your intention, override `CanOverrideExistingModule`.",
module.GetType().Name,
existing.GetType().Name,
module.Name));
}
_modules[module.Name] = module;
return this;
}
/// <summary>
/// Build a <see cref="NativeModuleRegistry"/> instance.
/// </summary>
/// <returns>The instance.</returns>
public NativeModuleRegistry Build()
{
var moduleTable = new List<ModuleDefinition>(_modules.Count);
var moduleInstances = new Dictionary<Type, INativeModule>(_modules.Count);
foreach (var module in _modules.Values)
{
var name = module.Name;
var moduleDef = new ModuleDefinition(name, module);
moduleTable.Add(moduleDef);
moduleInstances.Add(module.GetType(), module);
}
return new NativeModuleRegistry(_reactContext, moduleTable, moduleInstances);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using UnityEngine;
public struct VariableParm
{
public string VariableName;
public float VariableValue;
};
public struct EventParm
{
public string EventName;
public float EventDuration;
};
public class VarTracerCmdCacher
{
private Dictionary<string, NamePackage> _groupCmdPackage
= new Dictionary<string, NamePackage>();
public Dictionary<string, NamePackage> GroupCmdPackage
{
get { return _groupCmdPackage; }
}
public void SendEvent(string groupName, string eventName, float duration)
{
var group = GetGroupByName(groupName);
if (group == null)
return;
var eventParm = GetEventParmByName(group,eventName);
if (eventParm == null)
return;
eventParm._stamp = VarTracerUtils.GetTimeStamp();
eventParm._duration = duration;
}
public void SendVariable(string groupName, string variableName, float value)
{
var group = GetGroupByName(groupName);
if (group == null)
return;
var varParm = GetVariableParmByName(group, variableName);
if (varParm == null)
return;
varParm._stamp = VarTracerUtils.GetTimeStamp();
varParm._value = value;
}
private EventCmdParam GetEventParmByName(NamePackage group, string name)
{
if (string.IsNullOrEmpty(name))
return null;
if (!group.EventDict.ContainsKey(name))
{
var cmdParm = new EventCmdParam();
group.EventDict.Add(name, new CacheList<EventCmdParam>(cmdParm));
return cmdParm;
}
var reuseObj = group.EventDict[name].CheckReuse();
if (reuseObj != null)
return reuseObj as EventCmdParam;
var parm = new EventCmdParam();
group.EventDict[name].VarChacheList.Add(parm);
group.EventDict[name].UseIndex++;
return parm;
}
private VariableCmdParam GetVariableParmByName(NamePackage group, string name)
{
if (string.IsNullOrEmpty(name))
return null;
if (!group.VariableDict.ContainsKey(name))
{
var cmdParm = new VariableCmdParam();
group.VariableDict.Add(name, new CacheList<VariableCmdParam>(cmdParm));
return cmdParm;
}
var reuseObj = group.VariableDict[name].CheckReuse();
if(reuseObj != null)
return reuseObj as VariableCmdParam;
var parm = new VariableCmdParam();
group.VariableDict[name].VarChacheList.Add(parm);
group.VariableDict[name].UseIndex++;
return parm;
}
private NamePackage GetGroupByName(string name)
{
if (string.IsNullOrEmpty(name))
return null;
if (!_groupCmdPackage.ContainsKey(name))
_groupCmdPackage.Add(name,new NamePackage());
return _groupCmdPackage[name];
}
public void Clear()
{
foreach (var package in _groupCmdPackage)
{
package.Value.Reset();
}
}
public int GetUsedGroupCount()
{
int groupCount = 0;
foreach (var package in _groupCmdPackage)
{
if (package.Value.IsUse())
{
groupCount++;
}
}
return groupCount;
}
public int GetUsedVariableCount(NamePackage packet)
{
int variableCount = 0;
foreach (var list in packet.VariableDict.Values)
{
if (list.IsUse())
{
variableCount++;
}
}
return variableCount;
}
public int GetUsedEventCount(NamePackage packet)
{
int eventCount = 0;
foreach (var list in packet.EventDict.Values)
{
if (list.IsUse())
{
eventCount++;
}
}
return eventCount;
}
}
public class NamePackage
{
private Dictionary<string, CacheList<VariableCmdParam>> _variableDict
= new Dictionary<string, CacheList<VariableCmdParam>>();
public Dictionary<string, CacheList<VariableCmdParam>> VariableDict
{
get { return _variableDict; }
set { _variableDict = value; }
}
private Dictionary<string, CacheList<EventCmdParam>> _eventDict
= new Dictionary<string, CacheList<EventCmdParam>>();
public Dictionary<string, CacheList<EventCmdParam>> EventDict
{
get { return _eventDict; }
set { _eventDict = value; }
}
public void Reset() {
foreach (var list in _variableDict.Values)
list.UseIndex = 0;
foreach (var list in _eventDict.Values)
list.UseIndex = 0;
}
public bool IsUse()
{
foreach (var list in _variableDict.Values)
{
if (list.UseIndex > 0)
return true;
}
foreach (var list in _eventDict.Values)
{
if (list.UseIndex > 0)
return true;
}
return false;
}
}
public class CacheList<T>
{
int _useIndex = 0;
public CacheList()
{
}
public CacheList (T t)
{
_varChacheList.Add(t);
_useIndex++;
}
public int UseIndex
{
get { return _useIndex; }
set { _useIndex = value; }
}
private List<T> _varChacheList = new List<T>();
public List<T> VarChacheList
{
get { return _varChacheList; }
set { _varChacheList = value; }
}
public object CheckReuse()
{
if (_varChacheList.Count > UseIndex)
return _varChacheList[UseIndex++];
return null;
}
public bool IsUse()
{
return _useIndex >0;
}
}
public class VariableCmdParam
{
public long _stamp=0;
public float _value=0.0f;
}
public class EventCmdParam
{
public long _stamp = 0;
public float _duration = 0.0f;
}
| |
#region License
// Copyright 2013-2014 Matthew Ducker
//
// 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.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
using BitManipulator;
using Nessos.LinqOptimizer.CSharp;
using Obscur.Core.Cryptography;
using Obscur.Core.Cryptography.Authentication;
using Obscur.Core.Cryptography.Ciphers;
using Obscur.Core.Cryptography.Ciphers.Block;
using Obscur.Core.Cryptography.Ciphers.Stream;
using Obscur.Core.Cryptography.KeyAgreement.Primitives;
using Obscur.Core.Cryptography.KeyConfirmation;
using Obscur.Core.Cryptography.KeyDerivation;
using Obscur.Core.DTO;
using Obscur.Core.Packaging.Multiplexing;
namespace Obscur.Core.Packaging
{
/// <summary>
/// Constructs and writes ObscurCore packages.
/// </summary>
public sealed class PackageWriter
{
private const PayloadLayoutScheme DefaultLayoutScheme = PayloadLayoutScheme.Frameshift;
private const string MCryptoNotDefined = "Manifest cryptographic scheme not defined.";
private static readonly byte[] MPlaceholderBytes = new byte[1024];
#region Instance variables
private readonly int _formatVersion = Athena.Packaging.PackageFormatVersion;
private readonly Dictionary<Guid, byte[]> _itemPreKeys = new Dictionary<Guid, byte[]>();
private readonly Manifest _manifest;
/// <summary>
/// Configuration of the manifest cipher. Must be serialised into ManifestHeader when writing package.
/// </summary>
private IManifestCryptographySchemeConfiguration _manifestHeaderCryptoConfig;
private ManifestCryptographyScheme _manifestHeaderCryptoScheme = ManifestCryptographyScheme.None;
/// <summary>
/// Whether package has had Write() called already in its lifetime.
/// Multiple invocations are prohibited in order to preserve security properties.
/// </summary>
private bool _writingComplete;
/// <summary>
/// Key for the manifest cipher prior to key derivation.
/// </summary>
private byte[] _writingPreManifestKey;
#endregion
#region Constructors
/// <summary>
/// Create a new package using default symmetric-only encryption for security.
/// </summary>
/// <param name="key">Cryptographic key known to the recipient to use for the manifest.</param>
/// <param name="lowEntropy">Byte key supplied has low entropy (e.g. from a human password).</param>
/// <param name="layoutScheme">Scheme to use for the layout of items in the payload.</param>
public PackageWriter(SymmetricKey key, bool lowEntropy = false,
PayloadLayoutScheme layoutScheme = DefaultLayoutScheme)
{
Contract.Requires(key != null);
_manifest = new Manifest();
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.SymmetricOnly;
SetManifestCryptoSymmetric(key, lowEntropy);
PayloadLayout = layoutScheme;
}
/// <summary>
/// Create a new package using default symmetric-only encryption for security.
/// </summary>
/// <param name="key">Cryptographic key known to the recipient to use for the manifest.</param>
/// <param name="canary">Known value to use for confirming the <paramref name="key" />.</param>
/// <param name="lowEntropy">Byte key supplied has low entropy (e.g. from a human password).</param>
/// <param name="layoutScheme">Scheme to use for the layout of items in the payload.</param>
public PackageWriter(byte[] key, byte[] canary, bool lowEntropy = false,
PayloadLayoutScheme layoutScheme = DefaultLayoutScheme)
{
Contract.Requires(key != null);
Contract.Requires(canary != null);
_manifest = new Manifest();
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.SymmetricOnly;
SetManifestCryptoSymmetric(key, canary, lowEntropy);
PayloadLayout = layoutScheme;
}
/// <summary>
/// Create a new package using default symmetric-only encryption for security.
/// Key is used in UTF-8-encoded byte array form.
/// </summary>
/// <param name="key">Passphrase known to the recipient to use for the manifest.</param>
/// <param name="canary">Known value to use for confirming the <paramref name="key" />.</param>
/// <param name="lowEntropy">Byte key supplied has low entropy (e.g. from a human password).</param>
/// <param name="layoutScheme">Scheme to use for the layout of items in the payload.</param>
public PackageWriter(string key, string canary, bool lowEntropy = true,
PayloadLayoutScheme layoutScheme = DefaultLayoutScheme)
: this(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(canary), lowEntropy, layoutScheme) {}
/// <summary>
/// Create a new package using UM1-hybrid cryptography for security.
/// </summary>
/// <param name="sender">Elliptic curve key of the sender (private key).</param>
/// <param name="recipient">Elliptic curve key of the recipient (public key).</param>
/// <param name="layoutScheme">Scheme to use for the layout of items in the payload.</param>
public PackageWriter(ECKeypair sender, ECKeypair recipient,
PayloadLayoutScheme layoutScheme = DefaultLayoutScheme)
{
Contract.Requires(sender != null);
Contract.Requires(recipient != null);
_manifest = new Manifest();
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.Um1Hybrid;
SetManifestCryptoUm1(sender, recipient.ExportPublicKey());
PayloadLayout = layoutScheme;
}
/// <summary>
/// Initialise a writer without setting any manifest cryptographic scheme. This must be set before writing.
/// </summary>
/// <param name="layoutScheme"></param>
public PackageWriter(PayloadLayoutScheme layoutScheme = DefaultLayoutScheme)
{
_manifest = new Manifest();
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.None;
_manifestHeaderCryptoConfig = null;
PayloadLayout = layoutScheme;
}
#endregion
#region Properties
/// <summary>
/// Format version specification of the data transfer objects and logic used in the package.
/// </summary>
public int FormatVersion
{
get { return _formatVersion; }
}
/// <summary>
/// Cryptographic scheme used for the manifest.
/// </summary>
public ManifestCryptographyScheme ManifestCryptoScheme
{
get { return _manifestHeaderCryptoScheme; }
}
/// <summary>
/// Configuration of symmetric cipher used for encryption of the manifest.
/// </summary>
internal CipherConfiguration ManifestCipher
{
get { return _manifestHeaderCryptoConfig == null ? null : _manifestHeaderCryptoConfig.SymmetricCipher; }
private set
{
switch (ManifestCryptoScheme) {
case ManifestCryptographyScheme.SymmetricOnly:
((SymmetricManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).SymmetricCipher =
value;
break;
case ManifestCryptographyScheme.Um1Hybrid:
((Um1HybridManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).SymmetricCipher =
value;
break;
default:
throw new InvalidOperationException(MCryptoNotDefined);
}
}
}
/// <summary>
/// Configuration of function used in verifying the authenticity and integrity of the manifest.
/// </summary>
internal AuthenticationConfiguration ManifestAuthentication
{
get { return _manifestHeaderCryptoConfig == null ? null : _manifestHeaderCryptoConfig.Authentication; }
private set
{
switch (ManifestCryptoScheme) {
case ManifestCryptographyScheme.SymmetricOnly:
((SymmetricManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).Authentication =
value;
break;
case ManifestCryptographyScheme.Um1Hybrid:
((Um1HybridManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).Authentication =
value;
break;
default:
throw new InvalidOperationException(MCryptoNotDefined);
}
}
}
/// <summary>
/// Configuration of key derivation used to derive encryption and authentication keys from prior key material.
/// These keys are used in those functions of manifest encryption/authentication, respectively.
/// </summary>
internal KeyDerivationConfiguration ManifestKeyDerivation
{
get { return _manifestHeaderCryptoConfig == null ? null : _manifestHeaderCryptoConfig.KeyDerivation; }
private set
{
switch (ManifestCryptoScheme) {
case ManifestCryptographyScheme.SymmetricOnly:
((SymmetricManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).KeyDerivation =
value;
break;
case ManifestCryptographyScheme.Um1Hybrid:
((Um1HybridManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).KeyDerivation =
value;
break;
default:
throw new InvalidOperationException(MCryptoNotDefined);
}
}
}
/// <summary>
/// Configuration of key confirmation used for confirming the cryptographic key
/// to be used as the basis for key derivation.
/// </summary>
internal AuthenticationConfiguration ManifestKeyConfirmation
{
get { return _manifestHeaderCryptoConfig == null ? null : _manifestHeaderCryptoConfig.KeyConfirmation; }
private set
{
switch (ManifestCryptoScheme) {
case ManifestCryptographyScheme.SymmetricOnly:
((SymmetricManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).KeyConfirmation =
value;
break;
case ManifestCryptographyScheme.Um1Hybrid:
((Um1HybridManifestCryptographyConfiguration) _manifestHeaderCryptoConfig).KeyConfirmation =
value;
break;
default:
throw new InvalidOperationException(MCryptoNotDefined);
}
}
}
/// <summary>
/// Layout scheme configuration of the items in the payload.
/// </summary>
public PayloadLayoutScheme PayloadLayout
{
get { return _manifest.PayloadConfiguration.SchemeName.ToEnum<PayloadLayoutScheme>(); }
set { _manifest.PayloadConfiguration = PayloadLayoutConfigurationFactory.CreateDefault(value); }
}
#endregion
#region Methods for manifest cryptography
/// <summary>
/// Set the manifest to use symmetric-only security.
/// </summary>
/// <param name="key">Key known to the recipient of the package.</param>
/// <param name="lowEntropy">Pre-key has low entropy, e.g. a human-memorisable passphrase.</param>
/// <exception cref="ArgumentException">Key is null or zero-length.</exception>
/// <exception cref="ArgumentNullException">Canary is null.</exception>
public void SetManifestCryptoSymmetric(SymmetricKey key, bool lowEntropy = false)
{
SetManifestCryptoSymmetric(key.Key, key.ConfirmationCanary, lowEntropy);
}
/// <summary>
/// Set the manifest to use symmetric-only security.
/// Key is used in UTF-8 encoded byte array form.
/// </summary>
/// <param name="key">Passphrase known to the recipient of the package.</param>
/// <param name="canary">Known value to use for confirming the <paramref name="key" />.</param>
/// <exception cref="ArgumentException">Key or canary is null or zero-length.</exception>
public void SetManifestCryptoSymmetric(string key, string canary)
{
if (String.IsNullOrEmpty(key)) {
throw new ArgumentException("Key is null or zero-length (empty).", "key");
}
if (String.IsNullOrEmpty(canary)) {
throw new ArgumentException("Canary is null or zero-length (empty).", "canary");
}
SetManifestCryptoSymmetric(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(canary), true);
}
/// <summary>
/// Set the manifest to use symmetric-only security.
/// </summary>
/// <param name="key">Key known to the recipient of the package.</param>
/// <param name="canary">Known value to use for confirming the <paramref name="key" />.</param>
/// <param name="lowEntropy">Pre-key has low entropy, e.g. a human-memorisable passphrase.</param>
/// <exception cref="ArgumentException">Key is null or zero-length.</exception>
/// <exception cref="ArgumentNullException">Canary is null.</exception>
public void SetManifestCryptoSymmetric(byte[] key, byte[] canary, bool lowEntropy)
{
if (key.IsNullOrZeroLength()) {
throw new ArgumentException("Key is null or zero-length.", "key");
}
if (canary == null) {
throw new ArgumentNullException("canary");
}
if (_writingPreManifestKey != null) {
_writingPreManifestKey.SecureWipe();
}
_writingPreManifestKey = new byte[key.Length];
Array.Copy(key, _writingPreManifestKey, key.Length);
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "SetManifestCryptoSymmetric",
"Manifest pre-key",
_writingPreManifestKey.ToHexString()));
CipherConfiguration cipherConfig = _manifestHeaderCryptoConfig == null
? CreateDefaultManifestCipherConfiguration()
: _manifestHeaderCryptoConfig.SymmetricCipher ?? CreateDefaultManifestCipherConfiguration();
AuthenticationConfiguration authenticationConfig = _manifestHeaderCryptoConfig == null
? CreateDefaultManifestAuthenticationConfiguration()
: _manifestHeaderCryptoConfig.Authentication ?? CreateDefaultManifestAuthenticationConfiguration();
KeyDerivationConfiguration derivationConfig = _manifestHeaderCryptoConfig == null
? CreateDefaultManifestKeyDerivation(cipherConfig.KeySizeBits.BitsToBytes(), lowEntropy)
: _manifestHeaderCryptoConfig.KeyDerivation ??
CreateDefaultManifestKeyDerivation(cipherConfig.KeySizeBits.BitsToBytes());
byte[] keyConfirmationOutput;
AuthenticationConfiguration keyConfirmationConfig = CreateDefaultManifestKeyConfirmationConfiguration
(
canary, out keyConfirmationOutput);
_manifestHeaderCryptoConfig = new SymmetricManifestCryptographyConfiguration {
SymmetricCipher = cipherConfig,
Authentication = authenticationConfig,
KeyConfirmation = keyConfirmationConfig,
KeyConfirmationVerifiedOutput = keyConfirmationOutput,
KeyDerivation = derivationConfig
};
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.SymmetricOnly;
}
/// <summary>
/// Set manifest to use UM1-Hybrid cryptography.
/// </summary>
/// <param name="senderKeypair">Keypair of the sender.</param>
/// <param name="recipientKey">Key of the recipient (public key).</param>
public void SetManifestCryptoUm1(ECKeypair senderKeypair, ECKey recipientKey)
{
if (senderKeypair == null) {
throw new ArgumentNullException("senderKeypair");
}
if (recipientKey == null) {
throw new ArgumentNullException("recipientKey");
}
if (senderKeypair.CurveName.Equals(recipientKey.CurveName) == false) {
throw new InvalidOperationException(
"Elliptic curve cryptographic mathematics requires public and private keys be in the same curve domain.");
}
if (_writingPreManifestKey != null) {
_writingPreManifestKey.SecureWipe();
}
ECKey ephemeral;
_writingPreManifestKey = Um1Exchange.Initiate(recipientKey, senderKeypair.GetPrivateKey(), out ephemeral);
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "SetManifestCryptoUM1", "Manifest pre-key",
_writingPreManifestKey.ToHexString()));
CipherConfiguration cipherConfig = _manifestHeaderCryptoConfig == null
? CreateDefaultManifestCipherConfiguration()
: _manifestHeaderCryptoConfig.SymmetricCipher ?? CreateDefaultManifestCipherConfiguration();
AuthenticationConfiguration authenticationConfig = _manifestHeaderCryptoConfig == null
? CreateDefaultManifestAuthenticationConfiguration()
: _manifestHeaderCryptoConfig.Authentication ?? CreateDefaultManifestAuthenticationConfiguration();
KeyDerivationConfiguration derivationConfig = _manifestHeaderCryptoConfig == null
? CreateDefaultManifestKeyDerivation(cipherConfig.KeySizeBits.BitsToBytes(), false)
: _manifestHeaderCryptoConfig.KeyDerivation ??
CreateDefaultManifestKeyDerivation(cipherConfig.KeySizeBits.BitsToBytes());
byte[] keyConfirmationOutput;
AuthenticationConfiguration keyConfirmationConfig = CreateDefaultManifestKeyConfirmationConfiguration
(
senderKeypair,
recipientKey,
out keyConfirmationOutput);
_manifestHeaderCryptoConfig = new Um1HybridManifestCryptographyConfiguration {
SymmetricCipher = cipherConfig,
Authentication = authenticationConfig,
KeyConfirmation = keyConfirmationConfig,
KeyConfirmationVerifiedOutput = keyConfirmationOutput,
KeyDerivation = derivationConfig,
EphemeralKey = ephemeral
};
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.Um1Hybrid;
}
/// <summary>
/// Advanced method. Manually set a manifest cryptography configuration.
/// Misuse will likely result in unreadable package, and/or security risks.
/// </summary>
/// <param name="configuration">Configuration to apply.</param>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="ArgumentException">Object not a recognised type.</exception>
/// <exception cref="InvalidOperationException">Package is being read, not written.</exception>
public void SetManifestCryptography(IManifestCryptographySchemeConfiguration configuration)
{
if (configuration is IDataTransferObject) {
if (configuration is SymmetricManifestCryptographyConfiguration) {
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.SymmetricOnly;
_manifestHeaderCryptoConfig = configuration;
} else if (configuration is Um1HybridManifestCryptographyConfiguration) {
_manifestHeaderCryptoScheme = ManifestCryptographyScheme.Um1Hybrid;
_manifestHeaderCryptoConfig = configuration;
} else {
throw new ArgumentException("Configuration provided is of an unsupported type.",
new NotSupportedException(""));
}
} else {
throw new ArgumentException(
"Object is not a valid data transfer object type in the ObscurCore package format specification.",
"configuration");
}
}
/// <summary>
/// Set a specific block cipher configuration to be used for the cipher used for manifest encryption.
/// </summary>
/// <exception cref="InvalidOperationException">Package is being written, not read.</exception>
/// <exception cref="ArgumentException">Enum was set to None.</exception>
public void ConfigureManifestCryptoSymmetric(BlockCipher cipher, BlockCipherMode mode,
BlockCipherPadding padding)
{
if (cipher == BlockCipher.None) {
throw new ArgumentException("Cipher cannot be set to none.", "cipher");
}
if (mode == BlockCipherMode.None) {
throw new ArgumentException("Mode cannot be set to none.", "mode");
}
if (cipher == BlockCipher.None) {
throw new ArgumentException();
}
ManifestCipher = CipherConfigurationFactory.CreateBlockCipherConfiguration(cipher, mode, padding);
}
/// <summary>
/// Set a specific stream cipher to be used for the cipher used for manifest encryption.
/// </summary>
/// <exception cref="InvalidOperationException">Package is being written, not read.</exception>
/// <exception cref="ArgumentException">Cipher was set to None.</exception>
public void ConfigureManifestCryptoSymmetric(StreamCipher cipher)
{
if (cipher == StreamCipher.None) {
throw new ArgumentException();
}
ManifestCipher = CipherConfigurationFactory.CreateStreamCipherConfiguration(cipher);
}
/// <summary>
/// Advanced method. Manually set a payload configuration for the package.
/// </summary>
/// <param name="payloadConfiguration">Payload configuration to set.</param>
/// <exception cref="ArgumentNullException">Payload configuration is null.</exception>
public void SetPayloadConfiguration(PayloadConfiguration payloadConfiguration)
{
if (payloadConfiguration == null) {
throw new ArgumentNullException("payloadConfiguration");
}
_manifest.PayloadConfiguration = payloadConfiguration;
}
// Manifest default configuration creation methods
/// <summary>
/// Creates a default manifest cipher configuration.
/// </summary>
/// <remarks>Default configuration uses the stream cipher XSalsa20.</remarks>
private static CipherConfiguration CreateDefaultManifestCipherConfiguration()
{
return CipherConfigurationFactory.CreateStreamCipherConfiguration(StreamCipher.XSalsa20);
}
/// <summary>
/// Creates a default manifest authentication configuration.
/// </summary>
/// <remarks>Default configuration uses the MAC primitive SHA-3-512 (Keccak-512).</remarks>
/// <returns></returns>
private static AuthenticationConfiguration CreateDefaultManifestAuthenticationConfiguration()
{
int outputSize;
return AuthenticationConfigurationFactory.CreateAuthenticationConfiguration(MacFunction.Keccak512,
out outputSize);
}
/// <summary>
/// Creates a default manifest key confirmation configuration.
/// </summary>
/// <remarks>Default configuration uses HMAC-SHA3-256 (HMAC-Keccak-256).</remarks>
/// <param name="canary">Canary (associated with a key) to generate confirmation configuration for.</param>
/// <param name="verifiedOutput">Output of verification function.</param>
private static AuthenticationConfiguration CreateDefaultManifestKeyConfirmationConfiguration(
byte[] canary,
out byte[] verifiedOutput)
{
AuthenticationConfiguration config =
ConfirmationConfigurationFactory.GenerateConfiguration(HashFunction.Keccak256);
// Using HMAC (key can be any length)
verifiedOutput = ConfirmationUtility.GenerateVerifiedOutput(config, canary);
return config;
}
/// <summary>
/// Creates a default manifest key confirmation configuration.
/// </summary>
/// <remarks>Default configuration uses HMAC-SHA3-256 (HMAC-Keccak-256).</remarks>
/// <param name="key">Key to generate confirmation configuration for.</param>
/// <param name="verifiedOutput">Output of verification function.</param>
private static AuthenticationConfiguration CreateDefaultManifestKeyConfirmationConfiguration(
SymmetricKey key,
out byte[] verifiedOutput)
{
AuthenticationConfiguration config =
ConfirmationConfigurationFactory.GenerateConfiguration(HashFunction.Keccak256);
// Using HMAC (key can be any length)
verifiedOutput = ConfirmationUtility.GenerateVerifiedOutput(config, key);
return config;
}
private static AuthenticationConfiguration CreateDefaultManifestKeyConfirmationConfiguration(
ECKeypair senderKey,
ECKey recipientKey, out byte[] verifiedOutput)
{
AuthenticationConfiguration config =
ConfirmationConfigurationFactory.GenerateConfiguration(HashFunction.Keccak256);
// Using HMAC (key can be any length)
verifiedOutput = ConfirmationUtility.GenerateVerifiedOutput(config, senderKey, recipientKey);
return config;
}
/// <summary>
/// Creates a default manifest key derivation configuration.
/// </summary>
/// <remarks>Default configuration uses the KDF function 'scrypt'.</remarks>
/// <param name="keyLengthBytes">Length of key to produce.</param>
/// <param name="lowEntropyPreKey">Pre-key has low entropy, e.g. a human-memorisable passphrase.</param>
private static KeyDerivationConfiguration CreateDefaultManifestKeyDerivation(int keyLengthBytes,
bool lowEntropyPreKey = true)
{
var schemeConfig = new ScryptConfiguration {
Iterations = lowEntropyPreKey ? 65536 : 1024, // 2^16 : 2^10
Blocks = lowEntropyPreKey ? 16 : 8,
Parallelism = 2
};
var config = new KeyDerivationConfiguration {
FunctionName = KeyDerivationFunction.Scrypt.ToString(),
FunctionConfiguration = schemeConfig.SerialiseDto(),
Salt = new byte[keyLengthBytes]
};
StratCom.EntropySupplier.NextBytes(config.Salt);
return config;
}
#endregion
#region Methods for payload items
/// <summary>
/// Add a text payload item (encoded in UTF-8) to the package with a relative path
/// of root (/) in the manifest. Default encryption is used.
/// </summary>
/// <param name="name">Name of the item. Subject of the text is suggested.</param>
/// <param name="text">Content of the item.</param>
/// <exception cref="ArgumentException">Supplied null or empty string.</exception>
public void AddText(string name, string text)
{
if (String.IsNullOrEmpty(name) || String.IsNullOrWhiteSpace(name)) {
throw new ArgumentException("Item name is null or empty string.");
}
var stream = new MemoryStream(Encoding.UTF8.GetBytes(text));
PayloadItem newItem = CreateItem(() => stream, PayloadItemType.Message, stream.Length, name);
_manifest.PayloadItems.Add(newItem);
}
/// <summary>
/// Add a file-type payload item to the package with a relative path of root (/) in the manifest.
/// Default encryption is used.
/// </summary>
/// <param name="filePath">Path of the file to add.</param>
/// <exception cref="FileNotFoundException">File does not exist.</exception>
public void AddFile(string filePath)
{
var fileInfo = new FileInfo(filePath);
if (fileInfo.Exists == false) {
throw new FileNotFoundException();
}
PayloadItem newItem = CreateItem(fileInfo.OpenRead, PayloadItemType.File, fileInfo.Length, fileInfo.Name);
_manifest.PayloadItems.Add(newItem);
}
/// <summary>
/// Add a directory of files as payload items to the package with a relative path
/// of root (/) in the manifest. Default encryption is used.
/// </summary>
/// <param name="path">Path of the directory to search for and add files from.</param>
/// <param name="search">Search for files in subdirectories (default) or not.</param>
/// <exception cref="ArgumentException">Path supplied is not a directory.</exception>
public void AddDirectory(string path, SearchOption search = SearchOption.TopDirectoryOnly)
{
var dir = new DirectoryInfo(path);
if (Path.HasExtension(path)) {
throw new ArgumentException("Path is not a directory.");
}
if (!dir.Exists) {
throw new DirectoryNotFoundException();
}
int rootPathLength = dir.FullName.Length;
IEnumerable<FileInfo> files = dir.EnumerateFiles("*", search);
foreach (FileInfo file in files) {
string itemRelPath = search == SearchOption.TopDirectoryOnly
? file.Name
: file.FullName.Remove(0, rootPathLength + 1);
if (Path.DirectorySeparatorChar != Athena.Packaging.PathDirectorySeperator) {
itemRelPath = itemRelPath.Replace(Path.DirectorySeparatorChar,
Athena.Packaging.PathDirectorySeperator);
}
PayloadItem newItem = CreateItem(file.OpenRead, PayloadItemType.File, file.Length, itemRelPath);
_manifest.PayloadItems.Add(newItem);
}
}
/// <summary>
/// Add a payload item to the package.
/// </summary>
/// <exception cref="ArgumentNullException">Payload item argument is null.</exception>
public void AddFile(PayloadItem item)
{
if (item == null) {
throw new ArgumentNullException("item");
}
_manifest.PayloadItems.Add(item);
}
public IEnumerable<IPayloadItem> GetPayloadItems()
{
return _manifest.PayloadItems.AsQueryExpr().Select(item => item as IPayloadItem).Run();
}
/// <summary>
/// Creates a new PayloadItem DTO object.
/// </summary>
/// <returns>A payload item as a <see cref="PayloadItem" /> 'data transfer object'.</returns>
/// <param name="itemData">Function supplying a stream of the item data.</param>
/// <param name="itemType">Type of the item (as <see cref="PayloadItemType" />).</param>
/// <param name="externalLength">External length (outside the payload) of the item.</param>
/// <param name="relativePath">Relative path of the item.</param>
/// <param name="skipCrypto">
/// If set to <c>true</c>, leaves SymmetricCipher property set to null -
/// for post-method-modification.
/// </param>
private static PayloadItem CreateItem(Func<Stream> itemData, PayloadItemType itemType, long externalLength,
string relativePath, bool skipCrypto = false)
{
var newItem = new PayloadItem {
ExternalLength = externalLength,
Type = itemType,
Path = relativePath,
SymmetricCipher = skipCrypto ? null : CreateDefaultPayloadItemCipherConfiguration(),
Authentication = skipCrypto ? null : CreateDefaultPayloadItemAuthenticationConfiguration()
};
if (skipCrypto == false) {
newItem.SymmetricCipherKey = new byte[newItem.SymmetricCipher.KeySizeBits / 8];
StratCom.EntropySupplier.NextBytes(newItem.SymmetricCipherKey);
newItem.AuthenticationKey = new byte[newItem.Authentication.KeySizeBits.Value / 8];
StratCom.EntropySupplier.NextBytes(newItem.AuthenticationKey);
}
newItem.SetStreamBinding(itemData);
return newItem;
}
/// <summary>
/// Creates a new PayloadItem DTO object with a specific cryptographic key.
/// </summary>
/// <returns>A payload item as a <see cref="PayloadItem" /> 'data transfer object'.</returns>
/// <param name="itemData">Function supplying a stream of the item data.</param>
/// <param name="itemType">Type of the item (as <see cref="PayloadItemType" />).</param>
/// <param name="externalLength">External length (outside the payload) of the item.</param>
/// <param name="relativePath">Relative path of the item.</param>
/// <param name="preKey">Key to be found on recipient's system and used as a basis for derivation.</param>
/// <param name="lowEntropyKey">
/// If set to <c>true</c> pre-key has low entropy (e.g. a human-memorisable passphrase), and higher KDF difficulty will
/// be used.
/// </param>
private static PayloadItem CreateItem(Func<Stream> itemData, PayloadItemType itemType, long externalLength,
string relativePath, SymmetricKey preKey, bool lowEntropyKey = true)
{
byte[] keyConfirmationVerifiedOutput;
AuthenticationConfiguration keyConfirmatConf =
CreateDefaultPayloadItemKeyConfirmationConfiguration(preKey,
out keyConfirmationVerifiedOutput);
KeyDerivationConfiguration kdfConf = CreateDefaultPayloadItemKeyDerivation(preKey.Key.Length, lowEntropyKey);
var newItem = new PayloadItem {
ExternalLength = externalLength,
Type = itemType,
Path = relativePath,
SymmetricCipher = CreateDefaultPayloadItemCipherConfiguration(),
Authentication = CreateDefaultPayloadItemAuthenticationConfiguration(),
KeyConfirmation = keyConfirmatConf,
KeyConfirmationVerifiedOutput = keyConfirmationVerifiedOutput,
KeyDerivation = kdfConf
};
newItem.SetStreamBinding(itemData);
return newItem;
}
// Payload item default configuration creation methods
/// <summary>
/// Creates a default payload item cipher configuration.
/// </summary>
/// <remarks>Default configuration uses the stream cipher HC-128.</remarks>
private static CipherConfiguration CreateDefaultPayloadItemCipherConfiguration()
{
return CipherConfigurationFactory.CreateStreamCipherConfiguration(StreamCipher.Sosemanuk);
}
/// <summary>
/// Creates a default payload item authentication configuration.
/// </summary>
/// <remarks>Default configuration uses the hybrid MAC-cipher construction Poly1305-AES.</remarks>
private static AuthenticationConfiguration CreateDefaultPayloadItemAuthenticationConfiguration()
{
return AuthenticationConfigurationFactory.CreateAuthenticationConfigurationPoly1305(BlockCipher.Aes);
}
/// <summary>
/// Creates a default payload item key confirmation configuration.
/// </summary>
/// <remarks>Default configuration uses HMAC-SHA3-256 (HMAC-Keccak-256).</remarks>
/// <param name="key">Key to generate confirmation configuration for.</param>
/// <param name="verifiedOutput">Output of verification function.</param>
private static AuthenticationConfiguration CreateDefaultPayloadItemKeyConfirmationConfiguration(
SymmetricKey key, out byte[] verifiedOutput)
{
AuthenticationConfiguration config =
ConfirmationConfigurationFactory.GenerateConfiguration(HashFunction.Keccak256);
verifiedOutput = ConfirmationUtility.GenerateVerifiedOutput(config, key);
return config;
}
/// <summary>
/// Creates a default payload item key derivation configuration.
/// </summary>
/// <remarks>Default configuration uses the KDF function 'scrypt'.</remarks>
/// <param name="keyLengthBytes">Length of key to produce.</param>
/// <param name="lowEntropyPreKey">Pre-key has low entropy, e.g. a human-memorisable passphrase.</param>
private static KeyDerivationConfiguration CreateDefaultPayloadItemKeyDerivation(int keyLengthBytes,
bool lowEntropyPreKey = true)
{
var schemeConfig = new ScryptConfiguration {
Iterations = lowEntropyPreKey ? 16384 : 1024, // 2^14 : 2^10
Blocks = 8,
Parallelism = 1
};
var config = new KeyDerivationConfiguration {
FunctionName = KeyDerivationFunction.Scrypt.ToString(),
FunctionConfiguration = schemeConfig.SerialiseDto(),
Salt = new byte[keyLengthBytes]
};
StratCom.EntropySupplier.NextBytes(config.Salt);
return config;
}
#endregion
/// <summary>
/// Write package out to bound stream.
/// </summary>
/// <param name="outputStream">Stream which the package is to be written to.</param>
/// <param name="closeOnComplete">Whether to close the destination stream upon completion of writing.</param>
/// <exception cref="NotSupportedException">Unsupported manifest cryptographic scheme attempted to be used.</exception>
/// <exception cref="InvalidOperationException">Package state incomplete, or attempted to write package twice.</exception>
/// <exception cref="AggregateException">
/// Collection of however many items have no stream bindings (as <see cref="ItemStreamBindingAbsentException" />)
/// or keys (as <see cref="ItemStreamBindingAbsentException" />).
/// </exception>
public void Write(Stream outputStream, bool closeOnComplete = true)
{
Contract.Requires<ArgumentNullException>(outputStream != null);
Contract.Requires(outputStream != Stream.Null, "Stream is set to where bits go to die.");
Contract.Requires(outputStream.CanWrite, "Cannot write to output stream.");
// Contract.Ensures(_writingComplete == false,
// "Multiple writes from one package are not supported; it may compromise security properties.");
// Contract.Ensures(_manifestHeaderCryptoConfig != null,
// "Manifest cryptography scheme and its configuration is not set up.");
if (_manifest.PayloadItems.Count == 0) {
throw new InvalidOperationException("No payload items.");
}
// Check if any payload items are missing stream bindings or keys before proceeding
IEnumerable<ItemStreamBindingAbsentException> streamBindingAbsentExceptions =
(from item in _manifest.PayloadItems.AsQueryExpr()
where item.StreamHasBinding == false
select new ItemStreamBindingAbsentException(item)).Run();
IEnumerable<ItemKeyMissingException> keyMissingExceptions =
(from payloadItem in _manifest.PayloadItems.AsQueryExpr()
where _itemPreKeys.ContainsKey(payloadItem.Identifier) == false
&& (payloadItem.SymmetricCipherKey.IsNullOrZeroLength()
|| payloadItem.AuthenticationKey.IsNullOrZeroLength())
select new ItemKeyMissingException(payloadItem)).Run();
Exception[] streamOrKeyExceptions =
streamBindingAbsentExceptions.Concat<Exception>(keyMissingExceptions).ToArray();
if (streamOrKeyExceptions.Length > 0) {
throw new AggregateException(streamOrKeyExceptions);
}
// Write the package header tag
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "[*PACKAGE START*] Offset",
outputStream.Position));
byte[] headerTag = Athena.Packaging.GetPackageHeaderTag();
outputStream.Write(headerTag, 0, headerTag.Length);
/* Derive working manifest encryption & authentication keys from the manifest pre-key */
byte[] workingManifestCipherKey, workingManifestMacKey;
GetWorkingKeys(out workingManifestMacKey, out workingManifestCipherKey);
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "Manifest MAC working key",
workingManifestMacKey.ToHexString()));
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "Manifest cipher working key",
workingManifestCipherKey.ToHexString()));
long manifestHeaderStartPosition = outputStream.Position;
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "Manifest header offset (absolute)",
manifestHeaderStartPosition));
/* Determine the needed [manifest header + manifest] placeholder length */
int requiredPlaceholderLength = CalculateRequiredMHMPlaceholder();
// Write the required placeholder
int writtenPlaceholder = 0;
while (writtenPlaceholder < requiredPlaceholderLength) {
int toWrite = Math.Min(requiredPlaceholderLength - writtenPlaceholder, MPlaceholderBytes.Length);
outputStream.Write(MPlaceholderBytes, 0, toWrite);
writtenPlaceholder += toWrite;
}
long payloadStartPosition = outputStream.Position;
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "Payload offset (absolute)",
payloadStartPosition));
/* Write the payload */
try {
var payloadScheme = _manifest.PayloadConfiguration.SchemeName.ToEnum<PayloadLayoutScheme>();
// Bind the multiplexer to the output stream
PayloadMux mux = PayloadMuxFactory.CreatePayloadMultiplexer(payloadScheme, true, outputStream,
_manifest.PayloadItems, _itemPreKeys, _manifest.PayloadConfiguration);
mux.Execute();
} catch (EnumerationParsingException e) {
throw new ConfigurationInvalidException(
"Package payload schema specified is unsupported/unknown or missing.", e);
} catch (Exception e) {
throw new Exception("Payload multiplexing failed. More information in inner exception.", e);
}
long payloadEndPosition = outputStream.Position;
/*
* The manifest will now have all necessary information to write it into the placeholder location.
* ^ This information was generated by and written by the payload multiplexer.
* Write the manifest in encrypted + authenticated form to memory at first, then to actual output
*/
outputStream.Seek(manifestHeaderStartPosition, SeekOrigin.Begin);
using (MemoryStream mhmStream = GetManifest(workingManifestMacKey, workingManifestCipherKey)) {
mhmStream.WriteTo(outputStream);
}
outputStream.Seek(payloadEndPosition, SeekOrigin.Begin);
// Clear manifest keys from memory
workingManifestMacKey.SecureWipe();
workingManifestCipherKey.SecureWipe();
// Write the trailer tag
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "Trailer offset (absolute)",
outputStream.Position));
byte[] trailerTag = Athena.Packaging.GetPackageTrailerTag();
outputStream.Write(trailerTag, 0, trailerTag.Length);
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "Write", "[* PACKAGE END *] Offset (absolute)",
outputStream.Position));
// All done!
if (closeOnComplete) {
outputStream.Close();
}
_writingComplete = true;
}
/// <summary>
/// Derives working MAC and cipher keys from the manifest pre-key using KDF key-stretching.
/// </summary>
/// <param name="workingManifestMacKey">Output auth/MAC key.</param>
/// <param name="workingManifestCipherKey">Output cipher key.</param>
private void GetWorkingKeys(out byte[] workingManifestMacKey, out byte[] workingManifestCipherKey)
{
Debug.Assert(_manifestHeaderCryptoConfig.Authentication.KeySizeBits != null,
"Manifest authentication key size should not be null");
KeyStretchingUtility.DeriveWorkingKeys(_writingPreManifestKey,
_manifestHeaderCryptoConfig.SymmetricCipher.KeySizeBits.BitsToBytes(),
_manifestHeaderCryptoConfig.Authentication.KeySizeBits.Value.BitsToBytes(),
_manifestHeaderCryptoConfig.KeyDerivation,
out workingManifestCipherKey, out workingManifestMacKey);
}
/// <summary>
/// Gets the output size in bytes of the function specified by <see cref="config"/>.
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public static int GetOutputSize(AuthenticationConfiguration config)
{
if (config.FunctionType == AuthenticationFunctionType.Mac) {
MacFunction macEnum;
try {
macEnum = config.FunctionName.ToEnum<MacFunction>();
} catch (Exception e) {
throw new ArgumentException();
}
var macInfo = Athena.Cryptography.MacFunctions[macEnum];
if (macInfo.OutputSize != null) {
return macInfo.OutputSize.Value;
}
// Function is HMAC/CMAC (output size determined by internal working function state size)
if (macEnum == MacFunction.Hmac) {
string hashFunctionName = Encoding.UTF8.GetString(config.FunctionConfiguration);
if (String.IsNullOrEmpty(hashFunctionName)) {
throw new ConfigurationInvalidException("HMAC configuration does not specify an internal hash/digest function.");
}
HashFunction hashFunctionEnum;
try {
hashFunctionEnum = hashFunctionName.ToEnum<HashFunction>();
} catch (Exception e) {
throw new ConfigurationInvalidException(
"HMAC configuration specifies an unknown/invalid internal hash/digest function.", e);
}
return Athena.Cryptography.HashFunctions[hashFunctionEnum].OutputSizeBits;
} else if (macEnum == MacFunction.Cmac) {
string cipherName = Encoding.UTF8.GetString(config.FunctionConfiguration);
if (String.IsNullOrEmpty(cipherName)) {
throw new ConfigurationInvalidException("CMAC configuration does not specify an internal block cipher.");
}
BlockCipher cipherEnum;
try {
cipherEnum = cipherName.ToEnum<BlockCipher>();
} catch (Exception e) {
throw new ConfigurationInvalidException(
"CMAC configuration specifies an unknown/invalid internal block cipher.", e);
}
int[] cipherBlockSizes = Athena.Cryptography.BlockCiphers[cipherEnum].AllowableBlockSizesBits;
if ((128).IsOneOf(cipherBlockSizes)) {
return 16;
} else if ((64).IsOneOf(cipherBlockSizes)) {
return 8;
}
throw new ConfigurationInvalidException(
"Internal block cipher specified by CMAC configuration does not support any of the necessary block sizes required by CMAC.");
}
throw new NotSupportedException();
} else if (config.FunctionType == AuthenticationFunctionType.Digest) {
if (String.IsNullOrEmpty(config.FunctionName)) {
throw new ConfigurationInvalidException("Configuration does not specify an internal hash/digest function.");
}
HashFunction hashFunctionEnum;
try {
hashFunctionEnum = config.FunctionName.ToEnum<HashFunction>();
} catch (Exception e) {
throw new ConfigurationInvalidException("Configuration specifies an unknown/invalid hash/digest function.", e);
}
return Athena.Cryptography.HashFunctions[hashFunctionEnum].OutputSizeBits;
} else if (config.FunctionType == AuthenticationFunctionType.Kdf) {
KeyDerivationFunction kdfEnum;
try {
kdfEnum = config.FunctionName.ToEnum<KeyDerivationFunction>();
} catch (Exception e) {
throw new ConfigurationInvalidException(
"Configuration specifies an unknown/invalid key derivation function (used for authentication, here).", e);
}
if (kdfEnum == KeyDerivationFunction.Pbkdf2) {
var pbkdf2Config = config.FunctionConfiguration.DeserialiseDto<Pbkdf2Configuration>();
if (String.IsNullOrEmpty(pbkdf2Config.FunctionName)) {
throw new ConfigurationInvalidException(
"PBKDF2 key derivation function configuration does not specify an internal hash/digest function.");
}
HashFunction hashFunctionEnum;
try {
hashFunctionEnum = pbkdf2Config.FunctionName.ToEnum<HashFunction>();
} catch (Exception e) {
throw new ConfigurationInvalidException(
"PBKDF2 key derivation function configuration specifies an unknown/invalid hash/digest function.", e);
}
return Athena.Cryptography.HashFunctions[hashFunctionEnum].OutputSizeBits;
} else if (kdfEnum == KeyDerivationFunction.Pbkdf2) {
var scryptConfig = config.FunctionConfiguration.DeserialiseDto<ScryptConfiguration>();
//scryptConfig.
} else {
// dfw
}
} else {
// defwf
}
return 0;
}
/// <summary>
/// Calculate the required length for the manifest header + manifest placeholder (MH+M).
/// </summary>
/// <returns>Required length of the placeholder.</returns>
private int CalculateRequiredMHMPlaceholder()
{
var manifestMacEnum = _manifestHeaderCryptoConfig.Authentication.FunctionName.ToEnum<MacFunction>();
// TODO: Detect for corner cases such as HMAC/CMAC
// ... where Athena HashSize.Value will be null (have to base on digest/cipher, respectively)
int manifestMacOutputSizeBytes = Athena.Cryptography.MacFunctions[manifestMacEnum].OutputSize.Value.BitsToBytes();
ManifestHeader mhTemp = GetManifestHeader(new byte[manifestMacOutputSizeBytes]);
int mhPlaceholderLength;
try {
MemoryStream mhTempMS = mhTemp.SerialiseDto(true);
mhPlaceholderLength = (int) mhTempMS.Length;
} catch (Exception e) {
throw new Exception("Failed to generate manifest header authentication output placeholder prior to writing payload.", e);
}
try {
foreach (PayloadItem item in _manifest.PayloadItems) {
// Insert item MAC output placeholder
var itemMacEnum = item.Authentication.FunctionName.ToEnum<MacFunction>();
// TODO: Detect for corner cases such as HMAC/CMAC
// ... where Athena HashSize.Value will be null (have to base on digest/cipher, respectively)
int itemMacOutputSizeBytes = Athena.Cryptography.MacFunctions[itemMacEnum].OutputSize.Value.BitsToBytes();
item.AuthenticationVerifiedOutput = new byte[itemMacOutputSizeBytes];
// Don't have to put a placeholder for item internal length since the DTO field is fixed-size.
}
} catch (Exception e) {
throw new Exception("Failed to generate payload item authentication output placeholders prior to writing payload.", e);
}
int manifestPlaceholderLength;
try {
byte[] tempManifestBytes = _manifest.SerialiseDto();
manifestPlaceholderLength = sizeof(UInt32) + tempManifestBytes.Length; // inc. prefix
} catch (Exception e) {
throw new Exception(
"Serialisation error when determining manifest placeholder length prior to writing payload.", e);
}
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "CalculateRequiredMHMPlaceholder",
"Calculated manifest header length",
mhPlaceholderLength));
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "CalculateRequiredMHMPlaceholder",
"Calculated manifest length",
manifestPlaceholderLength));
return mhPlaceholderLength + manifestPlaceholderLength;
}
/// <summary>
/// Generates a <see cref="ManifestHeader" /> DTO object from current configuration.
/// </summary>
/// <param name="manifestAuthenticationOutput">
/// Value to insert as authentication output. Depends on step of package creation.
/// </param>
private ManifestHeader GetManifestHeader(byte[] manifestAuthenticationOutput)
{
byte[] schemeConfig = null;
try {
switch (ManifestCryptoScheme) {
case ManifestCryptographyScheme.SymmetricOnly:
var symConfig = (SymmetricManifestCryptographyConfiguration) _manifestHeaderCryptoConfig;
symConfig.AuthenticationVerifiedOutput = manifestAuthenticationOutput;
schemeConfig = symConfig.SerialiseDto();
break;
case ManifestCryptographyScheme.Um1Hybrid:
var um1Config = (Um1HybridManifestCryptographyConfiguration) _manifestHeaderCryptoConfig;
um1Config.AuthenticationVerifiedOutput = manifestAuthenticationOutput;
schemeConfig = um1Config.SerialiseDto();
break;
}
} catch (Exception e) {
throw new Exception("Error while serialising manifest cryptography configuration for manifest header.", e);
}
Debug.Assert(schemeConfig != null, "schemeConfig == null");
return new ManifestHeader {
FormatVersion = _formatVersion,
CryptographyScheme = _manifestHeaderCryptoScheme,
CryptographySchemeConfiguration = schemeConfig
};
}
/// <summary>
/// Generates and writes a <see cref="Manifest" /> DTO object to memory.
/// </summary>
/// <param name="workingMacKey">Key for authenticating the manifest.</param>
/// <param name="workingCipherKey">Key for encrypting the manifest.</param>
/// <returns></returns>
private MemoryStream GetManifest(byte[] workingMacKey, byte[] workingCipherKey)
{
var outputStream = new MemoryStream();
var manifestTemp = new MemoryStream();
byte[] manifestMac = null;
using (var authenticator = new MacStream(manifestTemp, true,
_manifestHeaderCryptoConfig.Authentication, out manifestMac, workingMacKey, false)) {
using (var encryptor = new CipherStream(authenticator, true,
_manifestHeaderCryptoConfig.SymmetricCipher, workingCipherKey, false)) {
_manifest.SerialiseDto(encryptor, false);
}
var lengthUint = (UInt32) authenticator.BytesOut;
byte[] lengthPrefix = lengthUint.ToLittleEndian();
authenticator.Update(lengthPrefix, 0, sizeof(UInt32));
byte[] manifestCryptoDtoForAuth;
switch (ManifestCryptoScheme) {
case ManifestCryptographyScheme.SymmetricOnly: {
var symConfig = _manifestHeaderCryptoConfig as SymmetricManifestCryptographyConfiguration;
Debug.Assert(symConfig != null,
"'symConfig' is null - casting of '_manifestHeaderCryptoConfig' must have failed.");
manifestCryptoDtoForAuth = symConfig.CreateAuthenticatibleClone().SerialiseDto();
break;
}
case ManifestCryptographyScheme.Um1Hybrid: {
var um1Config = _manifestHeaderCryptoConfig as Um1HybridManifestCryptographyConfiguration;
Debug.Assert(um1Config != null,
"um1Config is null - casting of '_manifestHeaderCryptoConfig' must have failed.");
manifestCryptoDtoForAuth = um1Config.CreateAuthenticatibleClone().SerialiseDto();
break;
}
default:
throw new NotSupportedException();
}
authenticator.Update(manifestCryptoDtoForAuth, 0, manifestCryptoDtoForAuth.Length);
}
Debug.Assert(manifestMac != null,
"'manifestMac' is null. It should have been set when 'authenticator' was closed.");
// Serialise and write ManifestHeader
ManifestHeader mh = GetManifestHeader(manifestMac);
mh.SerialiseDto(outputStream, prefixLength: true);
/* Write length prefix */
// Generate length prefix as 32b little-endian unsigned integer
var manifestLengthPrefixUint = (UInt32) manifestTemp.Length;
byte[] manifestLengthPrefixLe = manifestLengthPrefixUint.ToLittleEndian();
Debug.Assert(manifestLengthPrefixLe.Length == sizeof(UInt32));
// Obfuscate the manifest length header by XORing it with the derived manifest MAC (authentication) key
manifestLengthPrefixLe.XorInPlaceInternal(0, workingMacKey, 0, sizeof(UInt32));
// Write the now-obfuscated manifest length header
outputStream.Write(manifestLengthPrefixLe, 0, sizeof(UInt32));
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "GetManifest",
"Manifest header length",
outputStream.Position));
Debug.Print(DebugUtility.CreateReportString("PackageWriter", "GetManifest",
"Manifest length",
manifestTemp.Length));
// Write manifest
manifestTemp.WriteTo(outputStream);
outputStream.Seek(0, SeekOrigin.Begin);
return outputStream;
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindRepository
{
/// <summary>
/// Strongly-typed collection for the Shipper class.
/// </summary>
[Serializable]
public partial class ShipperCollection : RepositoryList<Shipper, ShipperCollection>
{
public ShipperCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ShipperCollection</returns>
public ShipperCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Shipper o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Shippers table.
/// </summary>
[Serializable]
public partial class Shipper : RepositoryRecord<Shipper>, IRecordBase
{
#region .ctors and Default Settings
public Shipper()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Shipper(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Shippers", TableType.Table, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarShipperID = new TableSchema.TableColumn(schema);
colvarShipperID.ColumnName = "ShipperID";
colvarShipperID.DataType = DbType.Int32;
colvarShipperID.MaxLength = 0;
colvarShipperID.AutoIncrement = true;
colvarShipperID.IsNullable = false;
colvarShipperID.IsPrimaryKey = true;
colvarShipperID.IsForeignKey = false;
colvarShipperID.IsReadOnly = false;
colvarShipperID.DefaultSetting = @"";
colvarShipperID.ForeignKeyTableName = "";
schema.Columns.Add(colvarShipperID);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
colvarCompanyName.DefaultSetting = @"";
colvarCompanyName.ForeignKeyTableName = "";
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema);
colvarPhone.ColumnName = "Phone";
colvarPhone.DataType = DbType.String;
colvarPhone.MaxLength = 24;
colvarPhone.AutoIncrement = false;
colvarPhone.IsNullable = true;
colvarPhone.IsPrimaryKey = false;
colvarPhone.IsForeignKey = false;
colvarPhone.IsReadOnly = false;
colvarPhone.DefaultSetting = @"";
colvarPhone.ForeignKeyTableName = "";
schema.Columns.Add(colvarPhone);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("Shippers",schema);
}
}
#endregion
#region Props
[XmlAttribute("ShipperID")]
[Bindable(true)]
public int ShipperID
{
get { return GetColumnValue<int>(Columns.ShipperID); }
set { SetColumnValue(Columns.ShipperID, value); }
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get { return GetColumnValue<string>(Columns.CompanyName); }
set { SetColumnValue(Columns.CompanyName, value); }
}
[XmlAttribute("Phone")]
[Bindable(true)]
public string Phone
{
get { return GetColumnValue<string>(Columns.Phone); }
set { SetColumnValue(Columns.Phone, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region Typed Columns
public static TableSchema.TableColumn ShipperIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CompanyNameColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn PhoneColumn
{
get { return Schema.Columns[2]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string ShipperID = @"ShipperID";
public static string CompanyName = @"CompanyName";
public static string Phone = @"Phone";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#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.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class HttpResponseMessage : IDisposable
{
private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK;
private HttpStatusCode _statusCode;
private HttpResponseHeaders _headers;
private string _reasonPhrase;
private HttpRequestMessage _requestMessage;
private Version _version;
private HttpContent _content;
private bool _disposed;
public Version Version
{
get { return _version; }
set
{
#if !PHONE
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
#endif
CheckDisposed();
_version = value;
}
}
public HttpContent Content
{
get { return _content; }
set
{
CheckDisposed();
if (HttpEventSource.Log.IsEnabled())
{
if (value == null)
{
HttpEventSource.ContentNull(this);
}
else
{
HttpEventSource.Associate(this, value);
}
}
_content = value;
}
}
public HttpStatusCode StatusCode
{
get { return _statusCode; }
set
{
if (((int)value < 0) || ((int)value > 999))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposed();
_statusCode = value;
}
}
public string ReasonPhrase
{
get
{
if (_reasonPhrase != null)
{
return _reasonPhrase;
}
// Provide a default if one was not set.
return HttpStatusDescription.Get(StatusCode);
}
set
{
if ((value != null) && ContainsNewLineCharacter(value))
{
throw new FormatException(SR.net_http_reasonphrase_format_error);
}
CheckDisposed();
_reasonPhrase = value; // It's OK to have a 'null' reason phrase.
}
}
public HttpResponseHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpResponseHeaders();
}
return _headers;
}
}
public HttpRequestMessage RequestMessage
{
get { return _requestMessage; }
set
{
CheckDisposed();
if (HttpEventSource.Log.IsEnabled() && (value != null)) HttpEventSource.Associate(this, value);
_requestMessage = value;
}
}
public bool IsSuccessStatusCode
{
get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); }
}
public HttpResponseMessage()
: this(defaultStatusCode)
{
}
public HttpResponseMessage(HttpStatusCode statusCode)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "StatusCode: " + (int)statusCode + ", ReasonPhrase: '" + _reasonPhrase + "'");
if (((int)statusCode < 0) || ((int)statusCode > 999))
{
throw new ArgumentOutOfRangeException(nameof(statusCode));
}
_statusCode = statusCode;
_version = HttpUtilities.DefaultResponseVersion;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
public HttpResponseMessage EnsureSuccessStatusCode()
{
if (!IsSuccessStatusCode)
{
// Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is
// thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g.
// connection failure). Users don't expect to dispose the content in this case: If an exception is
// thrown, the object is responsible fore cleaning up its state.
if (_content != null)
{
_content.Dispose();
}
throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode,
ReasonPhrase));
}
return this;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("StatusCode: ");
sb.Append((int)_statusCode);
sb.Append(", ReasonPhrase: '");
sb.Append(ReasonPhrase ?? "<null>");
sb.Append("', Version: ");
sb.Append(_version);
sb.Append(", Content: ");
sb.Append(_content == null ? "<null>" : _content.GetType().ToString());
sb.Append(", Headers:\r\n");
sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers));
return sb.ToString();
}
private bool ContainsNewLineCharacter(string value)
{
foreach (char character in value)
{
if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF))
{
return true;
}
}
return false;
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of types that implement
// IDisposable (content).
if (disposing && !_disposed)
{
_disposed = true;
if (_content != null)
{
_content.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
}
}
| |
#region License
/*
* WebSocketBehavior.cs
*
* The MIT License
*
* Copyright (c) 2012-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.IO;
using CustomWebSocketSharp.Net;
using CustomWebSocketSharp.Net.WebSockets;
namespace CustomWebSocketSharp.Server
{
/// <summary>
/// Exposes the methods and properties used to define the behavior of a WebSocket service
/// provided by the <see cref="WebSocketServer"/> or <see cref="HttpServer"/>.
/// </summary>
/// <remarks>
/// The WebSocketBehavior class is an abstract class.
/// </remarks>
public abstract class WebSocketBehavior : IWebSocketSession
{
#region Private Fields
private WebSocketContext _context;
private Func<CookieCollection, CookieCollection, bool> _cookiesValidator;
private bool _emitOnPing;
private string _id;
private bool _ignoreExtensions;
private Func<string, bool> _originValidator;
private string _protocol;
private WebSocketSessionManager _sessions;
private DateTime _startTime;
private WebSocket _websocket;
#endregion
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketBehavior"/> class.
/// </summary>
protected WebSocketBehavior ()
{
_startTime = DateTime.MaxValue;
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions,
/// or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
protected Logger Log {
get {
return _websocket != null ? _websocket.Log : null;
}
}
/// <summary>
/// Gets the access to the sessions in the WebSocket service.
/// </summary>
/// <value>
/// A <see cref="WebSocketSessionManager"/> that provides the access to the sessions,
/// or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
protected WebSocketSessionManager Sessions {
get {
return _sessions;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the information in a handshake request to the WebSocket service.
/// </summary>
/// <value>
/// A <see cref="WebSocketContext"/> instance that provides the access to the handshake request,
/// or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
public WebSocketContext Context {
get {
return _context;
}
}
/// <summary>
/// Gets or sets the delegate called to validate the HTTP cookies included in
/// a handshake request to the WebSocket service.
/// </summary>
/// <remarks>
/// This delegate is called when the <see cref="WebSocket"/> used in a session validates
/// the handshake request.
/// </remarks>
/// <value>
/// <para>
/// A <c>Func<CookieCollection, CookieCollection, bool></c> delegate that references
/// the method(s) used to validate the cookies.
/// </para>
/// <para>
/// 1st <see cref="CookieCollection"/> parameter passed to this delegate contains
/// the cookies to validate if any.
/// </para>
/// <para>
/// 2nd <see cref="CookieCollection"/> parameter passed to this delegate receives
/// the cookies to send to the client.
/// </para>
/// <para>
/// This delegate should return <c>true</c> if the cookies are valid.
/// </para>
/// <para>
/// The default value is <see langword="null"/>, and it does nothing to validate.
/// </para>
/// </value>
public Func<CookieCollection, CookieCollection, bool> CookiesValidator {
get {
return _cookiesValidator;
}
set {
_cookiesValidator = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the <see cref="WebSocket"/> used in a session emits
/// a <see cref="WebSocket.OnMessage"/> event when receives a Ping.
/// </summary>
/// <value>
/// <c>true</c> if the <see cref="WebSocket"/> emits a <see cref="WebSocket.OnMessage"/> event
/// when receives a Ping; otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool EmitOnPing {
get {
return _websocket != null ? _websocket.EmitOnPing : _emitOnPing;
}
set {
if (_websocket != null) {
_websocket.EmitOnPing = value;
return;
}
_emitOnPing = value;
}
}
/// <summary>
/// Gets the unique ID of a session.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the unique ID of the session,
/// or <see langword="null"/> if the WebSocket connection isn't established.
/// </value>
public string ID {
get {
return _id;
}
}
/// <summary>
/// Gets or sets a value indicating whether the WebSocket service ignores
/// the Sec-WebSocket-Extensions header included in a handshake request.
/// </summary>
/// <value>
/// <c>true</c> if the WebSocket service ignores the extensions requested from
/// a client; otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool IgnoreExtensions {
get {
return _ignoreExtensions;
}
set {
_ignoreExtensions = value;
}
}
/// <summary>
/// Gets or sets the delegate called to validate the Origin header included in
/// a handshake request to the WebSocket service.
/// </summary>
/// <remarks>
/// This delegate is called when the <see cref="WebSocket"/> used in a session validates
/// the handshake request.
/// </remarks>
/// <value>
/// <para>
/// A <c>Func<string, bool></c> delegate that references the method(s) used to
/// validate the origin header.
/// </para>
/// <para>
/// <see cref="string"/> parameter passed to this delegate represents the value of
/// the origin header to validate if any.
/// </para>
/// <para>
/// This delegate should return <c>true</c> if the origin header is valid.
/// </para>
/// <para>
/// The default value is <see langword="null"/>, and it does nothing to validate.
/// </para>
/// </value>
public Func<string, bool> OriginValidator {
get {
return _originValidator;
}
set {
_originValidator = value;
}
}
/// <summary>
/// Gets or sets the WebSocket subprotocol used in the WebSocket service.
/// </summary>
/// <remarks>
/// Set operation of this property is available before the WebSocket connection has
/// been established.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the subprotocol if any.
/// The default value is <see cref="String.Empty"/>.
/// </para>
/// <para>
/// The value to set must be a token defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-2.2">RFC 2616</see>.
/// </para>
/// </value>
public string Protocol {
get {
return _websocket != null ? _websocket.Protocol : (_protocol ?? String.Empty);
}
set {
if (State != WebSocketState.Connecting)
return;
if (value != null && (value.Length == 0 || !value.IsToken ()))
return;
_protocol = value;
}
}
/// <summary>
/// Gets the time that a session has started.
/// </summary>
/// <value>
/// A <see cref="DateTime"/> that represents the time that the session has started,
/// or <see cref="DateTime.MaxValue"/> if the WebSocket connection isn't established.
/// </value>
public DateTime StartTime {
get {
return _startTime;
}
}
/// <summary>
/// Gets the state of the <see cref="WebSocket"/> used in a session.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketState"/> enum values, indicates the state of
/// the <see cref="WebSocket"/>.
/// </value>
public WebSocketState State {
get {
return _websocket != null ? _websocket.ReadyState : WebSocketState.Connecting;
}
}
#endregion
#region Private Methods
private string checkHandshakeRequest (WebSocketContext context)
{
return _originValidator != null && !_originValidator (context.Origin)
? "Includes no Origin header, or it has an invalid value."
: _cookiesValidator != null
&& !_cookiesValidator (context.CookieCollection, context.WebSocket.CookieCollection)
? "Includes no cookie, or an invalid cookie exists."
: null;
}
private void onClose (object sender, CloseEventArgs e)
{
if (_id == null)
return;
_sessions.Remove (_id);
OnClose (e);
}
private void onError (object sender, ErrorEventArgs e)
{
OnError (e);
}
private void onMessage (object sender, MessageEventArgs e)
{
OnMessage (e);
}
private void onOpen (object sender, EventArgs e)
{
_id = _sessions.Add (this);
if (_id == null) {
_websocket.Close (CloseStatusCode.Away);
return;
}
_startTime = DateTime.Now;
OnOpen ();
}
#endregion
#region Internal Methods
internal void Start (WebSocketContext context, WebSocketSessionManager sessions)
{
if (_websocket != null) {
_websocket.Log.Error ("A session instance cannot be reused.");
context.WebSocket.Close (HttpStatusCode.ServiceUnavailable);
return;
}
_context = context;
_sessions = sessions;
_websocket = context.WebSocket;
_websocket.CustomHandshakeRequestChecker = checkHandshakeRequest;
_websocket.EmitOnPing = _emitOnPing;
_websocket.IgnoreExtensions = _ignoreExtensions;
_websocket.Protocol = _protocol;
var waitTime = sessions.WaitTime;
if (waitTime != _websocket.WaitTime)
_websocket.WaitTime = waitTime;
_websocket.OnOpen += onOpen;
_websocket.OnMessage += onMessage;
_websocket.OnError += onError;
_websocket.OnClose += onClose;
_websocket.InternalAccept ();
}
#endregion
#region Protected Methods
/// <summary>
/// Calls the <see cref="OnError"/> method with the specified <paramref name="message"/> and
/// <paramref name="exception"/>.
/// </summary>
/// <remarks>
/// This method doesn't call the <see cref="OnError"/> method if <paramref name="message"/> is
/// <see langword="null"/> or empty.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that represents the error message.
/// </param>
/// <param name="exception">
/// An <see cref="Exception"/> instance that represents the cause of the error if any.
/// </param>
protected void Error (string message, Exception exception)
{
if (message != null && message.Length > 0)
OnError (new ErrorEventArgs (message, exception));
}
/// <summary>
/// Called when the WebSocket connection used in a session has been closed.
/// </summary>
/// <param name="e">
/// A <see cref="CloseEventArgs"/> that represents the event data passed to
/// a <see cref="WebSocket.OnClose"/> event.
/// </param>
protected virtual void OnClose (CloseEventArgs e)
{
}
/// <summary>
/// Called when the <see cref="WebSocket"/> used in a session gets an error.
/// </summary>
/// <param name="e">
/// A <see cref="ErrorEventArgs"/> that represents the event data passed to
/// a <see cref="WebSocket.OnError"/> event.
/// </param>
protected virtual void OnError (ErrorEventArgs e)
{
}
/// <summary>
/// Called when the <see cref="WebSocket"/> used in a session receives a message.
/// </summary>
/// <param name="e">
/// A <see cref="MessageEventArgs"/> that represents the event data passed to
/// a <see cref="WebSocket.OnMessage"/> event.
/// </param>
protected virtual void OnMessage (MessageEventArgs e)
{
}
/// <summary>
/// Called when the WebSocket connection used in a session has been established.
/// </summary>
protected virtual void OnOpen ()
{
}
/// <summary>
/// Sends binary <paramref name="data"/> to the client on a session.
/// </summary>
/// <remarks>
/// This method is available after the WebSocket connection has been established.
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
protected void Send (byte[] data)
{
if (_websocket != null)
_websocket.Send (data);
}
/// <summary>
/// Sends the specified <paramref name="file"/> as binary data to the client on a session.
/// </summary>
/// <remarks>
/// This method is available after the WebSocket connection has been established.
/// </remarks>
/// <param name="file">
/// A <see cref="FileInfo"/> that represents the file to send.
/// </param>
protected void Send (FileInfo file)
{
if (_websocket != null)
_websocket.Send (file);
}
/// <summary>
/// Sends text <paramref name="data"/> to the client on a session.
/// </summary>
/// <remarks>
/// This method is available after the WebSocket connection has been established.
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
protected void Send (string data)
{
if (_websocket != null)
_websocket.Send (data);
}
/// <summary>
/// Sends binary <paramref name="data"/> asynchronously to the client on a session.
/// </summary>
/// <remarks>
/// <para>
/// This method is available after the WebSocket connection has been established.
/// </para>
/// <para>
/// This method doesn't wait for the send to be complete.
/// </para>
/// </remarks>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to send.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
protected void SendAsync (byte[] data, Action<bool> completed)
{
if (_websocket != null)
_websocket.SendAsync (data, completed);
}
/// <summary>
/// Sends the specified <paramref name="file"/> as binary data asynchronously to
/// the client on a session.
/// </summary>
/// <remarks>
/// <para>
/// This method is available after the WebSocket connection has been established.
/// </para>
/// <para>
/// This method doesn't wait for the send to be complete.
/// </para>
/// </remarks>
/// <param name="file">
/// A <see cref="FileInfo"/> that represents the file to send.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
protected void SendAsync (FileInfo file, Action<bool> completed)
{
if (_websocket != null)
_websocket.SendAsync (file, completed);
}
/// <summary>
/// Sends text <paramref name="data"/> asynchronously to the client on a session.
/// </summary>
/// <remarks>
/// <para>
/// This method is available after the WebSocket connection has been established.
/// </para>
/// <para>
/// This method doesn't wait for the send to be complete.
/// </para>
/// </remarks>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to send.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
protected void SendAsync (string data, Action<bool> completed)
{
if (_websocket != null)
_websocket.SendAsync (data, completed);
}
/// <summary>
/// Sends binary data from the specified <see cref="Stream"/> asynchronously to
/// the client on a session.
/// </summary>
/// <remarks>
/// <para>
/// This method is available after the WebSocket connection has been established.
/// </para>
/// <para>
/// This method doesn't wait for the send to be complete.
/// </para>
/// </remarks>
/// <param name="stream">
/// A <see cref="Stream"/> from which contains the binary data to send.
/// </param>
/// <param name="length">
/// An <see cref="int"/> that represents the number of bytes to send.
/// </param>
/// <param name="completed">
/// An <c>Action<bool></c> delegate that references the method(s) called when
/// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c>
/// if the send is complete successfully.
/// </param>
protected void SendAsync (Stream stream, int length, Action<bool> completed)
{
if (_websocket != null)
_websocket.SendAsync (stream, length, completed);
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Settings/MapSettings.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Settings {
/// <summary>Holder for reflection information generated from POGOProtos/Settings/MapSettings.proto</summary>
public static partial class MapSettingsReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Settings/MapSettings.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MapSettingsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVQT0dPUHJvdG9zL1NldHRpbmdzL01hcFNldHRpbmdzLnByb3RvEhNQT0dP",
"UHJvdG9zLlNldHRpbmdzIo8CCgtNYXBTZXR0aW5ncxIdChVwb2tlbW9uX3Zp",
"c2libGVfcmFuZ2UYASABKAESHQoVcG9rZV9uYXZfcmFuZ2VfbWV0ZXJzGAIg",
"ASgBEh4KFmVuY291bnRlcl9yYW5nZV9tZXRlcnMYAyABKAESKwojZ2V0X21h",
"cF9vYmplY3RzX21pbl9yZWZyZXNoX3NlY29uZHMYBCABKAISKwojZ2V0X21h",
"cF9vYmplY3RzX21heF9yZWZyZXNoX3NlY29uZHMYBSABKAISKwojZ2V0X21h",
"cF9vYmplY3RzX21pbl9kaXN0YW5jZV9tZXRlcnMYBiABKAISGwoTZ29vZ2xl",
"X21hcHNfYXBpX2tleRgHIAEoCWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Settings.MapSettings), global::POGOProtos.Settings.MapSettings.Parser, new[]{ "PokemonVisibleRange", "PokeNavRangeMeters", "EncounterRangeMeters", "GetMapObjectsMinRefreshSeconds", "GetMapObjectsMaxRefreshSeconds", "GetMapObjectsMinDistanceMeters", "GoogleMapsApiKey" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class MapSettings : pb::IMessage<MapSettings> {
private static readonly pb::MessageParser<MapSettings> _parser = new pb::MessageParser<MapSettings>(() => new MapSettings());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MapSettings> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Settings.MapSettingsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MapSettings() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MapSettings(MapSettings other) : this() {
pokemonVisibleRange_ = other.pokemonVisibleRange_;
pokeNavRangeMeters_ = other.pokeNavRangeMeters_;
encounterRangeMeters_ = other.encounterRangeMeters_;
getMapObjectsMinRefreshSeconds_ = other.getMapObjectsMinRefreshSeconds_;
getMapObjectsMaxRefreshSeconds_ = other.getMapObjectsMaxRefreshSeconds_;
getMapObjectsMinDistanceMeters_ = other.getMapObjectsMinDistanceMeters_;
googleMapsApiKey_ = other.googleMapsApiKey_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MapSettings Clone() {
return new MapSettings(this);
}
/// <summary>Field number for the "pokemon_visible_range" field.</summary>
public const int PokemonVisibleRangeFieldNumber = 1;
private double pokemonVisibleRange_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PokemonVisibleRange {
get { return pokemonVisibleRange_; }
set {
pokemonVisibleRange_ = value;
}
}
/// <summary>Field number for the "poke_nav_range_meters" field.</summary>
public const int PokeNavRangeMetersFieldNumber = 2;
private double pokeNavRangeMeters_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double PokeNavRangeMeters {
get { return pokeNavRangeMeters_; }
set {
pokeNavRangeMeters_ = value;
}
}
/// <summary>Field number for the "encounter_range_meters" field.</summary>
public const int EncounterRangeMetersFieldNumber = 3;
private double encounterRangeMeters_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double EncounterRangeMeters {
get { return encounterRangeMeters_; }
set {
encounterRangeMeters_ = value;
}
}
/// <summary>Field number for the "get_map_objects_min_refresh_seconds" field.</summary>
public const int GetMapObjectsMinRefreshSecondsFieldNumber = 4;
private float getMapObjectsMinRefreshSeconds_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float GetMapObjectsMinRefreshSeconds {
get { return getMapObjectsMinRefreshSeconds_; }
set {
getMapObjectsMinRefreshSeconds_ = value;
}
}
/// <summary>Field number for the "get_map_objects_max_refresh_seconds" field.</summary>
public const int GetMapObjectsMaxRefreshSecondsFieldNumber = 5;
private float getMapObjectsMaxRefreshSeconds_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float GetMapObjectsMaxRefreshSeconds {
get { return getMapObjectsMaxRefreshSeconds_; }
set {
getMapObjectsMaxRefreshSeconds_ = value;
}
}
/// <summary>Field number for the "get_map_objects_min_distance_meters" field.</summary>
public const int GetMapObjectsMinDistanceMetersFieldNumber = 6;
private float getMapObjectsMinDistanceMeters_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float GetMapObjectsMinDistanceMeters {
get { return getMapObjectsMinDistanceMeters_; }
set {
getMapObjectsMinDistanceMeters_ = value;
}
}
/// <summary>Field number for the "google_maps_api_key" field.</summary>
public const int GoogleMapsApiKeyFieldNumber = 7;
private string googleMapsApiKey_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string GoogleMapsApiKey {
get { return googleMapsApiKey_; }
set {
googleMapsApiKey_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MapSettings);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MapSettings other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (PokemonVisibleRange != other.PokemonVisibleRange) return false;
if (PokeNavRangeMeters != other.PokeNavRangeMeters) return false;
if (EncounterRangeMeters != other.EncounterRangeMeters) return false;
if (GetMapObjectsMinRefreshSeconds != other.GetMapObjectsMinRefreshSeconds) return false;
if (GetMapObjectsMaxRefreshSeconds != other.GetMapObjectsMaxRefreshSeconds) return false;
if (GetMapObjectsMinDistanceMeters != other.GetMapObjectsMinDistanceMeters) return false;
if (GoogleMapsApiKey != other.GoogleMapsApiKey) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (PokemonVisibleRange != 0D) hash ^= PokemonVisibleRange.GetHashCode();
if (PokeNavRangeMeters != 0D) hash ^= PokeNavRangeMeters.GetHashCode();
if (EncounterRangeMeters != 0D) hash ^= EncounterRangeMeters.GetHashCode();
if (GetMapObjectsMinRefreshSeconds != 0F) hash ^= GetMapObjectsMinRefreshSeconds.GetHashCode();
if (GetMapObjectsMaxRefreshSeconds != 0F) hash ^= GetMapObjectsMaxRefreshSeconds.GetHashCode();
if (GetMapObjectsMinDistanceMeters != 0F) hash ^= GetMapObjectsMinDistanceMeters.GetHashCode();
if (GoogleMapsApiKey.Length != 0) hash ^= GoogleMapsApiKey.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (PokemonVisibleRange != 0D) {
output.WriteRawTag(9);
output.WriteDouble(PokemonVisibleRange);
}
if (PokeNavRangeMeters != 0D) {
output.WriteRawTag(17);
output.WriteDouble(PokeNavRangeMeters);
}
if (EncounterRangeMeters != 0D) {
output.WriteRawTag(25);
output.WriteDouble(EncounterRangeMeters);
}
if (GetMapObjectsMinRefreshSeconds != 0F) {
output.WriteRawTag(37);
output.WriteFloat(GetMapObjectsMinRefreshSeconds);
}
if (GetMapObjectsMaxRefreshSeconds != 0F) {
output.WriteRawTag(45);
output.WriteFloat(GetMapObjectsMaxRefreshSeconds);
}
if (GetMapObjectsMinDistanceMeters != 0F) {
output.WriteRawTag(53);
output.WriteFloat(GetMapObjectsMinDistanceMeters);
}
if (GoogleMapsApiKey.Length != 0) {
output.WriteRawTag(58);
output.WriteString(GoogleMapsApiKey);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (PokemonVisibleRange != 0D) {
size += 1 + 8;
}
if (PokeNavRangeMeters != 0D) {
size += 1 + 8;
}
if (EncounterRangeMeters != 0D) {
size += 1 + 8;
}
if (GetMapObjectsMinRefreshSeconds != 0F) {
size += 1 + 4;
}
if (GetMapObjectsMaxRefreshSeconds != 0F) {
size += 1 + 4;
}
if (GetMapObjectsMinDistanceMeters != 0F) {
size += 1 + 4;
}
if (GoogleMapsApiKey.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(GoogleMapsApiKey);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MapSettings other) {
if (other == null) {
return;
}
if (other.PokemonVisibleRange != 0D) {
PokemonVisibleRange = other.PokemonVisibleRange;
}
if (other.PokeNavRangeMeters != 0D) {
PokeNavRangeMeters = other.PokeNavRangeMeters;
}
if (other.EncounterRangeMeters != 0D) {
EncounterRangeMeters = other.EncounterRangeMeters;
}
if (other.GetMapObjectsMinRefreshSeconds != 0F) {
GetMapObjectsMinRefreshSeconds = other.GetMapObjectsMinRefreshSeconds;
}
if (other.GetMapObjectsMaxRefreshSeconds != 0F) {
GetMapObjectsMaxRefreshSeconds = other.GetMapObjectsMaxRefreshSeconds;
}
if (other.GetMapObjectsMinDistanceMeters != 0F) {
GetMapObjectsMinDistanceMeters = other.GetMapObjectsMinDistanceMeters;
}
if (other.GoogleMapsApiKey.Length != 0) {
GoogleMapsApiKey = other.GoogleMapsApiKey;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
PokemonVisibleRange = input.ReadDouble();
break;
}
case 17: {
PokeNavRangeMeters = input.ReadDouble();
break;
}
case 25: {
EncounterRangeMeters = input.ReadDouble();
break;
}
case 37: {
GetMapObjectsMinRefreshSeconds = input.ReadFloat();
break;
}
case 45: {
GetMapObjectsMaxRefreshSeconds = input.ReadFloat();
break;
}
case 53: {
GetMapObjectsMinDistanceMeters = input.ReadFloat();
break;
}
case 58: {
GoogleMapsApiKey = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Organizations;
using AllReady.Areas.Admin.Features.Site;
using AllReady.Areas.Admin.Features.Users;
using AllReady.Extensions;
using AllReady.Features.Manage;
using AllReady.Models;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Areas.Admin.ViewModels.Site;
using AllReady.Constants;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class SiteAdminControllerTest
{
[Fact]
public async Task IndexReturnsCorrectViewModel()
{
var users = new List<ApplicationUser> { new ApplicationUser { Id = It.IsAny<string>() }, new ApplicationUser { Id = It.IsAny<string>() }};
var viewModel = new IndexViewModel { Users = users };
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.IsAny<IndexQuery>())).ReturnsAsync(viewModel);
var controller = new SiteController(null, null, mediator.Object);
var result = await controller.Index() as ViewResult;
var model = result.ViewData.Model as IndexViewModel;
Assert.Equal(model.Users.Count(), users.Count());
Assert.IsType<IndexViewModel>(model);
}
[Fact]
public async Task DeleteUserSendsUserQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
const string userId = "foo_id";
mediator.Setup(x => x.SendAsync(It.Is<UserQuery>(q => q.UserId == userId))).ReturnsAsync(new EditUserViewModel());
var controller = new SiteController(null, null, mediator.Object);
await controller.DeleteUser(userId);
mediator.Verify(m =>m.SendAsync(It.Is<UserQuery>(q =>q.UserId == userId)), Times.Once);
}
[Fact]
public async Task DeleteUserReturnsTheCorrectViewModel()
{
var mediator = new Mock<IMediator>();
const string userId = "foo_id";
mediator.Setup(x => x.SendAsync(It.IsAny<UserQuery>())).ReturnsAsync(new EditUserViewModel());
var controller = new SiteController(null, null, mediator.Object);
var result = await controller.DeleteUser(userId);
var model = ((ViewResult)result).ViewData.Model as DeleteUserViewModel;
Assert.Equal(model.UserId, userId);
Assert.IsType<DeleteUserViewModel>(model);
}
[Fact]
public void DeleteUserHasHttpGetAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.DeleteUser(It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task ConfirmDeletUserInvokesFindByIdAsync()
{
const string userId = "userId";
var userManager = CreateApplicationUserMock();
var controller = new SiteController(userManager.Object, null, null);
await controller.ConfirmDeleteUser(userId);
userManager.Verify(x => x.FindByIdAsync(userId), Times.Once);
}
[Fact]
public async Task ConfirmDeletUserRedirectsToCorrectAction()
{
var applicationUser = CreateApplicationUserMock();
var controller = new SiteController(applicationUser.Object, null, null);
var result = await controller.ConfirmDeleteUser(It.IsAny<string>()) as RedirectToActionResult;
Assert.Equal(nameof(SiteController.Index), result.ActionName);
}
[Fact]
public void ConfirmDeletUserHasHttpPostAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.ConfirmDeleteUser(It.IsAny<string>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void ConfirmDeletUserHasValidateAntiForgeryTokenAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.ConfirmDeleteUser(It.IsAny<string>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task EditUserGetSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)))
.ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.EditUser(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task EditUserGetReturnsCorrectViewModelWhenOrganizationIdIsNull()
{
{
var mediator = new Mock<IMediator>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)))
.ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, null, mediator.Object);
var result = controller.EditUser(userId);
var model = ((ViewResult)await result).ViewData.Model as EditUserViewModel;
Assert.Null(model.Organization);
Assert.IsType<EditUserViewModel>(model);
}
}
[Fact]
public async Task EditUserGetReturnsCorrectValueForOrganiztionOnViewModelWhenOrganizationIdIsNotNull()
{
var mediator = new Mock<IMediator>();
var user = new ApplicationUser();
var orgId = 99;
var orgName = "Test Org";
var org = new Organization { Id = orgId, Name = orgName };
var userId = It.IsAny<string>();
user.Claims.Add(new Microsoft.AspNetCore.Identity.IdentityUserClaim<string>
{
ClaimType = AllReady.Security.ClaimTypes.Organization,
ClaimValue = orgId.ToString()
});
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)))
.ReturnsAsync(user);
mediator.Setup(x => x.Send(It.Is<OrganizationByIdQuery>(q => q.OrganizationId == orgId)))
.Returns(org);
var controller = new SiteController(null, null, mediator.Object);
var result = controller.EditUser(userId);
var model = ((ViewResult)await result).ViewData.Model as EditUserViewModel;
Assert.NotNull(model.Organization);
Assert.IsType<EditUserViewModel>(model);
}
[Fact]
public async Task EditUserPostReturnsSameViewAndViewModelWhenModelStateIsInvalid()
{
var model = new EditUserViewModel
{
UserId = "1234",
};
var controller = new SiteController(null, null, null);
controller.ModelState.AddModelError("FakeKey", "FakeMessage");
var result = (ViewResult)await controller.EditUser(model);
Assert.Equal(result.Model, model);
}
[Fact]
public async Task EditUserPostSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var model = new EditUserViewModel
{
UserId = "1234",
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
.ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, null, mediator.Object);
await controller.EditUser(model);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)), Times.Once);
}
[Fact]
public async Task EditUserPostSendsUpdateUserWithCorrectUserWhenUsersAssociatedSkillsAreNotNull()
{
var mediator = new Mock<IMediator>();
var model = new EditUserViewModel
{
UserId = It.IsAny<string>(),
AssociatedSkills = new List<UserSkill> { new UserSkill {Skill = It.IsAny<Skill>() } }
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
.ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, null, mediator.Object);
await controller.EditUser(model);
mediator.Verify(m => m.SendAsync(It.Is<UpdateUser>(q => q.User.AssociatedSkills[0].Skill == model.AssociatedSkills[0].Skill)), Times.Once);
}
[Fact]
public async Task EditUserPostInvokesUpdateUserWithCorrectUserWhenUsersAssociatedSkillsAreNotNullAndThereIsAtLeastOneAssociatedSkillForTheUser()
{
var mediator = new Mock<IMediator>();
var model = new EditUserViewModel
{
UserId = It.IsAny<string>(),
AssociatedSkills = new List<UserSkill> { new UserSkill { SkillId = 1, Skill = new Skill { Id = 1 } } }
};
var user = new ApplicationUser
{
Id = model.UserId,
AssociatedSkills = new List<UserSkill> { new UserSkill { SkillId = 2, Skill = new Skill { Id = 2 } } }
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
.ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
await controller.EditUser(model);
mediator.Verify(m => m.SendAsync(It.Is<UpdateUser>(q => q.User.AssociatedSkills[0] == model.AssociatedSkills[0])), Times.Once);
}
[Fact]
public async Task EditUserPostInvokesAddClaimAsyncWithCorrectParameters_WhenModelsIsOrganizationAdminIsTrue()
{
var userManager = CreateApplicationUserMock();
var model = new EditUserViewModel
{
IsOrganizationAdmin = true,
UserId = It.IsAny<string>()
};
var user = new ApplicationUser
{
Id = model.UserId,
Email = "test@testy.com"
};
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Success);
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetDefaultHttpContext();
controller.Url = GetMockUrlHelper("any");
await controller.EditUser(model);
userManager.Verify(x => x.AddClaimAsync(user, It.Is<Claim>(c => c.Value == nameof(UserType.OrgAdmin))), Times.Once);
}
[Fact]
public async Task EditUserPostInvokesUrlActionWithCorrectParametersWhenModelsIsOrganizationAdminIsTrueAndOrganizationAdminClaimWasAddedSuccessfully()
{
const string requestScheme = "requestScheme";
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var model = new EditUserViewModel
{
IsOrganizationAdmin = true,
UserId = It.IsAny<string>()
};
var user = new ApplicationUser
{
Id = model.UserId,
Email = "test@testy.com"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Success);
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetFakeHttpRequestSchemeTo(requestScheme);
var urlHelper = new Mock<IUrlHelper>();
controller.Url = urlHelper.Object;
await controller.EditUser(model);
urlHelper.Verify(mock => mock.Action(It.Is<UrlActionContext>(uac =>
uac.Action == "Login" &&
uac.Controller == "Account" &&
uac.Protocol == requestScheme)),
Times.Once);
}
[Fact]
public async Task EditUserPostSendsSendAccountApprovalEmailWithCorrectDataWhenModelsIsOrganizationAdminIsTrueAndOrganizationAdminClaimWasAddedSuccessfully()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var model = new EditUserViewModel
{
IsOrganizationAdmin = true,
UserId = It.IsAny<string>()
};
var user = new ApplicationUser
{
Id = model.UserId,
Email = "test@testy.com"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Success);
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetDefaultHttpContext();
var expectedUrl = $"Login/Admin?Email={user.Email}";
controller.Url = GetMockUrlHelper(expectedUrl);
await controller.EditUser(model);
mediator.Verify(m => m.SendAsync(It.Is<SendAccountApprovalEmailCommand>(q => q.Email == user.Email && q.CallbackUrl == expectedUrl )), Times.Once);
}
[Fact]
public async Task EditUserPostReturnsRedirectResultWithCorrectUrlWhenModelsIsOrganizationAdminIsTrueAndOrganizationAdminClaimWasNotAddedSuccessfully()
{
var model = new EditUserViewModel
{
IsOrganizationAdmin = true,
UserId = It.IsAny<string>()
};
var user = new ApplicationUser
{
Id = model.UserId,
Email = "test@testy.com"
};
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
.ReturnsAsync(user);
var userManager = CreateApplicationUserMock();
userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Failed(null));
var controller = new SiteController(userManager.Object, null, mediator.Object);
var result = await controller.EditUser(model);
Assert.IsType<RedirectResult>(result);
Assert.Equal("Error", ((RedirectResult)result).Url);
}
[Fact]
public async Task EditUserPostInvokesRemoveClaimAsyncWithCorrectParameters_WhenUserIsAnOrganizationAdmin()
{
var model = new EditUserViewModel { IsOrganizationAdmin = false, UserId = It.IsAny<string>() };
var user = new ApplicationUser { Id = model.UserId, Email = "test@testy.com" };
user.MakeOrgAdmin();
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var userManager = CreateApplicationUserMock();
userManager.Setup(x => x.RemoveClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Success);
var controller = new SiteController(userManager.Object, null, mediator.Object);
await controller.EditUser(model);
userManager.Verify(x => x.RemoveClaimAsync(user, It.Is<Claim>(c => c.Value == nameof(UserType.OrgAdmin))), Times.Once);
}
[Fact]
public async Task EditUserPostReturnsRedirectResultWithCorrectUrlWhenUserIsAnOrganizationAdminAndRemovClaimAsyncDoesNotSucceed()
{
var model = new EditUserViewModel { IsOrganizationAdmin = false, UserId = It.IsAny<string>() };
var user = new ApplicationUser { Id = model.UserId, Email = "test@testy.com" };
user.MakeOrgAdmin();
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var userManager = CreateApplicationUserMock();
userManager.Setup(x => x.RemoveClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Failed(null));
var controller = new SiteController(userManager.Object, null, mediator.Object);
var result = await controller.EditUser(model);
Assert.IsType<RedirectResult>(result);
Assert.Equal("Error", ((RedirectResult)result).Url);
}
[Fact]
public async Task EditUserPostRedirectsToCorrectAction()
{
var mediator = new Mock<IMediator>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)))
.ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, null, mediator.Object);
var result = await controller.EditUser(new EditUserViewModel());
Assert.IsType<RedirectToActionResult>(result);
Assert.Equal("Index", ((RedirectToActionResult)result).ActionName);
}
[Fact]
public void EditUserPostHasHttpPostAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.EditUser(It.IsAny<EditUserViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void EditUserPostHasValidateAntiForgeryTokenAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.EditUser(It.IsAny<EditUserViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task ResetPasswordSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.ResetPassword(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task ResetPasswordAddsCorrectErrorMessageToViewBagWhenUserIsNull()
{
var mediator = new Mock<IMediator>();
var userId = "1234";
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync((ApplicationUser)null);
var controller = new SiteController(null, null, mediator.Object);
await controller.ResetPassword(userId);
Assert.Equal("User not found.", controller.ViewBag.ErrorMessage);
}
[Fact]
public async Task ResetPasswordInvokesGeneratePasswordResetTokenAsyncWithCorrectUserWhenUserIsNotNull()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234",
Email = "test@testy.com"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetDefaultHttpContext();
controller.Url = GetMockUrlHelper("any");
await controller.ResetPassword(user.Id);
userManager.Verify(u => u.GeneratePasswordResetTokenAsync(user));
}
[Fact]
public async Task ResetPasswordInvokesUrlActionWithCorrectParametersWhenUserIsNotNull()
{
const string requestScheme = "requestScheme";
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234",
Email = "test@testy.com"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var code = "passcode";
userManager.Setup(u => u.GeneratePasswordResetTokenAsync(user)).ReturnsAsync(code);
var controller = new SiteController(userManager.Object, null, mediator.Object);
var urlHelper = new Mock<IUrlHelper>();
controller.Url = urlHelper.Object;
controller.SetFakeHttpRequestSchemeTo(requestScheme);
await controller.ResetPassword(user.Id);
urlHelper.Verify(mock => mock.Action(It.Is<UrlActionContext>(uac =>
uac.Action == "ResetPassword" &&
uac.Controller == "Account" &&
uac.Protocol == requestScheme)),
Times.Once);
}
[Fact]
public async Task ResetPasswordSendsSendResetPasswordEmailWithCorrectDataWhenUserIsNotNull()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234",
Email = "test@testy.com"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var code = "passcode";
userManager.Setup(u => u.GeneratePasswordResetTokenAsync(user)).ReturnsAsync(code);
var url = $"Admin/ResetPassword?userId={user.Id}&code={code}";
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetDefaultHttpContext();
controller.Url = GetMockUrlHelper(url);
await controller.ResetPassword(user.Id);
mediator.Verify(x => x.SendAsync(It.Is<AllReady.Areas.Admin.Features.Site.SendResetPasswordEmailCommand>(e => e.Email == user.Email && e.CallbackUrl == url)));
}
[Fact]
public async Task ResetPasswordAddsCorrectSuccessMessagetoViewBagWhenUserIsNotNull()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234",
Email = "test@testy.com",
UserName = "auser"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var code = "passcode";
userManager.Setup(u => u.GeneratePasswordResetTokenAsync(user)).ReturnsAsync(code);
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetDefaultHttpContext();
controller.Url = GetMockUrlHelper("any");
await controller.ResetPassword(user.Id);
Assert.Equal($"Sent password reset email for {user.UserName}.", controller.ViewBag.SuccessMessage);
}
[Fact]
public async Task ResetPasswordReturnsAView()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234",
Email = "test@testy.com",
UserName = "auser"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var code = "passcode";
userManager.Setup(u => u.GeneratePasswordResetTokenAsync(user)).ReturnsAsync(code);
var controller = new SiteController(userManager.Object, null, mediator.Object);
controller.SetDefaultHttpContext();
controller.Url = GetMockUrlHelper("any");
var result = (ViewResult)await controller.ResetPassword(user.Id);
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task ResetPasswordInvokesLogErrorWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
mediator.Setup(x => x.SendAsync(It.IsAny<UserByUserIdQuery>()))
.Throws<Exception>();
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.ResetPassword("1234");
logger.Verify(l => l.Log<object>(LogLevel.Error, 0,
It.IsAny<Microsoft.Extensions.Logging.Internal.FormattedLogValues>(), null,
It.IsAny<Func<object, Exception, string>>()));
}
[Fact]
public async Task ResetPasswordAddsCorrectErrorMessagetoViewBagWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
mediator.Setup(x => x.SendAsync(It.IsAny<UserByUserIdQuery>()))
.Throws<Exception>();
var controller = new SiteController(null, logger.Object, mediator.Object);
var userId = "1234";
await controller.ResetPassword(userId);
Assert.Equal($"Failed to reset password for {userId}. Exception thrown.", controller.ViewBag.ErrorMessage);
}
[Fact]
public async Task ResetPasswordReturnsAViewWhenExcpetionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
mediator.Setup(x => x.SendAsync(It.IsAny<UserByUserIdQuery>()))
.Throws<Exception>();
var controller = new SiteController(null, logger.Object, mediator.Object);
var userId = "1234";
var result = (ViewResult)await controller.ResetPassword(userId);
Assert.IsType<ViewResult>(result);
}
[Fact]
public void ResetPasswordHasHttpGetAttribute()
{
var controller = new SiteController(null, null,null);
var attribute = controller.GetAttributesOn(x => x.ResetPassword(It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task AssignSiteAdminSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.AssignSiteAdmin(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task AssignApiRoleQueriesForCorrectId()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = Guid.NewGuid().ToString();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.AssignApiAccessRole(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task SearchForCorrectUserWhenManagingApiKeys()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = Guid.NewGuid().ToString();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.ManageApiKeys(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task SearchForCorrectUserWhenGeneratingApiKeys()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = Guid.NewGuid().ToString();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.GenerateToken(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task AssignSiteAdminInvokesAddClaimAsyncWithCorrrectParameters()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser { Id = "1234" };
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var controller = new SiteController(userManager.Object, null, mediator.Object);
await controller.AssignSiteAdmin(user.Id);
userManager.Verify(x => x.AddClaimAsync(user, It.Is<Claim>(c =>
c.Value == nameof(UserType.SiteAdmin) &&
c.Type == AllReady.Security.ClaimTypes.UserType)), Times.Once);
}
[Fact]
public async Task AssignSiteAdminRedirectsToCorrectAction()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id))).ReturnsAsync(user);
userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>())).ReturnsAsync(IdentityResult.Success);
var controller = new SiteController(userManager.Object, null, mediator.Object);
var result = (RedirectToActionResult) await controller.AssignSiteAdmin(user.Id);
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task AssignSiteAdminInvokesLogErrorWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.Throws<Exception>();
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.AssignSiteAdmin(user.Id);
logger.Verify(l => l.Log<object>(LogLevel.Error, 0,
It.IsAny<Microsoft.Extensions.Logging.Internal.FormattedLogValues>(), null,
It.IsAny<Func<object, Exception, string>>()));
}
[Fact]
public async Task AssignSiteAdminAddsCorrectErrorMessageToViewBagWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.Throws<Exception>();
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
await controller.AssignSiteAdmin(user.Id);
Assert.Equal($"Failed to assign site admin for {user.Id}. Exception thrown.", controller.ViewBag.ErrorMessage);
}
[Fact]
public async Task AssignSiteAdminReturnsAViewWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userManager = CreateApplicationUserMock();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.Throws<Exception>();
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
var result = await controller.AssignSiteAdmin(user.Id);
Assert.IsType<ViewResult>(result);
}
[Fact]
public void AssignSiteAdminHasHttpGetAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.AssignSiteAdmin(It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task AssignOrganizationAdminGetSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var userId = "1234";
var controller = new SiteController(null, null, mediator.Object);
await controller.AssignOrganizationAdmin(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task AssignOrganizationAdminGetRedirectsToCorrectActionWhenUserIsAnOrganizationAdmin()
{
var user = new ApplicationUser { Id = "1234" };
user.MakeOrgAdmin();
var mediator = new Mock<IMediator>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
var result = (RedirectToActionResult) await controller.AssignOrganizationAdmin(user.Id);
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task AssignOrganizationAdminGetRedirectsToCorrectActionWhenUserIsASiteAdmin()
{
var mediator = new Mock<IMediator>();
var user = new ApplicationUser
{
Id = "1234"
};
user.Claims.Add(new IdentityUserClaim<string>
{
ClaimType = AllReady.Security.ClaimTypes.UserType,
ClaimValue = nameof(UserType.SiteAdmin)
});
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
var result = (RedirectToActionResult) await controller.AssignOrganizationAdmin(user.Id);
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task AssignOrganizationAdminGetSendsAllOrganizationsQuery()
{
var mediator = new Mock<IMediator>();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
await controller.AssignOrganizationAdmin(user.Id);
mediator.Verify(m => m.SendAsync(It.IsAny<AllOrganizationsQuery>()), Times.Once);
}
[Fact]
public async Task AssignOrganizationAdminGetAddsCorrectSelectListItemToOrganizationsOnViewBag()
{
var mediator = new Mock<IMediator>();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var orgs = new List<Organization>
{
new Organization { Id = 2, Name = "Borg" },
new Organization { Id = 1, Name = "Aorg" }
};
mediator.Setup(x => x.SendAsync(It.IsAny<AllOrganizationsQuery>())).ReturnsAsync(orgs);
var controller = new SiteController(null, null, mediator.Object);
await controller.AssignOrganizationAdmin(user.Id);
var viewBagOrgs = ((IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>)controller.ViewBag.Organizations).ToList();
Assert.Equal(3, viewBagOrgs.Count);
Assert.Equal("0", viewBagOrgs[0].Value); // Select One item added in controller
Assert.Equal("1", viewBagOrgs[1].Value); // sorted items
Assert.Equal("2", viewBagOrgs[2].Value);
}
[Fact]
public async Task AssignOrganizationAdminGetReturnsCorrectViewModel()
{
var mediator = new Mock<IMediator>();
var user = new ApplicationUser
{
Id = "1234"
};
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == user.Id)))
.ReturnsAsync(user);
var orgs = new List<Organization>
{
new Organization { Id = 2, Name = "Borg" },
new Organization { Id = 1, Name = "Aorg" }
};
mediator.Setup(x => x.SendAsync(It.IsAny<AllOrganizationsQuery>())).ReturnsAsync(orgs);
var controller = new SiteController(null, null, mediator.Object);
var result = (ViewResult) await controller.AssignOrganizationAdmin(user.Id);
Assert.IsType<AssignOrganizationAdminViewModel>(result.Model);
}
[Fact]
public void AssignOrganizationAdminGetHasHttpGetAttribute()
{
var controller = new SiteController(null, null,null);
var attribute = controller.GetAttributesOn(x => x.AssignOrganizationAdmin(It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task AssignOrganizationAdminPostSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234"
};
var controller = new SiteController(null, null, mediator.Object);
await controller.AssignOrganizationAdmin(model);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)), Times.Once);
}
[Fact]
public async Task AssignOrganizationAdminPostRedirectsToCorrectActionIsUserIsNull()
{
var mediator = new Mock<IMediator>();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234"
};
ApplicationUser nullUser = null;
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(nullUser);
var controller = new SiteController(null, null, mediator.Object);
var result = (RedirectToActionResult)await controller.AssignOrganizationAdmin(model);
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task AssignOrganizationAdminPostAddsCorrectKeyAndErrorMessageToModelStateWhenOrganizationIdIsZero()
{
var mediator = new Mock<IMediator>();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234"
};
var user = new ApplicationUser { UserName = "name" };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
await controller.AssignOrganizationAdmin(model);
Assert.False(controller.ModelState.IsValid);
Assert.True(controller.ModelState.ContainsKey("OrganizationId"));
Assert.True(controller.ModelState.GetErrorMessagesByKey("OrganizationId").FirstOrDefault(x => x.ErrorMessage.Equals("You must pick a valid organization.")) != null);
}
[Fact]
public async Task AssignOrganizationAdminPostSendsAllOrganizationsQueryWhenModelStateIsValid()
{
var mediator = new Mock<IMediator>();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234",
OrganizationId = 5678
};
var user = new ApplicationUser { UserName = "name" };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
await controller.AssignOrganizationAdmin(model);
mediator.Verify(x => x.SendAsync(It.IsAny<AllOrganizationsQuery>()), Times.Once);
}
[Fact]
public async Task AssignOrganizationAdminPostInvokesAddClaimAsyncTwiceAddingTheCorrectClaimsWhenOrganizationIdOnModelMatchesAnyExistingOrganization()
{
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234",
OrganizationId = 5678
};
var orgs = new List<Organization> { new Organization { Id = 5678, Name = "Borg" } };
var user = new ApplicationUser { UserName = "name" };
var mediator = new Mock<IMediator>();
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
mediator.Setup(x => x.SendAsync(It.IsAny<AllOrganizationsQuery>())).ReturnsAsync(orgs);
var userManager = CreateApplicationUserMock();
var controller = new SiteController(userManager.Object, null, mediator.Object);
await controller.AssignOrganizationAdmin(model);
userManager.Verify(x => x.AddClaimAsync(user, It.Is<Claim>(c =>
c.Value == nameof(UserType.OrgAdmin) &&
c.Type == AllReady.Security.ClaimTypes.UserType)), Times.Once);
userManager.Verify(x => x.AddClaimAsync(user, It.Is<Claim>(c =>
c.Value == model.OrganizationId.ToString() &&
c.Type == AllReady.Security.ClaimTypes.Organization)), Times.Once);
}
[Fact]
public async Task AssignOrganizationAdminPostRedirectsToCorrectActionWhenOrganizationIdOnModelMatchesAnyExistingOrganization()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234",
OrganizationId = 5678
};
var user = new ApplicationUser { UserName = "name" };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var orgs = new List<Organization> { new Organization { Id = 5678, Name = "Borg" } };
mediator.Setup(x => x.SendAsync(It.IsAny<AllOrganizationsQuery>())).ReturnsAsync(orgs);
var controller = new SiteController(userManager.Object, null, mediator.Object);
var result = (RedirectToActionResult) await controller.AssignOrganizationAdmin(model);
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task AssignOrganizationAdminPostAddsCorrectKeyAndErrorMessageToModelStateWhenOrganzationNotFound()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234",
OrganizationId = 5678
};
var user = new ApplicationUser { UserName = "name" };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var orgs = new List<Organization> { new Organization { Id = 9123, Name = "Borg" } };
mediator.Setup(x => x.SendAsync(It.IsAny<AllOrganizationsQuery>())).ReturnsAsync(orgs);
var controller = new SiteController(userManager.Object, null, mediator.Object);
await controller.AssignOrganizationAdmin(model);
Assert.False(controller.ModelState.IsValid);
Assert.True(controller.ModelState.ContainsKey("OrganizationId"));
Assert.True(controller.ModelState.GetErrorMessagesByKey("OrganizationId").FirstOrDefault(x => x.ErrorMessage.Equals("Invalid Organization. Please contact support.")) != null);
}
[Fact]
public async Task AssignOrganizationAdminPostReturnsAView()
{
var mediator = new Mock<IMediator>();
var model = new AssignOrganizationAdminViewModel
{
UserId = "1234",
OrganizationId = 0
};
var user = new ApplicationUser { UserName = "name" };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId))).ReturnsAsync(user);
var controller = new SiteController(null, null, mediator.Object);
var result = await controller.AssignOrganizationAdmin(model);
Assert.IsType<ViewResult>(result);
}
[Fact]
public void AssignOrganizationAdminPostHasHttpPostAttribute()
{
var mediator = new Mock<IMediator>();
var controller = new SiteController(null, null, mediator.Object);
var model = new AssignOrganizationAdminViewModel { UserId = It.IsAny<string>(), OrganizationId = It.IsAny<int>() };
var attribute = controller.GetAttributesOn(x => x.AssignOrganizationAdmin(model)).OfType<HttpPostAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void AssignOrganizationAdminPostHasValidateAntiForgeryTokenAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.AssignOrganizationAdmin(It.IsAny<AssignOrganizationAdminViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task RevokeSiteAdminSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.RevokeSiteAdmin(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task RevokeSiteAdminInvokesRemoveClaimAsyncWithCorrectParameters()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var userId = "1234";
var user = new ApplicationUser { UserName = "name", Id = userId };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(user);
var controller = new SiteController(userManager.Object, null, mediator.Object);
await controller.RevokeSiteAdmin(userId);
userManager.Verify(u => u.RemoveClaimAsync(user, It.Is<Claim>(c =>
c.Type == AllReady.Security.ClaimTypes.UserType
&& c.Value == nameof(UserType.SiteAdmin))), Times.Once);
}
[Fact]
public async Task RevokeSiteAdminRedirectsToCorrectAction()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
mediator.Setup(m => m.SendAsync(It.IsAny<UserByUserIdQuery>())).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(userManager.Object, null, mediator.Object);
var result = (RedirectToActionResult) await controller.RevokeSiteAdmin(It.IsAny<string>());
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task RevokeSiteAdminInvokesLogErrorWithCorrectParametersWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
var thrown = new Exception("Test");
mediator.Setup(x => x.SendAsync(It.IsAny<UserByUserIdQuery>()))
.Throws(thrown);
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.RevokeSiteAdmin (userId);
string expectedMessage = $"Failed to revoke site admin for {userId}";
logger.Verify(l => l.Log(LogLevel.Error, 0,
It.Is<Microsoft.Extensions.Logging.Internal.FormattedLogValues>(x => x.ToString().Equals(expectedMessage)),
null, It.IsAny<Func<object, Exception, string>>()), Times.Once);
}
[Fact]
public async Task RevokeSiteAdminAddsCorrectErrorMessageToViewBagWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
var thrown = new Exception("Test");
mediator.Setup(x => x.SendAsync(It.IsAny<UserByUserIdQuery>()))
.Throws(thrown);
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.RevokeSiteAdmin(userId);
string expectedMessage = $"Failed to revoke site admin for {userId}. Exception thrown.";
Assert.Equal(expectedMessage, controller.ViewBag.ErrorMessage);
}
[Fact]
public async Task RevokeSiteAdminReturnsAViewWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
var thrown = new Exception("Test");
mediator.Setup(x => x.SendAsync(It.IsAny<UserByUserIdQuery>()))
.Throws(thrown);
var controller = new SiteController(null, logger.Object, mediator.Object);
var result = await controller.RevokeSiteAdmin(userId);
Assert.IsType<ViewResult>(result);
}
[Fact]
public void RevokeSiteAdminHasHttpGetAttribute()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributesOn(x => x.RevokeSiteAdmin(It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public async Task RevokeOrganizationAdminSendsUserByUserIdQueryWithCorrectUserId()
{
var mediator = new Mock<IMediator>();
var logger = new Mock<ILogger<SiteController>>();
var userId = It.IsAny<string>();
mediator.Setup(x => x.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(new ApplicationUser());
var controller = new SiteController(null, logger.Object, mediator.Object);
await controller.RevokeOrganizationAdmin(userId);
mediator.Verify(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId)), Times.Once);
}
[Fact]
public async Task RevokeOrganizationAdminInvokesGetclaimsAsyncWithCorrectUser()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
var user = new ApplicationUser { UserName = "name", Id = userId };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(user);
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
await controller.RevokeOrganizationAdmin(userId);
userManager.Verify(u => u.GetClaimsAsync(user), Times.Once);
}
[Fact]
public async Task RevokeOrganizationAdminInokesRemoveClaimAsyncTwiceWithCorrectParameters()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
var user = new ApplicationUser { UserName = "name", Id = userId };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(user);
var orgId = "4567";
IList<Claim> claims = new List<Claim>();
claims.Add(new Claim(AllReady.Security.ClaimTypes.UserType, nameof(UserType.SiteAdmin)));
claims.Add(new Claim(AllReady.Security.ClaimTypes.Organization, orgId));
userManager.Setup(u => u.GetClaimsAsync(user)).ReturnsAsync(claims);
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
await controller.RevokeOrganizationAdmin(userId);
userManager.Verify(u => u.RemoveClaimAsync(user, It.Is<Claim>(c =>
c.Type == AllReady.Security.ClaimTypes.UserType
&& c.Value == nameof(UserType.SiteAdmin))), Times.Once);
userManager.Verify(u => u.RemoveClaimAsync(user, It.Is<Claim>(c =>
c.Type == AllReady.Security.ClaimTypes.Organization
&& c.Value == orgId)), Times.Once);
}
[Fact]
public async Task RevokeOrganizationAdminRedirectsToCorrectAction()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
var user = new ApplicationUser { UserName = "name", Id = userId };
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).ReturnsAsync(user);
var orgId = "4567";
IList<Claim> claims = new List<Claim>();
claims.Add(new Claim(AllReady.Security.ClaimTypes.UserType, nameof(UserType.SiteAdmin)));
claims.Add(new Claim(AllReady.Security.ClaimTypes.Organization, orgId));
userManager.Setup(u => u.GetClaimsAsync(user)).ReturnsAsync(claims);
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
var result = (RedirectToActionResult) await controller.RevokeOrganizationAdmin(userId);
Assert.Equal("Index", result.ActionName);
}
[Fact]
public async Task RevokeOrganizationAdminInvokesLogErrorWithCorrectParametersWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).Throws<Exception>();
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
await controller.RevokeOrganizationAdmin(userId);
string expectedMessage = $"Failed to revoke organization admin for {userId}";
logger.Verify(l => l.Log(LogLevel.Error, 0,
It.Is<Microsoft.Extensions.Logging.Internal.FormattedLogValues>(x => x.ToString().Equals(expectedMessage)),
null, It.IsAny<Func<object, Exception, string>>()), Times.Once);
}
[Fact]
public async Task RevokeOrganizationAdminAddsCorrectErrorMessageToViewBagWhenExceptionIsThrown()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).Throws<Exception>();
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
await controller.RevokeOrganizationAdmin(userId);
string expectedMessage = $"Failed to revoke organization admin for {userId}. Exception thrown.";
Assert.Equal(controller.ViewBag.ErrorMessage, expectedMessage);
}
[Fact]
public async Task RevokeOrganizationAdminReturnsAViewWhenErrorIsThrown()
{
var mediator = new Mock<IMediator>();
var userManager = CreateApplicationUserMock();
var logger = new Mock<ILogger<SiteController>>();
var userId = "1234";
mediator.Setup(m => m.SendAsync(It.Is<UserByUserIdQuery>(q => q.UserId == userId))).Throws<Exception>();
var controller = new SiteController(userManager.Object, logger.Object, mediator.Object);
var result = (ViewResult)await controller.RevokeOrganizationAdmin(userId);
Assert.IsType<ViewResult>(result);
}
[Fact]
public void RevokeOrganizationAdminHasHttpGetAttribute()
{
var controller = new SiteController(null, null,null);
var attribute = controller.GetAttributesOn(x => x.RevokeOrganizationAdmin(It.IsAny<string>())).OfType<HttpGetAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
}
[Fact]
public void ControllerHasAreaAtttributeWithTheCorrectAreaName()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributes().OfType<AreaAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
Assert.Equal(AreaNames.Admin, attribute.RouteValue);
}
[Fact]
public void ControllerHasAuthorizeAtttributeWithTheCorrectPolicy()
{
var controller = new SiteController(null, null, null);
var attribute = controller.GetAttributes().OfType<AuthorizeAttribute>().SingleOrDefault();
Assert.NotNull(attribute);
Assert.Equal(nameof(UserType.SiteAdmin), attribute.Policy);
}
private static Mock<UserManager<ApplicationUser>> CreateApplicationUserMock()
{
return new Mock<UserManager<ApplicationUser>>(Mock.Of<IUserStore<ApplicationUser>>(), null, null, null, null, null, null, null,null);
}
private static IUrlHelper GetMockUrlHelper(string returnValue)
{
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(o => o.Action(It.IsAny<UrlActionContext>())).Returns(returnValue);
return urlHelper.Object;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_EventInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class EventInfo : MemberInfo, _EventInfo
{
#region Constructor
protected EventInfo() { }
#endregion
public static bool operator ==(EventInfo left, EventInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeEventInfo || right is RuntimeEventInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(EventInfo left, EventInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Event; } }
#endregion
#region Public Abstract\Virtual Members
public virtual MethodInfo[] GetOtherMethods(bool nonPublic)
{
throw new NotImplementedException();
}
public abstract MethodInfo GetAddMethod(bool nonPublic);
public abstract MethodInfo GetRemoveMethod(bool nonPublic);
public abstract MethodInfo GetRaiseMethod(bool nonPublic);
public abstract EventAttributes Attributes { get; }
#endregion
#region Public Members
public virtual MethodInfo AddMethod
{
get
{
return GetAddMethod(true);
}
}
public virtual MethodInfo RemoveMethod
{
get
{
return GetRemoveMethod(true);
}
}
public virtual MethodInfo RaiseMethod
{
get
{
return GetRaiseMethod(true);
}
}
public MethodInfo[] GetOtherMethods() { return GetOtherMethods(false); }
public MethodInfo GetAddMethod() { return GetAddMethod(false); }
public MethodInfo GetRemoveMethod() { return GetRemoveMethod(false); }
public MethodInfo GetRaiseMethod() { return GetRaiseMethod(false); }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual void AddEventHandler(Object target, Delegate handler)
{
MethodInfo addMethod = GetAddMethod();
if (addMethod == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod"));
#if FEATURE_COMINTEROP
if (addMethod.ReturnType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
// Must be a normal non-WinRT event
Contract.Assert(addMethod.ReturnType == typeof(void));
#endif // FEATURE_COMINTEROP
addMethod.Invoke(target, new object[] { handler });
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual void RemoveEventHandler(Object target, Delegate handler)
{
MethodInfo removeMethod = GetRemoveMethod();
if (removeMethod == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicRemoveMethod"));
#if FEATURE_COMINTEROP
ParameterInfo[] parameters = removeMethod.GetParametersNoCopy();
Contract.Assert(parameters != null && parameters.Length == 1);
if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
// Must be a normal non-WinRT event
Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
#endif // FEATURE_COMINTEROP
removeMethod.Invoke(target, new object[] { handler });
}
public virtual Type EventHandlerType
{
get
{
MethodInfo m = GetAddMethod(true);
ParameterInfo[] p = m.GetParametersNoCopy();
Type del = typeof(Delegate);
for (int i = 0; i < p.Length; i++)
{
Type c = p[i].ParameterType;
if (c.IsSubclassOf(del))
return c;
}
return null;
}
}
public bool IsSpecialName
{
get
{
return(Attributes & EventAttributes.SpecialName) != 0;
}
}
public virtual bool IsMulticast
{
get
{
Type cl = EventHandlerType;
Type mc = typeof(MulticastDelegate);
return mc.IsAssignableFrom(cl);
}
}
#endregion
#if !FEATURE_CORECLR
Type _EventInfo.GetType()
{
return base.GetType();
}
void _EventInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and
// include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
[Serializable]
internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable
{
#region Private Data Members
private int m_token;
private EventAttributes m_flags;
private string m_name;
[System.Security.SecurityCritical]
private void* m_utf8name;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_addMethod;
private RuntimeMethodInfo m_removeMethod;
private RuntimeMethodInfo m_raiseMethod;
private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
#endregion
#region Constructor
internal RuntimeEventInfo()
{
// Used for dummy head node during population
}
[System.Security.SecurityCritical] // auto-generated
internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
Contract.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkEvent;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType();
scope.GetEventProps(tkEvent, out m_utf8name, out m_flags);
RuntimeMethodInfo dummy;
Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType,
out m_addMethod, out m_removeMethod, out m_raiseMethod,
out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags);
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeEventInfo m = o as RuntimeEventInfo;
if ((object)m == null)
return false;
return m.m_token == m_token &&
RuntimeTypeHandle.GetModule(m_declaringType).Equals(
RuntimeTypeHandle.GetModule(m.m_declaringType));
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#region Object Overrides
public override String ToString()
{
if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod"));
return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Event; } }
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
return m_name;
}
}
public override Type DeclaringType { get { return m_declaringType; } }
public override Type ReflectedType
{
get
{
return ReflectedTypeInternal;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override int MetadataToken { get { return m_token; } }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
null,
MemberTypes.Event);
}
#endregion
#region EventInfo Overrides
public override MethodInfo[] GetOtherMethods(bool nonPublic)
{
List<MethodInfo> ret = new List<MethodInfo>();
if ((object)m_otherMethod == null)
return new MethodInfo[0];
for(int i = 0; i < m_otherMethod.Length; i ++)
{
if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic))
ret.Add(m_otherMethod[i]);
}
return ret.ToArray();
}
public override MethodInfo GetAddMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_addMethod, nonPublic))
return null;
return m_addMethod;
}
public override MethodInfo GetRemoveMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_removeMethod, nonPublic))
return null;
return m_removeMethod;
}
public override MethodInfo GetRaiseMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic))
return null;
return m_raiseMethod;
}
public override EventAttributes Attributes
{
get
{
return m_flags;
}
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System.Collections.Generic
{
// Summary:
// Represents a doubly linked list.
//
// Type parameters:
// T:
// Specifies the element type of the linked list.
// [Serializable]
public class LinkedList<T> : ICollection<T> //, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
{
// Summary:
// Initializes a new instance of the System.Collections.Generic.LinkedList<T>
// class that is empty.
public LinkedList()
{
Contract.Ensures(Count == 0);
}
//
// Summary:
// Initializes a new instance of the System.Collections.Generic.LinkedList<T>
// class that contains elements copied from the specified System.Collections.IEnumerable
// and has sufficient capacity to accommodate the number of elements copied.
//
// Parameters:
// collection:
// The System.Collections.IEnumerable whose elements are copied to the new System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.ArgumentNullException:
// collection is null.
public LinkedList(IEnumerable<T> collection)
{
Contract.Requires(collection != null);
}
//
// Summary:
// Initializes a new instance of the System.Collections.Generic.LinkedList<T>
// class that is serializable with the specified System.Runtime.Serialization.SerializationInfo
// and System.Runtime.Serialization.StreamingContext.
//
// Parameters:
// info:
// A System.Runtime.Serialization.SerializationInfo object containing the information
// required to serialize the System.Collections.Generic.LinkedList<T>.
//
// context:
// A System.Runtime.Serialization.StreamingContext object containing the source
// and destination of the serialized stream associated with the System.Collections.Generic.LinkedList<T>.
//protected LinkedList(SerializationInfo info, StreamingContext context);
// Summary:
// Gets the number of nodes actually contained in the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The number of nodes actually contained in the System.Collections.Generic.LinkedList<T>.
extern public int Count
{
get;
}
//
// Summary:
// Gets the first node of the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The first System.Collections.Generic.LinkedListNode<T> of the System.Collections.Generic.LinkedList<T>.
public LinkedListNode<T> First
{
get
{
Contract.Ensures(Count != 0 || Contract.Result<LinkedListNode<T>>() == null);
Contract.Ensures(Count == 0 || Contract.Result<LinkedListNode<T>>() != null);
return default(LinkedListNode<T>);
}
}
//
// Summary:
// Gets the last node of the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The last System.Collections.Generic.LinkedListNode<T> of the System.Collections.Generic.LinkedList<T>.
public LinkedListNode<T> Last
{
get
{
Contract.Ensures(Count != 0 || Contract.Result<LinkedListNode<T>>() == null);
Contract.Ensures(Count == 0 || Contract.Result<LinkedListNode<T>>() != null);
return default(LinkedListNode<T>);
}
}
// Summary:
// Adds the specified new node after the specified existing node in the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The System.Collections.Generic.LinkedListNode<T> after which to insert newNode.
//
// newNode:
// The new System.Collections.Generic.LinkedListNode<T> to add to the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.ArgumentNullException:
// node is null. -or- newNode is null.
//
// System.InvalidOperationException:
// node is not in the current System.Collections.Generic.LinkedList<T>. -or-
// newNode belongs to another System.Collections.Generic.LinkedList<T>.
public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode)
{
Contract.Requires(node != null);
Contract.Requires(newNode != null);
Contract.Ensures(Count == Contract.OldValue(Count) +1);
}
//
// Summary:
// Adds a new node containing the specified value after the specified existing
// node in the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The System.Collections.Generic.LinkedListNode<T> after which to insert a
// new System.Collections.Generic.LinkedListNode<T> containing value.
//
// value:
// The value to add to the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The new System.Collections.Generic.LinkedListNode<T> containing value.
//
// Exceptions:
// System.ArgumentNullException:
// node is null.
//
// System.InvalidOperationException:
// node is not in the current System.Collections.Generic.LinkedList<T>.
public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value)
{
Contract.Requires(node != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
return default(LinkedListNode<T>);
}
//
// Summary:
// Adds the specified new node before the specified existing node in the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The System.Collections.Generic.LinkedListNode<T> before which to insert newNode.
//
// newNode:
// The new System.Collections.Generic.LinkedListNode<T> to add to the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.ArgumentNullException:
// node is null. -or- newNode is null.
//
// System.InvalidOperationException:
// node is not in the current System.Collections.Generic.LinkedList<T>. -or-
// newNode belongs to another System.Collections.Generic.LinkedList<T>.
public void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode)
{
Contract.Requires(node != null);
Contract.Requires(newNode != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
}
//
// Summary:
// Adds a new node containing the specified value before the specified existing
// node in the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The System.Collections.Generic.LinkedListNode<T> before which to insert a
// new System.Collections.Generic.LinkedListNode<T> containing value.
//
// value:
// The value to add to the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The new System.Collections.Generic.LinkedListNode<T> containing value.
//
// Exceptions:
// System.ArgumentNullException:
// node is null.
//
// System.InvalidOperationException:
// node is not in the current System.Collections.Generic.LinkedList<T>.
public LinkedListNode<T> AddBefore(LinkedListNode<T> node, T value)
{
Contract.Requires(node != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
return default(LinkedListNode<T>);
}
//
// Summary:
// Adds the specified new node at the start of the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The new System.Collections.Generic.LinkedListNode<T> to add at the start
// of the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.ArgumentNullException:
// node is null.
//
// System.InvalidOperationException:
// node belongs to another System.Collections.Generic.LinkedList<T>.
public void AddFirst(LinkedListNode<T> node)
{
Contract.Requires(node != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
}
//
// Summary:
// Adds a new node containing the specified value at the start of the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// value:
// The value to add at the start of the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The new System.Collections.Generic.LinkedListNode<T> containing value.
public LinkedListNode<T> AddFirst(T value)
{
Contract.Ensures(Contract.Result<LinkedListNode<T>>() != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
return default(LinkedListNode<T>);
}
//
// Summary:
// Adds the specified new node at the end of the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The new System.Collections.Generic.LinkedListNode<T> to add at the end of
// the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.ArgumentNullException:
// node is null.
//
// System.InvalidOperationException:
// node belongs to another System.Collections.Generic.LinkedList<T>.
public void AddLast(LinkedListNode<T> node)
{
Contract.Requires(node != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
}
//
// Summary:
// Adds a new node containing the specified value at the end of the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// value:
// The value to add at the end of the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The new System.Collections.Generic.LinkedListNode<T> containing value.
public LinkedListNode<T> AddLast(T value)
{
Contract.Ensures(Contract.Result<LinkedListNode<T>>() != null);
Contract.Ensures(Count == Contract.OldValue(Count) + 1);
return default(LinkedListNode<T>);
}
//
// Summary:
// Determines whether a value is in the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// value:
// The value to locate in the System.Collections.Generic.LinkedList<T>. The
// value can be null for reference types.
//
// Returns:
// true if value is found in the System.Collections.Generic.LinkedList<T>; otherwise,
// false.
//public bool Contains(T value);
//
// Summary:
// Copies the entire System.Collections.Generic.LinkedList<T> to a compatible
// one-dimensional System.Array, starting at the specified index of the target
// array.
//
// Parameters:
// array:
// The one-dimensional System.Array that is the destination of the elements
// copied from System.Collections.Generic.LinkedList<T>. The System.Array must
// have zero-based indexing.
//
// index:
// The zero-based index in array at which copying begins.
//
// Exceptions:
// System.ArgumentNullException:
// array is null.
//
// System.ArgumentOutOfRangeException:
// index is equal to or greater than the length of array. -or- index is less
// than zero.
//
// System.ArgumentException:
// The number of elements in the source System.Collections.Generic.LinkedList<T>
// is greater than the available space from index to the end of the destination
// array.
extern public void CopyTo(T[] array, int index);
//
// Summary:
// Finds the first node that contains the specified value.
//
// Parameters:
// value:
// The value to locate in the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The first System.Collections.Generic.LinkedListNode<T> that contains the
// specified value, if found; otherwise, null.
//public LinkedListNode<T> Find(T value);
//
// Summary:
// Finds the last node that contains the specified value.
//
// Parameters:
// value:
// The value to locate in the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// The last System.Collections.Generic.LinkedListNode<T> that contains the specified
// value, if found; otherwise, null.
//public LinkedListNode<T> FindLast(T value);
//
// Summary:
// Returns an enumerator that iterates through the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// An System.Collections.Generic.LinkedList<T>.Enumerator for the System.Collections.Generic.LinkedList<T>.
//public LinkedList<T>.Enumerator GetEnumerator();
//
// Summary:
// Implements the System.Runtime.Serialization.ISerializable interface and returns
// the data needed to serialize the System.Collections.Generic.LinkedList<T>
// instance.
//
// Parameters:
// info:
// A System.Runtime.Serialization.SerializationInfo object that contains the
// information required to serialize the System.Collections.Generic.LinkedList<T>
// instance.
//
// context:
// A System.Runtime.Serialization.StreamingContext object that contains the
// source and destination of the serialized stream associated with the System.Collections.Generic.LinkedList<T>
// instance.
//
// Exceptions:
// System.ArgumentNullException:
// info is null.
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context);
//
// Summary:
// Implements the System.Runtime.Serialization.ISerializable interface and raises
// the deserialization event when the deserialization is complete.
//
// Parameters:
// sender:
// The source of the deserialization event.
//
// Exceptions:
// System.Runtime.Serialization.SerializationException:
// The System.Runtime.Serialization.SerializationInfo object associated with
// the current System.Collections.Generic.LinkedList<T> instance is invalid.
//public virtual void OnDeserialization(object sender);
//
// Summary:
// Removes the specified node from the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// node:
// The System.Collections.Generic.LinkedListNode<T> to remove from the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.ArgumentNullException:
// node is null.
//
// System.InvalidOperationException:
// node is not in the current System.Collections.Generic.LinkedList<T>.
public void Remove(LinkedListNode<T> node)
{
Contract.Requires(node != null);
Contract.Ensures(Count == Contract.OldValue(Count) -1);
}
//
// Summary:
// Removes the first occurrence of the specified value from the System.Collections.Generic.LinkedList<T>.
//
// Parameters:
// value:
// The value to remove from the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// true if the element containing value is successfully removed; otherwise,
// false. This method also returns false if value was not found in the original
// System.Collections.Generic.LinkedList<T>.
virtual public bool Remove(T value)
{
Contract.Ensures(!Contract.Result<bool>() || Count == Contract.OldValue(Count) - 1);
return default(bool);
}
//
// Summary:
// Removes the node at the start of the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.InvalidOperationException:
// The System.Collections.Generic.LinkedList<T> is empty.
public void RemoveFirst()
{
Contract.Requires(Count > 0);
Contract.Ensures(Count == Contract.OldValue(Count) - 1);
}
//
// Summary:
// Removes the node at the end of the System.Collections.Generic.LinkedList<T>.
//
// Exceptions:
// System.InvalidOperationException:
// The System.Collections.Generic.LinkedList<T> is empty.
public void RemoveLast()
{
Contract.Requires(Count > 0);
Contract.Ensures(Count == Contract.OldValue(Count) -1);
}
// Summary:
// Enumerates the elements of a System.Collections.Generic.LinkedList<T>.
//[Serializable]
public struct Enumerator //: IEnumerator<T>, IDisposable, IEnumerator, ISerializable, IDeserializationCallback
{
// Summary:
// Gets the element at the current position of the enumerator.
//
// Returns:
// The element in the System.Collections.Generic.LinkedList<T> at the current
// position of the enumerator.
//public T Current { get; }
// Summary:
// Releases all resources used by the System.Collections.Generic.LinkedList<T>.Enumerator.
//public void Dispose();
//
// Summary:
// Advances the enumerator to the next element of the System.Collections.Generic.LinkedList<T>.
//
// Returns:
// true if the enumerator was successfully advanced to the next element; false
// if the enumerator has passed the end of the collection.
//
// Exceptions:
// System.InvalidOperationException:
// The collection was modified after the enumerator was created.
//public bool MoveNext();
}
#region ICollection<T> Members
extern void ICollection<T>.Add(T item);
extern public void Clear();
extern public bool Contains(T item);
extern bool ICollection<T>.IsReadOnly { get; }
#endregion
#region IEnumerable<T> Members
extern IEnumerator<T> IEnumerable<T>.GetEnumerator();
#endregion
#region IEnumerable Members
extern IEnumerator IEnumerable.GetEnumerator();
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Reflection;
using System.Collections;
using System.Text;
using NS_GMath;
using NS_ValCommon;
using NS_IDraw;
using ArrayList = System.Collections.ArrayList;
namespace NS_Glyph
{
public class Glyph : I_Drawable
{
/*
* MEMBERS: content
*/
private int index;
private GConsts.TypeGlyph typeGlyph;
BoxD bbox;
Outline outl;
Composite comp;
/*
* MEMBERS: management
*/
private FManager fm;
private StatusGV[] statusGV;
/*
* PROPERTIES
*/
internal BoxD BBox
{
get { return this.bbox; }
set
{
if (this.bbox!=null)
{
this.bbox.Clear();
this.bbox=null;
}
this.bbox=value;
}
}
internal Outline Outl
{
get { return this.outl; }
set
{
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
this.outl=value;
}
}
internal Composite Comp
{
get { return this.comp; }
set
{
if (this.comp!=null)
{
this.comp.ClearDestroy();
this.comp=null;
}
this.comp=value;
}
}
public bool IsDiffFromSource
{
get
{
switch (this.typeGlyph)
{
case GConsts.TypeGlyph.Uninitialized:
return true;
case GConsts.TypeGlyph.Undef:
return false;
case GConsts.TypeGlyph.Empty:
return ((this.outl!=null)||(this.comp!=null));
case GConsts.TypeGlyph.Simple:
return (!this.statusGV[(int)DefsGV.TypeGV.ValidateSimpSource].IsValid);
case GConsts.TypeGlyph.Composite:
return (!this.statusGV[(int)DefsGV.TypeGV.ValidateCompSource].IsValid);
}
throw new ExceptionGlyph("Glyph","IsDiffFromSource",null);
//return true;
}
}
/*
internal Flags IsFailedGV
{
get { return this.f_isFailedGV; }
}
internal Flags IsValidGV
{
get { return this.f_isValidGV; }
}
*/
public GConsts.TypeGlyph TypeGlyph
{
get { return this.typeGlyph; }
}
public int IndexGlyph
{
get {return this.index;}
}
internal ArrayList CompDep
{
get { return this.fm.GGetCompDep(this.index); }
}
public string StringInfoGeneral
{
get
{
StringBuilder sb=new StringBuilder();
sb.Append("Glyph index: "+this.index);
sb.Append(" type:"+this.typeGlyph);
if ((this.typeGlyph==GConsts.TypeGlyph.Composite)&&(this.comp!=null))
{
sb.Append(" components: ");
foreach (Component component in this.comp)
{
sb.Append(component.IndexGlyphComponent);
sb.Append(" ");
}
}
if (this.typeGlyph==GConsts.TypeGlyph.Simple)
{
if (this.bbox==null)
sb.Append("\r\nFailed to load Bounding Box");
if (this.outl==null)
sb.Append("\r\nFailed to load Outline");
}
if (this.typeGlyph==GConsts.TypeGlyph.Composite)
{
if (this.bbox==null)
sb.Append("\r\nFailed to load Bounding Box");
if (this.comp==null)
sb.Append("\r\nFailed to load Composite Data");
}
if (!this.IsDiffFromSource)
{
sb.Append("\r\nUnmodified (with respect to source)");
}
else
{
sb.Append("\r\nMODIFIED (with respect to source)");
}
return sb.ToString();
}
}
/*
* CONSTRUCTORS
*/
private Glyph()
{
}
public Glyph(int indexGlyph, FManager fm)
{
this.fm=fm;
this.index=indexGlyph;
this.typeGlyph=GConsts.TypeGlyph.Uninitialized;
this.bbox=null;
this.outl=null;
this.comp=null;
this.statusGV=new StatusGV[DefsGV.NumTest];
for (int iTest=0; iTest<DefsGV.NumTest; iTest++)
{
this.statusGV[iTest]=new StatusGV();
}
}
/*
* METHODS : ACCESS
*/
internal StatusGV StatusVal(DefsGV.TypeGV typeGV)
{
return this.statusGV[(int)typeGV];
}
/*
* METHODS : CALLS
*/
private bool CanExecDepend(DefsGV.TypeGV typePreRequired)
{
if ((this.typeGlyph!=GConsts.TypeGlyph.Simple)&&
(this.typeGlyph!=GConsts.TypeGlyph.Composite))
{
throw new ExceptionGlyph("Glyph","CanExecDepend",null);
}
if ((this.typeGlyph==GConsts.TypeGlyph.Composite)&&
(DefsGV.IsPureSimp(typePreRequired)))
return true;
if (this.statusGV[(int)typePreRequired].StatusExec!=
StatusGV.TypeStatusExec.Completed)
return false;
switch (typePreRequired)
{
case DefsGV.TypeGV.ValidateTypeGlyphSource:
return (this.typeGlyph!=GConsts.TypeGlyph.Undef);
case DefsGV.TypeGV.ValidateSimpSource:
return ((this.bbox!=null)&&(this.outl!=null));
case DefsGV.TypeGV.ValidateCompSource:
return ((this.bbox!=null)&&(this.comp!=null));
case DefsGV.TypeGV.ValidateCompBind:
if (!this.statusGV[(int)typePreRequired].IsValid)
return false;
return ((this.bbox!=null)&&(this.comp!=null)&&(this.outl!=null));
default:
if (!this.statusGV[(int)typePreRequired].IsValid)
return false;
return true;
}
}
private bool CanBeExec(DefsGV.TypeGV typeGV)
{
DefsGV.TypeGV[] typesPreRequired=DefsGV.GetTestsPreRequired(typeGV);
if (typesPreRequired!=null)
{
foreach (DefsGV.TypeGV typePreRequired in typesPreRequired)
{
if (!this.CanExecDepend(typePreRequired))
{
return false;
}
}
}
return true;
}
private void CallGV(DefsGV.TypeGV typeGV)
{
/*
* TRY/CATCH function
*/
/*
* MEANING: UNCONDITIONAL call of action
*/
GErrList gerrlist=null;
try
{
this.statusGV[(int)typeGV].StatusExec=StatusGV.TypeStatusExec.Aborted;
this.statusGV[(int)typeGV].StatusRes=StatusGV.TypeStatusRes.Undef;
gerrlist=new GErrList();
if (DefsGV.IsModifier(typeGV))
{
this.fm.OnGM(this.index,DefsGM.From(typeGV),true);
}
// check that pre-required tests are performed
if (!this.CanBeExec(typeGV))
{
this.statusGV[(int)typeGV].StatusExec=
StatusGV.TypeStatusExec.UnableToExec;
}
// call Validate.. function
System.Exception excValidation=null;
if (this.statusGV[(int)typeGV].StatusExec!=
StatusGV.TypeStatusExec.UnableToExec)
{
try
{
string strTypeCV=Enum.GetName(typeof(DefsGV.TypeGV),typeGV);
MethodInfo infoMethod=this.GetType().GetMethod(strTypeCV,
System.Reflection.BindingFlags.Instance|
System.Reflection.BindingFlags.NonPublic);
if (infoMethod!=null)
{
object[] pars={gerrlist};
// statusGV can be set to:
// Completed || UnableToExec || Aborted
try
{
this.statusGV[(int)typeGV].StatusExec=(StatusGV.TypeStatusExec)
infoMethod.Invoke(this, pars);
}
catch(System.Reflection.TargetInvocationException TIException)
{
throw TIException.InnerException;
}
GErrSign.Sign(gerrlist, typeGV, this.index);
}
if (this.statusGV[(int)typeGV].StatusExec==
StatusGV.TypeStatusExec.Completed)
{
this.statusGV[(int)typeGV].StatusRes=
gerrlist.StatusResGV(typeGV);
}
}
catch (System.Exception exc)
{
excValidation=exc;
this.statusGV[(int)typeGV].StatusExec=
StatusGV.TypeStatusExec.Aborted;
}
}
if (this.statusGV[(int)typeGV].StatusExec!=
StatusGV.TypeStatusExec.Completed)
{
this.CleanUpOnNonCompletedGV(typeGV);
GErrValidation gerrVal=new GErrValidation(this.index,
this.typeGlyph,
typeGV,
this.statusGV[(int)typeGV].StatusExec,
excValidation);
gerrlist.Add(gerrVal);
}
GErrSign.Sign(gerrlist,typeGV,this.index);
this.fm.OnGV(this.index, typeGV, gerrlist);
gerrlist.ClearRelease();
}
catch (Exception excManagement) // exception thrown by the fm management structures
{
this.statusGV[(int)typeGV].StatusExec=
StatusGV.TypeStatusExec.Aborted;
this.CleanUpOnNonCompletedGV(typeGV); // T/C function
GErrValidation gerrVal=new GErrValidation(this.index,
this.typeGlyph,
typeGV,
StatusGV.TypeStatusExec.Aborted,
excManagement);
this.fm.ReportFailure(gerrVal); // T/C function
if (gerrlist!=null)
{
try { gerrlist.ClearRelease(); }
catch (Exception) {}
}
}
}
private void CleanUpOnNonCompletedGV(DefsGV.TypeGV typeGV)
{
/*
* TRY/CATCH function
*/
switch (typeGV)
{
case DefsGV.TypeGV.ValidateTypeGlyphSource:
this.typeGlyph=GConsts.TypeGlyph.Undef;
break;
case DefsGV.TypeGV.ValidateSimpSource:
if (this.bbox!=null)
this.bbox=null;
if (this.outl!=null)
{
try
{
this.outl.ClearDestroy();
}
catch(System.Exception)
{
}
this.outl=null;
}
break;
case DefsGV.TypeGV.ValidateCompSource:
if (this.bbox!=null)
this.bbox=null;
if (this.comp!=null)
{
try
{
this.comp.ClearDestroy();
}
catch(System.Exception)
{
}
this.comp=null;
}
break;
case DefsGV.TypeGV.ValidateCompBind:
if (this.outl!=null)
{
try
{
this.outl.ClearDestroy();
}
catch(System.Exception)
{
}
this.outl=null;
}
break;
}
/*
private int index;
private GConsts.TypeGlyph typeGlyph;
BoxD bbox;
Outline outl;
Composite comp;
private FManager fm;
private StatusGV[] statusGV;
*/
}
private void CallGM(DefsGM.TypeGM typeGM, params object[] pars)
{
/*
* MEANING: UNCONDITIONAL call of action
*/
this.fm.OnGM(this.index,typeGM,true);
string strTypeGM=Enum.GetName(typeof(DefsGM.TypeGM),typeGM);
MethodInfo infoMethod=typeof(Glyph).GetMethod(strTypeGM);
try
{
infoMethod.Invoke(this,pars);
}
catch(System.Reflection.TargetInvocationException TIException)
{
throw TIException.InnerException;
}
}
override public int GetHashCode()
{
return this.IndexGlyph;
}
override public bool Equals(object obj)
{
Glyph glyph = obj as Glyph;
if ((object)glyph==null)
return false;
return (this.IndexGlyph==glyph.IndexGlyph);
}
public void ClearDestroy()
{
if (this.bbox!=null)
{
this.bbox.Clear();
this.bbox=null;
}
if (this.comp!=null)
{
this.comp.ClearDestroy();
this.comp=null;
}
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
if (this.statusGV!=null)
{
this.statusGV=null;
}
this.index=GConsts.IND_UNINITIALIZED;
this.fm=null;
}
public void ClearRelease()
{
if (this.bbox!=null)
{
this.bbox.Clear();
this.bbox=null;
}
if (this.comp!=null)
{
this.comp.ClearRelease();
this.comp=null;
}
if (this.outl!=null)
{
this.outl.ClearRelease();
this.outl=null;
}
this.index=GConsts.IND_UNINITIALIZED;
this.fm=null;
}
internal Glyph CreateCopy()
{
// TODO: write !!!
return null;
}
/*
* METHODS : VALIDATORS SOURCE
*/
internal StatusGV.TypeStatusExec ValidateTypeGlyphSource(GErrList gerrlist)
{
DIAction dia=DIActionBuilder.DIA(gerrlist,"DIAFunc_AddToListUnique");
gerrlist.DIW=new DIWrapperSource(this.index,
GConsts.TypeGlyph.Undef,
GScope.TypeGScope._GG_);
I_IOGlyphs i_IOGlyphs=this.fm.IIOGlyphs;
if (i_IOGlyphs==null)
{
//throw new ExceptionGlyph("Glyph","ValidateTypeGlyphSource",null);
return StatusGV.TypeStatusExec.Aborted;
}
int numErrBefore=gerrlist.Length;
i_IOGlyphs.ReadTypeGlyph(this.index,out this.typeGlyph, dia);
int numErrAfter=gerrlist.Length;
int iErr;
for (iErr=numErrBefore; iErr<numErrAfter; iErr++)
{
gerrlist[iErr].TypeGlyph=this.typeGlyph;
}
gerrlist.DIW=null;
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpSource(GErrList gerrlist)
{
if (this.bbox!=null)
{
this.bbox.Clear();
this.bbox=null;
}
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
if (this.typeGlyph==GConsts.TypeGlyph.Empty)
{
return StatusGV.TypeStatusExec.Completed;
}
if (this.typeGlyph!=GConsts.TypeGlyph.Simple)
{
//throw new ExceptionGlyph("Glyph","ValidateSimpSource",null);
return StatusGV.TypeStatusExec.Aborted;
}
DIAction dia=DIActionBuilder.DIA(gerrlist,"DIAFunc_AddToListUnique");
gerrlist.DIW=new DIWrapperSource(this.index,this.typeGlyph,GScope.TypeGScope._GGB_);
I_IOGlyphs i_IOGlyphs=this.fm.IIOGlyphs;
if (i_IOGlyphs==null)
{
//throw new ExceptionGlyph("Glyph","ValidateSimpSource",null);
return StatusGV.TypeStatusExec.Aborted;
}
i_IOGlyphs.ReadGGB(this.index, out this.bbox, dia);
i_IOGlyphs.ReadGGO(this.index, out this.outl, dia);
gerrlist.DIW=null;
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateCompSource(GErrList gerrlist)
{
if (this.bbox!=null)
{
this.bbox.Clear();
this.bbox=null;
}
if (this.comp!=null)
{
this.comp.ClearDestroy();
this.comp=null;
}
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
if (this.typeGlyph==GConsts.TypeGlyph.Empty)
{
return StatusGV.TypeStatusExec.Completed;
}
if (this.typeGlyph!=GConsts.TypeGlyph.Composite)
{
//throw new ExceptionGlyph("Glyph","ValidateCompSource",null);
return StatusGV.TypeStatusExec.Aborted;
}
DIAction dia=DIActionBuilder.DIA(gerrlist,"DIAFunc_AddToListUnique");
gerrlist.DIW=new DIWrapperSource(this.index,this.typeGlyph,GScope.TypeGScope._GGB_);
I_IOGlyphs i_IOGlyphs=this.fm.IIOGlyphs;
if (i_IOGlyphs==null)
{
//throw new ExceptionGlyph("Glyph","ValidateCompSource",null);
return StatusGV.TypeStatusExec.Aborted;
}
i_IOGlyphs.ReadGGB(this.index, out this.bbox, dia);
i_IOGlyphs.ReadGGC(this.index, out this.comp, dia);
if (this.comp!=null)
{
this.fm.OnGComposite(this.index);
}
gerrlist.DIW=null;
return StatusGV.TypeStatusExec.Completed;
}
/*
* METHODS : VALIDATORS CONTENT
*
*/
internal StatusGV.TypeStatusExec ValidateSimpBBox(GErrList gerrlist)
{
if ((this.bbox==null)||(this.outl==null))
{
//throw new ExceptionGlyph("Glyph","ValidateSimpBBox",null);
return StatusGV.TypeStatusExec.Aborted;
}
BoxD bboxCP; // bbox for the control points
bboxCP=this.outl.BBoxCP;
if (!bbox.Equals(bboxCP))
{
GErrBBox gerrBbox=new GErrBBox(this.IndexGlyph,
this.typeGlyph,
this.bbox,bboxCP);
gerrlist.Add(gerrBbox);
}
BoxD bboxOutl; // bbox for Outline
bboxOutl=this.outl.BBox;
//bboxOutline.SetEnlargeFU();
if (!bboxOutl.Equals(bboxCP))
{
// warning
GErrExtremeNotOnCurve gerrExtreme=new
GErrExtremeNotOnCurve(this.IndexGlyph,
this.typeGlyph,bboxCP,bboxOutl);
gerrlist.Add(gerrExtreme);
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpKnotDupl(GErrList gerrlist)
{
ListPairInt infosKnotDupl=new ListPairInt();
for (int pozCont=0; pozCont<this.outl.NumCont; pozCont++)
{
Contour cont=this.outl.ContourByPoz(pozCont);
cont.KnotDupl(infosKnotDupl);
}
if (infosKnotDupl.Count!=0)
{
GErr gerr=new GErrKnotDupl(this.index, infosKnotDupl);
gerrlist.Add(gerr);
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpContDegen(GErrList gerrlist)
{
ArrayList listIndsKnotStart=new ArrayList();
for (int pozCont=0; pozCont<this.outl.NumCont; pozCont++)
{
Contour cont=this.outl.ContourByPoz(pozCont);
if (cont.IsDegen)
{
listIndsKnotStart.Add(cont.IndKnotStart);
}
}
int numCont=listIndsKnotStart.Count;
if (numCont!=0)
{
int[] indsKnotStart=new int[numCont];
for (int iCont=0; iCont<numCont; iCont++)
{
indsKnotStart[iCont]=(int)listIndsKnotStart[iCont];
}
GErr gerr=new GErrContDegen(this.index, indsKnotStart);
gerrlist.Add(gerr);
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpContWrap(GErrList gerrlist)
{
/*
* ASSUMPTION: determines only "fully" wrapped contours
*/
if (this.outl==null)
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContWrap",null);
return StatusGV.TypeStatusExec.Aborted;
}
ArrayList pozsContWrap=new ArrayList();
for (int pozCont=0; pozCont<this.outl.NumCont; pozCont++)
{
Contour cont=this.outl.ContourByPoz(pozCont);
bool isWrapped;
if (!cont.IsWrapped(out isWrapped))
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContWrap",null);
return StatusGV.TypeStatusExec.Aborted;
}
if (isWrapped)
{
pozsContWrap.Add(pozCont);
}
}
int numCont=pozsContWrap.Count;
if (numCont!=0)
{
int[] indsKnotStart=new int[numCont];
for (int iCont=0; iCont<numCont; iCont++)
{
int pozCont=(int)pozsContWrap[iCont];
indsKnotStart[iCont]=this.Outl.ContourByPoz(pozCont).IndKnotStart;
}
GErr gerr=new GErrContWrap(this.index, indsKnotStart);
gerrlist.Add(gerr);
//this.isOrientDefined=false;
}
/*
else
{
//this.isOrientDefined=true;
}
*/
pozsContWrap.Clear();
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpContDupl(GErrList gerrlist)
{
if (this.outl==null)
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContDupl",null);
return StatusGV.TypeStatusExec.Aborted;
}
ListPairInt pairsIndKnotStart=new ListPairInt();
for (int pozContA=0; pozContA<this.outl.NumCont-1; pozContA++)
{
Contour contA=this.outl.ContourByPoz(pozContA);
for (int pozContB=pozContA+1; pozContB<this.outl.NumCont; pozContB++)
{
Contour contB=this.outl.ContourByPoz(pozContB);
bool isDupl;
if (!contA.AreDuplicated(contB, out isDupl))
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContDupl",null);
return StatusGV.TypeStatusExec.Aborted;
}
if (isDupl)
{
pairsIndKnotStart.Add(this.outl.ContourByPoz(pozContA).IndKnotStart,
this.outl.ContourByPoz(pozContB).IndKnotStart);
}
}
}
if (pairsIndKnotStart.Count!=0)
{
GErr gerr=new GErrContDupl(this.index, pairsIndKnotStart);
gerrlist.Add(gerr);
//this.isOrientDefined=false;
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpContInters(GErrList gerrlist)
{
/*
* MEANING: finds ALL intersections:
* including D0, D1 and S/I bezier
*/
ListInfoInters linters = new ListInfoInters();
if (this.outl==null)
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContInters",null);
return StatusGV.TypeStatusExec.Aborted;
}
if (!this.outl.Intersect(linters))
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContInters",null);
return StatusGV.TypeStatusExec.Aborted;
}
if (linters.Count>0)
{
GErr gerr=new GErrContInters(this.index, linters);
gerrlist.Add(gerr);
//this.isOrientDefined=false;
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateSimpContMisor(GErrList gerrlist)
{
if ((this.statusGV[(int)DefsGV.TypeGV.ValidateSimpContDupl].StatusRes!=
StatusGV.TypeStatusRes.NoErrors)||
(this.statusGV[(int)DefsGV.TypeGV.ValidateSimpContWrap].StatusRes!=
StatusGV.TypeStatusRes.NoErrors)||
(this.statusGV[(int)DefsGV.TypeGV.ValidateSimpContInters].StatusRes!=
StatusGV.TypeStatusRes.NoErrors))
{
return StatusGV.TypeStatusExec.UnableToExec;
}
if (this.outl==null)
{
//throw new ExceptionGlyph("Glyph","ValidateSimpContMisor",null);
return StatusGV.TypeStatusExec.Aborted;
}
ArrayList pozsContMisor=new ArrayList();
for (int pozCont=0; pozCont<this.outl.NumCont; pozCont++)
{
Contour cont=this.outl.ContourByPoz(pozCont);
bool isMisoriented;
if (!cont.IsMisoriented(this.outl, out isMisoriented))
{
throw new ExceptionGlyph("Glyph","ValidateSimpContMisor",null);
//return StatusGV.TypeStatusExec.Aborted;
}
if (isMisoriented)
{
pozsContMisor.Add(pozCont);
}
}
int numCont=pozsContMisor.Count;
if (numCont!=0)
{
int[] indsKnotStart=new int[numCont];
for (int iCont=0; iCont<numCont; iCont++)
{
int pozCont=(int)pozsContMisor[iCont];
indsKnotStart[iCont]=this.Outl.ContourByPoz(pozCont).IndKnotStart;
}
GErr gerr=new GErrContMisor(this.index, indsKnotStart);
gerrlist.Add(gerr);
}
pozsContMisor.Clear();
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateCompBind(GErrList gerrlist)
{
/*
* ASSUMPTION: - the glyph is composite and Comp is already
* read
* - clears outline that is already
* built in case of failure to load one
* of components
*/
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
GErr gerr;
bool isCircular=this.fm.PathCompBind.Contains(this.index);
if (isCircular)
{
int numGlyph=this.fm.PathCompBind.Count;
int[] pathCompBind=new int[numGlyph+1];
for (int iGlyph=0; iGlyph<numGlyph; iGlyph++)
{
pathCompBind[iGlyph]=(int)this.fm.PathCompBind[iGlyph];
}
pathCompBind[numGlyph]=this.index;
gerr=new GErrComponentCircularDependency(this.index,
this.index, pathCompBind);
gerrlist.Add(gerr);
this.fm.PathCompBind.Clear();
return StatusGV.TypeStatusExec.Completed;
}
if (this.outl!=null)
{
this.outl.ClearReset();
this.outl=null;
}
if (this.comp==null)
{
//throw new ExceptionGlyph("Glyph","ValidateCompBind",null);
return StatusGV.TypeStatusExec.Aborted;
}
this.fm.PathCompBind.Add(this.index);
//throw new ArgumentOutOfRangeException();
if (this.comp.NumComponent==0)
{
this.outl=new Outline();
gerr=new GErrComponentEmpty(this.index,GConsts.IND_UNDEFINED);
gerrlist.Add(gerr);
return StatusGV.TypeStatusExec.Completed;
}
foreach (Component component in this.comp)
{
int indGlyphComponent=component.IndexGlyphComponent;
if ((indGlyphComponent<0)||(indGlyphComponent>=this.fm.FNumGlyph))
{
gerr=new GErrComponentIndexGlyph(this.index,indGlyphComponent);
gerrlist.Add(gerr);
this.fm.PathCompBind.Clear();
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
return StatusGV.TypeStatusExec.Completed;
}
Glyph glyphComponent=this.fm.GGet(indGlyphComponent);
if (glyphComponent==null)
{
gerr=new GErrComponentLoadFailure(this.index,indGlyphComponent);
gerrlist.Add(gerr);
this.fm.PathCompBind.Clear();
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
return StatusGV.TypeStatusExec.Completed;
}
if (glyphComponent.typeGlyph==GConsts.TypeGlyph.Empty)
{
gerr=new GErrComponentEmpty(this.index,indGlyphComponent);
gerrlist.Add(gerr);
continue;
}
else
{
if (glyphComponent.Outl==null)
{
gerr=new GErrComponentLoadFailure(this.index,indGlyphComponent);
gerrlist.Add(gerr);
this.fm.PathCompBind.Clear();
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
return StatusGV.TypeStatusExec.Completed;
}
}
if (this.outl==null)
{
this.outl=new Outline();
}
ArrayList errsLoadComponent;
if (!this.outl.LoadComponent(component,
glyphComponent.outl,
out errsLoadComponent))
{
this.fm.PathCompBind.Clear();
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
//throw new ExceptionGlyph("Glyph","ValidateCompBind",null);
return StatusGV.TypeStatusExec.Aborted;
}
if (errsLoadComponent!=null)
{
foreach (Component.TypeErrLoadComponent errLoadComponent in errsLoadComponent)
{
gerr=null;
switch (errLoadComponent)
{
case Component.TypeErrLoadComponent.IncorrectShiftSpecification:
gerr=new GErrComponentIncorrectShift(this.index,
component.IndexGlyphComponent);
break;
case Component.TypeErrLoadComponent.IncorrectIndexKnotGlyph:
gerr=new GErrComponentIndexKnot(this.index,
component.IndexGlyphComponent,
component.IndexKnotAttGlyph,
true);
break;
case Component.TypeErrLoadComponent.IncorrectIndexKnotComponent:
gerr=new GErrComponentIndexKnot(this.index,
component.IndexGlyphComponent,
component.IndexKnotAttComponent,
false);
break;
case Component.TypeErrLoadComponent.IncorrectTransform:
gerr=new GErrComponentIncorrectTransform(this.index,
component.IndexGlyphComponent,
component.TrOTF2Dot14);
break;
}
gerrlist.Add(gerr);
}
if (this.outl!=null)
{
this.outl.ClearDestroy();
this.outl=null;
}
this.fm.PathCompBind.Clear();
return StatusGV.TypeStatusExec.Completed;
}
}
this.fm.PathCompBind.RemoveAt(this.fm.PathCompBind.Count-1);
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateCompBBox(GErrList gerrlist)
{
if ((this.bbox==null)||(this.outl==null))
{
//throw new ExceptionGlyph("Glyph","ValidateCompBBox",null);
return StatusGV.TypeStatusExec.Aborted;
}
BoxD bboxCP; // bbox for the control points
bboxCP=this.outl.BBoxCP;
if (!this.bbox.Equals(bboxCP))
{
double deviation=this.bbox.DeviationMax(bboxCP);
bool toSkipError=((this.outl.IsChangedByRound)&&(Math.Abs(deviation)<=1.0));
if (!toSkipError)
{
GErrBBox gerrBbox=new GErrBBox(this.IndexGlyph,
this.typeGlyph,
this.bbox,bboxCP);
gerrlist.Add(gerrBbox);
}
}
BoxD bboxOutl; // bbox for Outline
bboxOutl=this.outl.BBox;
//bboxOutline.SetEnlargeFU();
if (!bboxOutl.Equals(bboxCP))
{
// warning
GErrExtremeNotOnCurve gerrExtreme=new
GErrExtremeNotOnCurve(this.IndexGlyph,
this.typeGlyph,bboxCP,bboxOutl);
gerrlist.Add(gerrExtreme);
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateCompComponentDupl(GErrList gerrlist)
{
ListPairInt pairsIndComponentDupl=new ListPairInt();
if ((this.comp==null)||(this.outl==null))
{
//throw new ExceptionGlyph("Glyph","ValidateCompComponentDupl",null);
return StatusGV.TypeStatusExec.Aborted;
}
int numComponent=this.comp.NumComponent;
for (int pozComponentA=0; pozComponentA<numComponent-1; pozComponentA++)
{
Component componentA=this.comp.ComponentByPoz(pozComponentA);
for (int pozComponentB=pozComponentA+1; pozComponentB<numComponent; pozComponentB++)
{
ListInfoInters linters=new ListInfoInters();
Component componentB=this.comp.ComponentByPoz(pozComponentB);
bool areDuplicated;
this.outl.AreDuplicatedComponents(componentA,componentB,out areDuplicated);
if (areDuplicated)
{
pairsIndComponentDupl.Add(componentA.IndexGlyphComponent,
componentB.IndexGlyphComponent);
}
}
}
if (pairsIndComponentDupl.Count!=0)
{
GErr gerr=new GErrComponentDupl(this.index, pairsIndComponentDupl);
gerrlist.Add(gerr);
}
return StatusGV.TypeStatusExec.Completed;
}
internal StatusGV.TypeStatusExec ValidateCompComponentInters(GErrList gerrlist)
{
ArrayList arrLinters=new ArrayList();
if ((this.comp==null)||(this.outl==null))
{
//throw new ExceptionGlyph("Glyph","ValidateCompComponentInters",null);
return StatusGV.TypeStatusExec.Aborted;
}
int numComponent=this.comp.NumComponent;
for (int pozComponentA=0; pozComponentA<numComponent-1; pozComponentA++)
{
Component componentA=this.comp.ComponentByPoz(pozComponentA);
for (int pozComponentB=pozComponentA+1; pozComponentB<numComponent; pozComponentB++)
{
ListInfoInters linters=new ListInfoInters();
Component componentB=this.comp.ComponentByPoz(pozComponentB);
bool areDuplicated;
this.outl.AreDuplicatedComponents(componentA,componentB,out areDuplicated);
if (areDuplicated)
continue;
this.outl.IntersectComponents(componentA, componentB, linters);
if (linters.Count!=0)
{
linters.SetIndGlyphComponent(componentA.IndexGlyphComponent,
componentB.IndexGlyphComponent);
arrLinters.Add(linters);
}
}
}
if (arrLinters.Count!=0)
{
GErr gerr=new GErrComponentInters(this.index, arrLinters);
gerrlist.Add(gerr);
}
return StatusGV.TypeStatusExec.Completed;
}
/*
* VALIDATION GROUPS & Auxiliary Functions
*/
public void GValidate()
{
bool performGV;
bool needsActionGV;
needsActionGV=this.NeedsActionForValidate(DefsGV.TypeGV.ValidateTypeGlyphSource);
if (needsActionGV)
{
this.CallGV(DefsGV.TypeGV.ValidateTypeGlyphSource);
}
if (this.typeGlyph==GConsts.TypeGlyph.Undef)
{
foreach (StatusGV stGV in this.statusGV)
{
stGV.StatusExec=StatusGV.TypeStatusExec.UnableToExec;
}
return;
}
if (this.typeGlyph==GConsts.TypeGlyph.Empty)
return;
if ((this.TypeGlyph==GConsts.TypeGlyph.Simple)||
(this.TypeGlyph==GConsts.TypeGlyph.Composite))
{
DefsGV.TypeGV[] orderTest=null;
if (this.typeGlyph==GConsts.TypeGlyph.Simple)
{
orderTest=DefsGV.orderTestSimp;
}
if (this.typeGlyph==GConsts.TypeGlyph.Composite)
{
orderTest=DefsGV.orderTestComp;
}
FlagsGV flagsGV=this.fm.FlagsPerformGV;
foreach (DefsGV.TypeGV typeGV in orderTest)
{
performGV=flagsGV[typeGV];
needsActionGV=this.NeedsActionForValidate(typeGV);
if ((!performGV)||(!needsActionGV))
continue;
this.CallGV(typeGV);
}
}
}
public void GResetFromSource()
{
/*
* MEANING: - RESETS glyph from original source
* - BINDS composite glyphs
*/
if (this.NeedsActionForReset(DefsGV.TypeGV.ValidateTypeGlyphSource))
{
this.CallGV(DefsGV.TypeGV.ValidateTypeGlyphSource);
}
switch (this.typeGlyph)
{
case GConsts.TypeGlyph.Simple:
if (this.NeedsActionForReset(DefsGV.TypeGV.ValidateSimpSource))
{
this.CallGV(DefsGV.TypeGV.ValidateSimpSource);
}
break;
case GConsts.TypeGlyph.Composite:
if (this.NeedsActionForReset(DefsGV.TypeGV.ValidateCompSource))
{
this.CallGV(DefsGV.TypeGV.ValidateCompSource);
}
if (this.NeedsActionForReset(DefsGV.TypeGV.ValidateCompBind))
{
this.CallGV(DefsGV.TypeGV.ValidateCompBind);
}
break;
}
}
private bool NeedsActionForValidate(DefsGV.TypeGV typeGV)
{
if (DefsGV.IsSourceValidator(typeGV))
{
return (this.statusGV[(int)typeGV].StatusExec==
StatusGV.TypeStatusExec.NeverExec);
}
return (!this.statusGV[(int)typeGV].IsValid);
}
private bool NeedsActionForReset(DefsGV.TypeGV typeGV)
{
if (DefsGV.IsPureValidator(typeGV))
return false;
if ((typeGV==DefsGV.TypeGV.ValidateSimpSource)&&
(this.typeGlyph==GConsts.TypeGlyph.Composite))
return false;
if ((typeGV==DefsGV.TypeGV.ValidateCompSource)&&
(this.typeGlyph==GConsts.TypeGlyph.Simple))
return false;
int ind=(int)typeGV;
return (!this.statusGV[(int)typeGV].IsValid);
}
/*
* METHODS: MODIFY: GM
*/
public bool ModifyMoveKnot(int indKnot, VecD vecLocNew)
{
this.fm.OnGM(this.index,DefsGM.TypeGM.ModifyMoveKnot,true);
Knot knot=this.outl.KnotByInd(indKnot);
if (knot!=null)
{
knot.Val.From(vecLocNew);
bool isChanged;
knot.Val.FURound(out isChanged);
}
return true;
}
public bool ModifyDeleteKnot(int indKnot)
{
this.fm.OnGM(this.index,DefsGM.TypeGM.ModifyDeleteKnot,true);
this.outl.KnotDeleteByInd(indKnot);
return true;
}
/*
* METHODS: INFO (all information is copied
* prior passing to a user)
*/
public Knot InfoKnotByLocation(VecD vecLocation)
{
Knot knotNearestCopy=null;
if (this.outl!=null)
{
Knot knotNearest=this.outl.KnotNearest(vecLocation);
if (knotNearest!=null)
{
knotNearestCopy=new Knot(knotNearest);
}
}
return knotNearestCopy;
}
public Knot InfoKnotByInd(int indKnot)
{
Knot knot=this.Outl.KnotByInd(indKnot);
if (knot==null)
return null;
return new Knot(knot);
}
/*
* METHODS: I_DRAWABLE
*/
public void Draw(I_Draw i_draw, DrawParam dp)
{
if (this.bbox!=null)
{
DrawParam dpBBox=new DrawParam("Yellow",0.5F);
this.bbox.Draw(i_draw, dpBBox);
}
if (this.outl!=null)
{
DrawParamKnot dpKnot=new DrawParamKnot("Blue",0.5F,1.5F,true);
DrawParamVec dpEndPoints=new DrawParamVec("Orange",0.5F,0.7F,true);
string colorCurve;
if (this.typeGlyph==GConsts.TypeGlyph.Composite)
{
colorCurve="Blue";
}
else
{
bool isOrientDefined=
(this.statusGV[(int)DefsGV.TypeGV.ValidateSimpContMisor].IsValid)&&
(this.statusGV[(int)DefsGV.TypeGV.ValidateSimpContMisor].StatusExec==
StatusGV.TypeStatusExec.Completed);
colorCurve=isOrientDefined? "Blue": "Green";
}
DrawParamCurve dpCurve=new DrawParamCurve(colorCurve,1F,true,dpEndPoints);
DrawParamContour dpContour=new DrawParamContour(dpCurve,dpKnot);
this.outl.Draw(i_draw, dpContour);
BoxD bboxComputed=this.outl.BBox;
bboxComputed.SetEnlargeFU();
DrawParam dpBBoxComputed=new DrawParam("Yellow",0.5F);
bboxComputed.Draw(i_draw,dpBBoxComputed);
}
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System.Globalization
{
public partial class CompareInfo
{
private unsafe void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
if (GlobalizationMode.Invariant)
{
_sortHandle = IntPtr.Zero;
}
else
{
const uint LCMAP_SORTHANDLE = 0x20000000;
IntPtr handle;
int ret = Interop.Kernel32.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
_sortHandle = ret > 0 ? handle : IntPtr.Zero;
}
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
string stringSource,
int offset,
int cchSource,
string value,
int cchValue,
bool bIgnoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(stringSource != null);
Debug.Assert(value != null);
fixed (char* pSource = stringSource)
fixed (char* pValue = value)
{
int ret = Interop.Kernel32.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource + offset,
cchSource,
pValue,
cchValue,
bIgnoreCase ? 1 : 0);
return ret < 0 ? ret : ret + offset;
}
}
private static unsafe int FindStringOrdinal(
uint dwFindStringOrdinalFlags,
ReadOnlySpan<char> source,
ReadOnlySpan<char> value,
bool bIgnoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pValue = &MemoryMarshal.GetReference(value))
{
int ret = Interop.Kernel32.FindStringOrdinal(
dwFindStringOrdinalFlags,
pSource,
source.Length,
pValue,
value.Length,
bIgnoreCase ? 1 : 0);
return ret;
}
}
internal static int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int IndexOfOrdinalCore(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase, bool fromBeginning)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source.Length != 0);
Debug.Assert(value.Length != 0);
uint positionFlag = fromBeginning ? (uint)FIND_FROMSTART : FIND_FROMEND;
return FindStringOrdinal(positionFlag, source, value, ignoreCase);
}
internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(value != null);
return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(ReadOnlySpan<char> source, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
uint flags = LCMAP_SORTKEY | (uint)GetNativeCompareFlags(options);
fixed (char* pSource = source)
{
int sortKeyLength = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
flags,
pSource, source.Length /* in chars */,
null, 0,
null, null, _sortHandle);
if (sortKeyLength == 0)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
// Note in calls to LCMapStringEx below, the input buffer is specified in wchars (and wchar count),
// but the output buffer is specified in bytes (and byte count). This is because when generating
// sort keys, LCMapStringEx treats the output buffer as containing opaque binary data.
// See https://docs.microsoft.com/en-us/windows/desktop/api/winnls/nf-winnls-lcmapstringex.
byte[] borrowedArr = null;
Span<byte> span = sortKeyLength <= 512 ?
stackalloc byte[512] :
(borrowedArr = ArrayPool<byte>.Shared.Rent(sortKeyLength));
fixed (byte* pSortKey = &MemoryMarshal.GetReference(span))
{
if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
flags,
pSource, source.Length /* in chars */,
pSortKey, sortKeyLength,
null, null, _sortHandle) != sortKeyLength)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
}
int hash = Marvin.ComputeHash32(span.Slice(0, sortKeyLength), Marvin.DefaultSeed);
// Return the borrowed array if necessary.
if (borrowedArr != null)
{
ArrayPool<byte>.Shared.Return(borrowedArr);
}
return hash;
}
}
private static unsafe int CompareStringOrdinalIgnoreCase(ref char string1, int count1, ref char string2, int count2)
{
Debug.Assert(!GlobalizationMode.Invariant);
fixed (char* char1 = &string1)
fixed (char* char2 = &string2)
{
// Use the OS to compare and then convert the result to expected value by subtracting 2
return Interop.Kernel32.CompareStringOrdinal(char1, count1, char2, count2, true) - 2;
}
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
private unsafe int CompareString(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
Debug.Assert(string2 != null);
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = &MemoryMarshal.GetReference(string1))
fixed (char* pString2 = &string2.GetRawStringData())
{
Debug.Assert(pString1 != null);
int result = Interop.Kernel32.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1,
string1.Length,
pString2,
string2.Length,
null,
null,
_sortHandle);
if (result == 0)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int CompareString(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pString1 = &MemoryMarshal.GetReference(string1))
fixed (char* pString2 = &MemoryMarshal.GetReference(string2))
{
Debug.Assert(pString1 != null);
Debug.Assert(pString2 != null);
int result = Interop.Kernel32.CompareStringEx(
pLocaleName,
(uint)GetNativeCompareFlags(options),
pString1,
string1.Length,
pString2,
string2.Length,
null,
null,
_sortHandle);
if (result == 0)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
ReadOnlySpan<char> lpStringSource,
ReadOnlySpan<char> lpStringValue,
int* pcchFound)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!lpStringSource.IsEmpty);
Debug.Assert(!lpStringValue.IsEmpty);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = &MemoryMarshal.GetReference(lpStringSource))
fixed (char* pValue = &MemoryMarshal.GetReference(lpStringValue))
{
return Interop.Kernel32.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pSource,
lpStringSource.Length,
pValue,
lpStringValue.Length,
pcchFound,
null,
null,
_sortHandle);
}
}
private unsafe int FindString(
uint dwFindNLSStringFlags,
string lpStringSource,
int startSource,
int cchSource,
string lpStringValue,
int startValue,
int cchValue,
int* pcchFound)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(lpStringSource != null);
Debug.Assert(lpStringValue != null);
string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
fixed (char* pLocaleName = localeName)
fixed (char* pSource = lpStringSource)
fixed (char* pValue = lpStringValue)
{
char* pS = pSource + startSource;
char* pV = pValue + startValue;
return Interop.Kernel32.FindNLSStringEx(
pLocaleName,
dwFindNLSStringFlags,
pS,
cchSource,
pV,
cchValue,
pcchFound,
null,
null,
_sortHandle);
}
}
internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source != null);
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
Debug.Assert((options & CompareOptions.Ordinal) == 0);
int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count,
target, 0, target.Length, matchLengthPtr);
if (retValue >= 0)
{
return retValue + startIndex;
}
return -1;
}
internal unsafe int IndexOfCore(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(source.Length != 0);
Debug.Assert(target.Length != 0);
Debug.Assert((options == CompareOptions.None || options == CompareOptions.IgnoreCase));
uint positionFlag = fromBeginning ? (uint)FIND_FROMSTART : FIND_FROMEND;
return FindString(positionFlag | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr);
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(target != null);
Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
return startIndex;
if ((options & CompareOptions.Ordinal) != 0)
{
return FastLastIndexOfString(source, target, startIndex, count, target.Length);
}
else
{
int retValue = FindString(FIND_FROMEND | (uint)GetNativeCompareFlags(options), source, startIndex - count + 1,
count, target, 0, target.Length, null);
if (retValue >= 0)
{
return retValue + startIndex - (count - 1);
}
}
return -1;
}
private unsafe bool StartsWith(string source, string prefix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(prefix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length,
prefix, 0, prefix.Length, null) >= 0;
}
private unsafe bool StartsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!prefix.IsEmpty);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, prefix, null) >= 0;
}
private unsafe bool EndsWith(string source, string suffix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!string.IsNullOrEmpty(source));
Debug.Assert(!string.IsNullOrEmpty(suffix));
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length,
suffix, 0, suffix.Length, null) >= 0;
}
private unsafe bool EndsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!suffix.IsEmpty);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, suffix, null) >= 0;
}
// PAL ends here
[NonSerialized]
private IntPtr _sortHandle;
private const uint LCMAP_SORTKEY = 0x00000400;
private const uint LCMAP_HASH = 0x00040000;
private const int FIND_STARTSWITH = 0x00100000;
private const int FIND_ENDSWITH = 0x00200000;
private const int FIND_FROMSTART = 0x00400000;
private const int FIND_FROMEND = 0x00800000;
// TODO: Instead of this method could we just have upstack code call LastIndexOfOrdinal with ignoreCase = false?
private static unsafe int FastLastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount)
{
int retValue = -1;
int sourceStartIndex = startIndex - sourceCount + 1;
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
int endPattern = sourceCount - targetCount;
if (endPattern < 0)
return -1;
Debug.Assert(target.Length >= 1);
char patternChar0 = spTarget[0];
for (int ctrSrc = endPattern; ctrSrc >= 0; ctrSrc--)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex - sourceCount + 1;
}
}
return retValue;
}
private unsafe SortKey CreateSortKey(string source, CompareOptions options)
{
Debug.Assert(!GlobalizationMode.Invariant);
if (source == null) { throw new ArgumentNullException(nameof(source)); }
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData = null;
if (source.Length == 0)
{
keyData = Array.Empty<byte>();
}
else
{
uint flags = LCMAP_SORTKEY | (uint)GetNativeCompareFlags(options);
fixed (char *pSource = source)
{
int sortKeyLength = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
flags,
pSource, source.Length,
null, 0,
null, null, _sortHandle);
if (sortKeyLength == 0)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
keyData = new byte[sortKeyLength];
fixed (byte* pBytes = keyData)
{
if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
flags,
pSource, source.Length,
pBytes, keyData.Length,
null, null, _sortHandle) != sortKeyLength)
{
throw new ArgumentException(SR.Arg_ExternalException);
}
}
}
}
return new SortKey(Name, source, options, keyData);
}
private static unsafe bool IsSortable(char* text, int length)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(text != null);
return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length);
}
private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
private static int GetNativeCompareFlags(CompareOptions options)
{
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
// TODO: Can we try for GetNativeCompareFlags to never
// take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special
// in some places.
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.IgnoreWidth |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
return nativeCompareFlags;
}
private unsafe SortVersion GetSortVersion()
{
Debug.Assert(!GlobalizationMode.Invariant);
Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx();
nlsVersion.dwNLSVersionInfoSize = sizeof(Interop.Kernel32.NlsVersionInfoEx);
Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion);
return new SortVersion(
nlsVersion.dwNLSVersion,
nlsVersion.dwEffectiveId == 0 ? LCID : nlsVersion.dwEffectiveId,
nlsVersion.guidCustomVersion);
}
}
}
| |
// ****************************************************************
// Copyright 2009, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
namespace PclUnit.Constraints.Pieces
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class ConstraintFactory
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return Is.Not; }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return Has.No; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return Is.All; }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return Has.Some; }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return Has.None; }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public static ConstraintExpression Exactly(int expectedCount)
{
return Has.Exactly(expectedCount);
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return Has.Property(name);
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Has.Length; }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Has.Count; }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Has.Message; }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Has.InnerException; }
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the suppled argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the suppled argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the suppled argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the suppled argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<T>()
{
return new ExactTypeConstraint(typeof(T));
}
#endif
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf(expectedType)")]
public InstanceOfTypeConstraint InstanceOfType(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
[Obsolete("Use InstanceOf<T>()")]
public InstanceOfTypeConstraint InstanceOfType<T>()
{
return new InstanceOfTypeConstraint(typeof(T));
}
#endif
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<T>()
{
return new AssignableFromConstraint(typeof(T));
}
#endif
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<T>()
{
return new AssignableToConstraint(typeof(T));
}
#endif
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region Member
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Member(object expected)
{
return new CollectionContainsConstraint(expected);
}
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Contains(object expected)
{
return new CollectionContainsConstraint(expected);
}
#endregion
#region Contains
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return new ContainsConstraint(expected);
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint ContainsSubstring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region DoesNotContain
/// <summary>
/// Returns a constraint that fails if the actual
/// value contains the substring supplied as an argument.
/// </summary>
public SubstringConstraint DoesNotContain(string expected)
{
return new ConstraintExpression().Not.ContainsSubstring(expected);
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint DoesNotStartWith(string expected)
{
return new ConstraintExpression().Not.StartsWith(expected);
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint DoesNotEndWith(string expected)
{
return new ConstraintExpression().Not.EndsWith(expected);
}
#endregion
#region Matches
// /// <summary>
// /// Returns a constraint that succeeds if the actual
// /// value matches the Regex pattern supplied as an argument.
// /// </summary>
// public RegexConstraint Matches(string pattern)
// {
// return new RegexConstraint(pattern);
// }
//
// /// <summary>
// /// Returns a constraint that succeeds if the actual
// /// value matches the Regex pattern supplied as an argument.
// /// </summary>
// public RegexConstraint StringMatching(string pattern)
// {
// return new RegexConstraint(pattern);
// }
#endregion
#region DoesNotMatch
// /// <summary>
// /// Returns a constraint that fails if the actual
// /// value matches the pattern supplied as an argument.
// /// </summary>
// public RegexConstraint DoesNotMatch(string pattern)
// {
// return new ConstraintExpression().Not.Matches(pattern);
// }
#endregion
#region InRange<T>
#if CLR_2_0 || CLR_4_0
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T>
{
return new RangeConstraint<T>(from, to);
}
#endif
#endregion
}
}
| |
// <copyright file="MetricAPITest.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Threading;
using OpenTelemetry.Tests;
using Xunit;
using Xunit.Abstractions;
namespace OpenTelemetry.Metrics.Tests
{
public class MetricApiTest
{
private const int MaxTimeToAllowForFlush = 10000;
private static int numberOfThreads = Environment.ProcessorCount;
private static long deltaLongValueUpdatedByEachCall = 10;
private static double deltaDoubleValueUpdatedByEachCall = 11.987;
private static int numberOfMetricUpdateByEachThread = 100000;
private readonly ITestOutputHelper output;
public MetricApiTest(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void ObserverCallbackTest()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems)
.Build();
var measurement = new Measurement<int>(100, new("name", "apple"), new("color", "red"));
meter.CreateObservableGauge("myGauge", () => measurement);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("myGauge", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
Assert.Equal(100, metricPoint.GetGaugeLastValueLong());
Assert.True(metricPoint.Tags.Count > 0);
}
[Fact]
public void ObserverCallbackExceptionTest()
{
using var meter = new Meter(Utils.GetCurrentMethodName());
var exportedItems = new List<Metric>();
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems)
.Build();
var measurement = new Measurement<int>(100, new("name", "apple"), new("color", "red"));
meter.CreateObservableGauge("myGauge", () => measurement);
meter.CreateObservableGauge<long>("myBadGauge", observeValues: () => throw new Exception("gauge read error"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("myGauge", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
Assert.Equal(100, metricPoint.GetGaugeLastValueLong());
Assert.True(metricPoint.Tags.Count > 0);
}
[Theory]
[InlineData("unit")]
[InlineData("")]
[InlineData(null)]
public void MetricUnitIsExportedCorrectly(string unit)
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var counter = meter.CreateCounter<long>("name1", unit);
counter.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal(unit ?? string.Empty, metric.Unit);
}
[Theory]
[InlineData("description")]
[InlineData("")]
[InlineData(null)]
public void MetricDescriptionIsExportedCorrectly(string description)
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var counter = meter.CreateCounter<long>("name1", null, description);
counter.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal(description ?? string.Empty, metric.Description);
}
[Fact]
public void DuplicateInstrumentRegistration_NoViews_IdenticalInstruments()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription");
var duplicateInstrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription");
instrument.Add(10);
duplicateInstrument.Add(20);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("instrumentName", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
var metricPoint1 = metricPoints[0];
Assert.Equal(30, metricPoint1.GetSumLong());
}
[Fact]
public void DuplicateInstrumentRegistration_NoViews_DuplicateInstruments_DifferentDescription()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription1");
var duplicateInstrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription2");
instrument.Add(10);
duplicateInstrument.Add(20);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metric1 = exportedItems[0];
var metric2 = exportedItems[1];
Assert.Equal("instrumentDescription1", metric1.Description);
Assert.Equal("instrumentDescription2", metric2.Description);
List<MetricPoint> metric1MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric1.GetMetricPoints())
{
metric1MetricPoints.Add(mp);
}
Assert.Single(metric1MetricPoints);
var metricPoint1 = metric1MetricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
List<MetricPoint> metric2MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric2.GetMetricPoints())
{
metric2MetricPoints.Add(mp);
}
Assert.Single(metric2MetricPoints);
var metricPoint2 = metric2MetricPoints[0];
Assert.Equal(20, metricPoint2.GetSumLong());
}
[Fact]
public void DuplicateInstrumentRegistration_NoViews_DuplicateInstruments_DifferentUnit()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit1", "instrumentDescription");
var duplicateInstrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit2", "instrumentDescription");
instrument.Add(10);
duplicateInstrument.Add(20);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metric1 = exportedItems[0];
var metric2 = exportedItems[1];
Assert.Equal("instrumentUnit1", metric1.Unit);
Assert.Equal("instrumentUnit2", metric2.Unit);
List<MetricPoint> metric1MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric1.GetMetricPoints())
{
metric1MetricPoints.Add(mp);
}
Assert.Single(metric1MetricPoints);
var metricPoint1 = metric1MetricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
List<MetricPoint> metric2MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric2.GetMetricPoints())
{
metric2MetricPoints.Add(mp);
}
Assert.Single(metric2MetricPoints);
var metricPoint2 = metric2MetricPoints[0];
Assert.Equal(20, metricPoint2.GetSumLong());
}
[Fact]
public void DuplicateInstrumentRegistration_NoViews_DuplicateInstruments_DifferentDataType()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription");
var duplicateInstrument = meter.CreateCounter<double>("instrumentName", "instrumentUnit", "instrumentDescription");
instrument.Add(10);
duplicateInstrument.Add(20);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metric1 = exportedItems[0];
var metric2 = exportedItems[1];
List<MetricPoint> metric1MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric1.GetMetricPoints())
{
metric1MetricPoints.Add(mp);
}
Assert.Single(metric1MetricPoints);
var metricPoint1 = metric1MetricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
List<MetricPoint> metric2MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric2.GetMetricPoints())
{
metric2MetricPoints.Add(mp);
}
Assert.Single(metric2MetricPoints);
var metricPoint2 = metric2MetricPoints[0];
Assert.Equal(20D, metricPoint2.GetSumDouble());
}
[Fact]
public void DuplicateInstrumentRegistration_NoViews_DuplicateInstruments_DifferentInstrumentType()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription");
var duplicateInstrument = meter.CreateHistogram<long>("instrumentName", "instrumentUnit", "instrumentDescription");
instrument.Add(10);
duplicateInstrument.Record(20);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metric1 = exportedItems[0];
var metric2 = exportedItems[1];
List<MetricPoint> metric1MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric1.GetMetricPoints())
{
metric1MetricPoints.Add(mp);
}
Assert.Single(metric1MetricPoints);
var metricPoint1 = metric1MetricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
List<MetricPoint> metric2MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric2.GetMetricPoints())
{
metric2MetricPoints.Add(mp);
}
Assert.Single(metric2MetricPoints);
var metricPoint2 = metric2MetricPoints[0];
Assert.Equal(1, metricPoint2.GetHistogramCount());
Assert.Equal(20D, metricPoint2.GetHistogramSum());
}
[Fact]
public void DuplicateInstrumentRegistration_WithViews_DuplicateInstruments_DifferentDescription()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView("instrumentName", new MetricStreamConfiguration { Description = "newDescription1" })
.AddView("instrumentName", new MetricStreamConfiguration { Description = "newDescription2" })
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument = meter.CreateCounter<long>("instrumentName", "instrumentUnit", "instrumentDescription");
instrument.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
var metric1 = exportedItems[0];
var metric2 = exportedItems[1];
Assert.Equal("newDescription1", metric1.Description);
Assert.Equal("newDescription2", metric2.Description);
List<MetricPoint> metric1MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric1.GetMetricPoints())
{
metric1MetricPoints.Add(mp);
}
Assert.Single(metric1MetricPoints);
var metricPoint1 = metric1MetricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
List<MetricPoint> metric2MetricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric2.GetMetricPoints())
{
metric2MetricPoints.Add(mp);
}
Assert.Single(metric2MetricPoints);
var metricPoint2 = metric2MetricPoints[0];
Assert.Equal(10, metricPoint2.GetSumLong());
}
[Fact]
public void DuplicateInstrumentRegistration_WithViews_TwoInstruments_ThreeStreams()
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddView((instrument) =>
{
return new MetricStreamConfiguration { Name = "MetricStreamA", Description = "description" };
})
.AddView((instrument) =>
{
return instrument.Description == "description1"
? new MetricStreamConfiguration { Name = "MetricStreamB" }
: new MetricStreamConfiguration { Name = "MetricStreamC" };
})
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
var instrument1 = meter.CreateCounter<long>("name", "unit", "description1");
var instrument2 = meter.CreateCounter<long>("name", "unit", "description2");
instrument1.Add(10);
instrument2.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(3, exportedItems.Count);
var metricA = exportedItems[0];
var metricB = exportedItems[1];
var metricC = exportedItems[2];
Assert.Equal("MetricStreamA", metricA.Name);
Assert.Equal(20, GetAggregatedValue(metricA));
Assert.Equal("MetricStreamB", metricB.Name);
Assert.Equal(10, GetAggregatedValue(metricB));
Assert.Equal("MetricStreamC", metricC.Name);
Assert.Equal(10, GetAggregatedValue(metricC));
long GetAggregatedValue(Metric metric)
{
var metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
return metricPoints[0].GetSumLong();
}
}
[Fact]
public void DuplicateInstrumentNamesFromDifferentMetersWithSameNameDifferentVersion()
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter($"{Utils.GetCurrentMethodName()}", "1.0");
using var meter2 = new Meter($"{Utils.GetCurrentMethodName()}", "2.0");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddMeter(meter2.Name)
.AddInMemoryExporter(exportedItems);
using var meterProvider = meterProviderBuilder.Build();
// Expecting one metric stream.
var counterLong = meter1.CreateCounter<long>("name1");
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
// Expeecting another metric stream since the meter differs by version
var anotherCounterSameNameDiffMeter = meter2.CreateCounter<long>("name1");
anotherCounterSameNameDiffMeter.Add(10);
counterLong.Add(10);
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
}
[Theory]
[InlineData(AggregationTemporality.Cumulative, true)]
[InlineData(AggregationTemporality.Cumulative, false)]
[InlineData(AggregationTemporality.Delta, true)]
[InlineData(AggregationTemporality.Delta, false)]
public void DuplicateInstrumentNamesFromDifferentMetersAreAllowed(AggregationTemporality temporality, bool hasView)
{
var exportedItems = new List<Metric>();
using var meter1 = new Meter($"{Utils.GetCurrentMethodName()}.1.{temporality}");
using var meter2 = new Meter($"{Utils.GetCurrentMethodName()}.2.{temporality}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddMeter(meter2.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = temporality;
});
if (hasView)
{
meterProviderBuilder.AddView("name1", new MetricStreamConfiguration() { Description = "description" });
}
using var meterProvider = meterProviderBuilder.Build();
// Expecting one metric stream.
var counterLong = meter1.CreateCounter<long>("name1");
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
// The following will not be ignored
// as it is the same metric name but different meter.
var anotherCounterSameNameDiffMeter = meter2.CreateCounter<long>("name1");
anotherCounterSameNameDiffMeter.Add(10);
counterLong.Add(10);
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void MeterSourcesWildcardSupportMatchTest(bool hasView)
{
using var meter1 = new Meter("AbcCompany.XyzProduct.ComponentA");
using var meter2 = new Meter("abcCompany.xYzProduct.componentC"); // Wildcard match is case insensitive.
using var meter3 = new Meter("DefCompany.AbcProduct.ComponentC");
using var meter4 = new Meter("DefCompany.XyzProduct.ComponentC"); // Wildcard match supports matching multiple patterns.
using var meter5 = new Meter("GhiCompany.qweProduct.ComponentN");
using var meter6 = new Meter("SomeCompany.SomeProduct.SomeComponent");
var exportedItems = new List<Metric>();
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter("AbcCompany.XyzProduct.Component?")
.AddMeter("DefCompany.*.ComponentC")
.AddMeter("GhiCompany.qweProduct.ComponentN") // Mixing of non-wildcard meter name and wildcard meter name.
.AddInMemoryExporter(exportedItems);
if (hasView)
{
meterProviderBuilder.AddView("myGauge1", "newName");
}
using var meterProvider = meterProviderBuilder.Build();
var measurement = new Measurement<int>(100, new("name", "apple"), new("color", "red"));
meter1.CreateObservableGauge("myGauge1", () => measurement);
meter2.CreateObservableGauge("myGauge2", () => measurement);
meter3.CreateObservableGauge("myGauge3", () => measurement);
meter4.CreateObservableGauge("myGauge4", () => measurement);
meter5.CreateObservableGauge("myGauge5", () => measurement);
meter6.CreateObservableGauge("myGauge6", () => measurement);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.True(exportedItems.Count == 5); // "SomeCompany.SomeProduct.SomeComponent" will not be subscribed.
if (hasView)
{
Assert.Equal("newName", exportedItems[0].Name);
}
else
{
Assert.Equal("myGauge1", exportedItems[0].Name);
}
Assert.Equal("myGauge2", exportedItems[1].Name);
Assert.Equal("myGauge3", exportedItems[2].Name);
Assert.Equal("myGauge4", exportedItems[3].Name);
Assert.Equal("myGauge5", exportedItems[4].Name);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void MeterSourcesWildcardSupportNegativeTestNoMeterAdded(bool hasView)
{
using var meter1 = new Meter($"AbcCompany.XyzProduct.ComponentA.{hasView}");
using var meter2 = new Meter($"abcCompany.xYzProduct.componentC.{hasView}");
var exportedItems = new List<Metric>();
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddInMemoryExporter(exportedItems);
if (hasView)
{
meterProviderBuilder.AddView("gauge1", "renamed");
}
using var meterProvider = meterProviderBuilder.Build();
var measurement = new Measurement<int>(100, new("name", "apple"), new("color", "red"));
meter1.CreateObservableGauge("myGauge1", () => measurement);
meter2.CreateObservableGauge("myGauge2", () => measurement);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.True(exportedItems.Count == 0);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CounterAggregationTest(bool exportDelta)
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{exportDelta}");
var counterLong = meter.CreateCounter<long>("mycounter");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = exportDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
})
.Build();
counterLong.Add(10);
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
long sumReceived = GetLongSum(exportedItems);
Assert.Equal(20, sumReceived);
exportedItems.Clear();
counterLong.Add(10);
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(20, sumReceived);
}
else
{
Assert.Equal(40, sumReceived);
}
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(0, sumReceived);
}
else
{
Assert.Equal(40, sumReceived);
}
exportedItems.Clear();
counterLong.Add(40);
counterLong.Add(20);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(60, sumReceived);
}
else
{
Assert.Equal(100, sumReceived);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ObservableCounterAggregationTest(bool exportDelta)
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{exportDelta}");
int i = 1;
var counterLong = meter.CreateObservableCounter(
"observable-counter",
() =>
{
return new List<Measurement<long>>()
{
new Measurement<long>(i++ * 10),
};
});
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = exportDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
})
.Build();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
long sumReceived = GetLongSum(exportedItems);
Assert.Equal(10, sumReceived);
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(10, sumReceived);
}
else
{
Assert.Equal(20, sumReceived);
}
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(10, sumReceived);
}
else
{
Assert.Equal(30, sumReceived);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ObservableCounterWithTagsAggregationTest(bool exportDelta)
{
var exportedItems = new List<Metric>();
var tags1 = new List<KeyValuePair<string, object>>();
tags1.Add(new("statusCode", 200));
tags1.Add(new("verb", "get"));
var tags2 = new List<KeyValuePair<string, object>>();
tags2.Add(new("statusCode", 200));
tags2.Add(new("verb", "post"));
var tags3 = new List<KeyValuePair<string, object>>();
tags3.Add(new("statusCode", 500));
tags3.Add(new("verb", "get"));
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{exportDelta}");
var counterLong = meter.CreateObservableCounter(
"observable-counter",
() =>
{
return new List<Measurement<long>>()
{
new Measurement<long>(10, tags1),
new Measurement<long>(10, tags2),
new Measurement<long>(10, tags3),
};
});
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = exportDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
})
.Build();
// Export 1
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("observable-counter", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Equal(3, metricPoints.Count);
var metricPoint1 = metricPoints[0];
Assert.Equal(10, metricPoint1.GetSumLong());
ValidateMetricPointTags(tags1, metricPoint1.Tags);
var metricPoint2 = metricPoints[1];
Assert.Equal(10, metricPoint2.GetSumLong());
ValidateMetricPointTags(tags2, metricPoint2.Tags);
var metricPoint3 = metricPoints[2];
Assert.Equal(10, metricPoint3.GetSumLong());
ValidateMetricPointTags(tags3, metricPoint3.Tags);
// Export 2
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
metric = exportedItems[0];
Assert.Equal("observable-counter", metric.Name);
metricPoints.Clear();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Equal(3, metricPoints.Count);
metricPoint1 = metricPoints[0];
Assert.Equal(exportDelta ? 0 : 10, metricPoint1.GetSumLong());
ValidateMetricPointTags(tags1, metricPoint1.Tags);
metricPoint2 = metricPoints[1];
Assert.Equal(exportDelta ? 0 : 10, metricPoint2.GetSumLong());
ValidateMetricPointTags(tags2, metricPoint2.Tags);
metricPoint3 = metricPoints[2];
Assert.Equal(exportDelta ? 0 : 10, metricPoint3.GetSumLong());
ValidateMetricPointTags(tags3, metricPoint3.Tags);
}
[Theory(Skip = "Known issue.")]
[InlineData(true)]
[InlineData(false)]
public void ObservableCounterSpatialAggregationTest(bool exportDelta)
{
var exportedItems = new List<Metric>();
var tags1 = new List<KeyValuePair<string, object>>();
tags1.Add(new("statusCode", 200));
tags1.Add(new("verb", "get"));
var tags2 = new List<KeyValuePair<string, object>>();
tags2.Add(new("statusCode", 200));
tags2.Add(new("verb", "post"));
var tags3 = new List<KeyValuePair<string, object>>();
tags3.Add(new("statusCode", 500));
tags3.Add(new("verb", "get"));
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{exportDelta}");
var counterLong = meter.CreateObservableCounter(
"requestCount",
() =>
{
return new List<Measurement<long>>()
{
new Measurement<long>(10, tags1),
new Measurement<long>(10, tags2),
new Measurement<long>(10, tags3),
};
});
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = exportDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
})
.AddView("requestCount", new MetricStreamConfiguration() { TagKeys = new string[] { } })
.Build();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal("requestCount", metric.Name);
List<MetricPoint> metricPoints = new List<MetricPoint>();
foreach (ref readonly var mp in metric.GetMetricPoints())
{
metricPoints.Add(mp);
}
Assert.Single(metricPoints);
var emptyTags = new List<KeyValuePair<string, object>>();
var metricPoint1 = metricPoints[0];
ValidateMetricPointTags(emptyTags, metricPoint1.Tags);
// This will fail, as SDK is not "spatially" aggregating the
// requestCount
Assert.Equal(30, metricPoint1.GetSumLong());
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void DimensionsAreOrderInsensitiveWithSortedKeysFirst(bool exportDelta)
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{exportDelta}");
var counterLong = meter.CreateCounter<long>("Counter");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = exportDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
})
.Build();
// Emit the first metric with the sorted order of tag keys
counterLong.Add(5, new("Key1", "Value1"), new("Key2", "Value2"), new("Key3", "Value3"));
counterLong.Add(10, new("Key1", "Value1"), new("Key3", "Value3"), new("Key2", "Value2"));
counterLong.Add(10, new("Key2", "Value20"), new("Key1", "Value10"), new("Key3", "Value30"));
// Emit a metric with different set of keys but the same set of values as one of the previous metric points
counterLong.Add(25, new("Key4", "Value1"), new("Key5", "Value3"), new("Key6", "Value2"));
counterLong.Add(25, new("Key4", "Value1"), new("Key6", "Value3"), new("Key5", "Value2"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
List<KeyValuePair<string, object>> expectedTagsForFirstMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key1", "Value1"),
new("Key2", "Value2"),
new("Key3", "Value3"),
};
List<KeyValuePair<string, object>> expectedTagsForSecondMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key1", "Value10"),
new("Key2", "Value20"),
new("Key3", "Value30"),
};
List<KeyValuePair<string, object>> expectedTagsForThirdMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key4", "Value1"),
new("Key5", "Value3"),
new("Key6", "Value2"),
};
List<KeyValuePair<string, object>> expectedTagsForFourthMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key4", "Value1"),
new("Key5", "Value2"),
new("Key6", "Value3"),
};
Assert.Equal(4, GetNumberOfMetricPoints(exportedItems));
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFirstMetricPoint, 1);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForSecondMetricPoint, 2);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForThirdMetricPoint, 3);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFourthMetricPoint, 4);
long sumReceived = GetLongSum(exportedItems);
Assert.Equal(75, sumReceived);
exportedItems.Clear();
counterLong.Add(5, new("Key2", "Value2"), new("Key1", "Value1"), new("Key3", "Value3"));
counterLong.Add(5, new("Key2", "Value2"), new("Key1", "Value1"), new("Key3", "Value3"));
counterLong.Add(10, new("Key2", "Value2"), new("Key3", "Value3"), new("Key1", "Value1"));
counterLong.Add(10, new("Key2", "Value20"), new("Key3", "Value30"), new("Key1", "Value10"));
counterLong.Add(20, new("Key4", "Value1"), new("Key6", "Value2"), new("Key5", "Value3"));
counterLong.Add(20, new("Key4", "Value1"), new("Key5", "Value2"), new("Key6", "Value3"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(4, GetNumberOfMetricPoints(exportedItems));
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFirstMetricPoint, 1);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForSecondMetricPoint, 2);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForThirdMetricPoint, 3);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFourthMetricPoint, 4);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(70, sumReceived);
}
else
{
Assert.Equal(145, sumReceived);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void DimensionsAreOrderInsensitiveWithUnsortedKeysFirst(bool exportDelta)
{
var exportedItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{exportDelta}");
var counterLong = meter.CreateCounter<long>("Counter");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = exportDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
})
.Build();
// Emit the first metric with the unsorted order of tag keys
counterLong.Add(5, new("Key1", "Value1"), new("Key3", "Value3"), new("Key2", "Value2"));
counterLong.Add(10, new("Key1", "Value1"), new("Key2", "Value2"), new("Key3", "Value3"));
counterLong.Add(10, new("Key2", "Value20"), new("Key1", "Value10"), new("Key3", "Value30"));
// Emit a metric with different set of keys but the same set of values as one of the previous metric points
counterLong.Add(25, new("Key4", "Value1"), new("Key5", "Value3"), new("Key6", "Value2"));
counterLong.Add(25, new("Key4", "Value1"), new("Key6", "Value3"), new("Key5", "Value2"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
List<KeyValuePair<string, object>> expectedTagsForFirstMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key1", "Value1"),
new("Key2", "Value2"),
new("Key3", "Value3"),
};
List<KeyValuePair<string, object>> expectedTagsForSecondMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key1", "Value10"),
new("Key2", "Value20"),
new("Key3", "Value30"),
};
List<KeyValuePair<string, object>> expectedTagsForThirdMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key4", "Value1"),
new("Key5", "Value3"),
new("Key6", "Value2"),
};
List<KeyValuePair<string, object>> expectedTagsForFourthMetricPoint = new List<KeyValuePair<string, object>>()
{
new("Key4", "Value1"),
new("Key5", "Value2"),
new("Key6", "Value3"),
};
Assert.Equal(4, GetNumberOfMetricPoints(exportedItems));
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFirstMetricPoint, 1);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForSecondMetricPoint, 2);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForThirdMetricPoint, 3);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFourthMetricPoint, 4);
long sumReceived = GetLongSum(exportedItems);
Assert.Equal(75, sumReceived);
exportedItems.Clear();
counterLong.Add(5, new("Key2", "Value2"), new("Key1", "Value1"), new("Key3", "Value3"));
counterLong.Add(5, new("Key2", "Value2"), new("Key1", "Value1"), new("Key3", "Value3"));
counterLong.Add(10, new("Key2", "Value2"), new("Key3", "Value3"), new("Key1", "Value1"));
counterLong.Add(10, new("Key2", "Value20"), new("Key3", "Value30"), new("Key1", "Value10"));
counterLong.Add(20, new("Key4", "Value1"), new("Key6", "Value2"), new("Key5", "Value3"));
counterLong.Add(20, new("Key4", "Value1"), new("Key5", "Value2"), new("Key6", "Value3"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(4, GetNumberOfMetricPoints(exportedItems));
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFirstMetricPoint, 1);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForSecondMetricPoint, 2);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForThirdMetricPoint, 3);
CheckTagsForNthMetricPoint(exportedItems, expectedTagsForFourthMetricPoint, 4);
sumReceived = GetLongSum(exportedItems);
if (exportDelta)
{
Assert.Equal(70, sumReceived);
}
else
{
Assert.Equal(145, sumReceived);
}
}
[Theory]
[InlineData(AggregationTemporality.Cumulative)]
[InlineData(AggregationTemporality.Delta)]
public void TestInstrumentDisposal(AggregationTemporality temporality)
{
var exportedItems = new List<Metric>();
var meter1 = new Meter($"{Utils.GetCurrentMethodName()}.{temporality}.1");
var meter2 = new Meter($"{Utils.GetCurrentMethodName()}.{temporality}.2");
var counter1 = meter1.CreateCounter<long>("counterFromMeter1");
var counter2 = meter2.CreateCounter<long>("counterFromMeter2");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter1.Name)
.AddMeter(meter2.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = temporality;
})
.Build();
counter1.Add(10, new KeyValuePair<string, object>("key", "value"));
counter2.Add(10, new KeyValuePair<string, object>("key", "value"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
exportedItems.Clear();
counter1.Add(10, new KeyValuePair<string, object>("key", "value"));
counter2.Add(10, new KeyValuePair<string, object>("key", "value"));
meter1.Dispose();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(2, exportedItems.Count);
exportedItems.Clear();
counter1.Add(10, new KeyValuePair<string, object>("key", "value"));
counter2.Add(10, new KeyValuePair<string, object>("key", "value"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
exportedItems.Clear();
counter1.Add(10, new KeyValuePair<string, object>("key", "value"));
counter2.Add(10, new KeyValuePair<string, object>("key", "value"));
meter2.Dispose();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Single(exportedItems);
exportedItems.Clear();
counter1.Add(10, new KeyValuePair<string, object>("key", "value"));
counter2.Add(10, new KeyValuePair<string, object>("key", "value"));
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Empty(exportedItems);
}
[Theory]
[InlineData(AggregationTemporality.Cumulative)]
[InlineData(AggregationTemporality.Delta)]
public void TestMetricPointCap(AggregationTemporality temporality)
{
var exportedItems = new List<Metric>();
int MetricPointCount()
{
var count = 0;
foreach (var metric in exportedItems)
{
foreach (ref readonly var metricPoint in metric.GetMetricPoints())
{
count++;
}
}
return count;
}
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{temporality}");
var counterLong = meter.CreateCounter<long>("mycounterCapTest");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems, metricReaderOptions =>
{
metricReaderOptions.Temporality = temporality;
})
.Build();
// Make one Add with no tags.
// as currently we reserve 0th index
// for no tag point!
// This may be changed later.
counterLong.Add(10);
for (int i = 0; i < MeterProviderBuilderBase.MaxMetricPointsPerMetricDefault + 1; i++)
{
counterLong.Add(10, new KeyValuePair<string, object>("key", "value" + i));
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(MeterProviderBuilderBase.MaxMetricPointsPerMetricDefault, MetricPointCount());
exportedItems.Clear();
counterLong.Add(10);
for (int i = 0; i < MeterProviderBuilderBase.MaxMetricPointsPerMetricDefault + 1; i++)
{
counterLong.Add(10, new KeyValuePair<string, object>("key", "value" + i));
}
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(MeterProviderBuilderBase.MaxMetricPointsPerMetricDefault, MetricPointCount());
counterLong.Add(10);
for (int i = 0; i < MeterProviderBuilderBase.MaxMetricPointsPerMetricDefault + 1; i++)
{
counterLong.Add(10, new KeyValuePair<string, object>("key", "value" + i));
}
// These updates would be dropped.
counterLong.Add(10, new KeyValuePair<string, object>("key", "valueA"));
counterLong.Add(10, new KeyValuePair<string, object>("key", "valueB"));
counterLong.Add(10, new KeyValuePair<string, object>("key", "valueC"));
exportedItems.Clear();
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
Assert.Equal(MeterProviderBuilderBase.MaxMetricPointsPerMetricDefault, MetricPointCount());
}
[Fact]
public void MultithreadedLongCounterTest()
{
this.MultithreadedCounterTest(deltaLongValueUpdatedByEachCall);
}
[Fact]
public void MultithreadedDoubleCounterTest()
{
this.MultithreadedCounterTest(deltaDoubleValueUpdatedByEachCall);
}
[Fact]
public void MultithreadedLongHistogramTest()
{
var expected = new long[11];
for (var i = 0; i < expected.Length; i++)
{
expected[i] = numberOfThreads * numberOfMetricUpdateByEachThread;
}
// Metric.DefaultHistogramBounds: 0, 5, 10, 25, 50, 75, 100, 250, 500, 1000
var values = new long[] { -1, 1, 6, 20, 40, 60, 80, 200, 300, 600, 1001 };
this.MultithreadedHistogramTest(expected, values);
}
[Fact]
public void MultithreadedDoubleHistogramTest()
{
var expected = new long[11];
for (var i = 0; i < expected.Length; i++)
{
expected[i] = numberOfThreads * numberOfMetricUpdateByEachThread;
}
// Metric.DefaultHistogramBounds: 0, 5, 10, 25, 50, 75, 100, 250, 500, 1000
var values = new double[] { -1.0, 1.0, 6.0, 20.0, 40.0, 60.0, 80.0, 200.0, 300.0, 600.0, 1001.0 };
this.MultithreadedHistogramTest(expected, values);
}
[Theory]
[MemberData(nameof(MetricTestData.InvalidInstrumentNames), MemberType = typeof(MetricTestData))]
public void InstrumentWithInvalidNameIsIgnoredTest(string instrumentName)
{
var exportedItems = new List<Metric>();
using var meter = new Meter("InstrumentWithInvalidNameIsIgnoredTest");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems)
.Build();
var counterLong = meter.CreateCounter<long>(instrumentName);
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// instrument should have been ignored
// as its name does not comply with the specification
Assert.Empty(exportedItems);
}
[Theory]
[MemberData(nameof(MetricTestData.ValidInstrumentNames), MemberType = typeof(MetricTestData))]
public void InstrumentWithValidNameIsExportedTest(string name)
{
var exportedItems = new List<Metric>();
using var meter = new Meter("InstrumentValidNameIsExportedTest");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems)
.Build();
var counterLong = meter.CreateCounter<long>(name);
counterLong.Add(10);
meterProvider.ForceFlush(MaxTimeToAllowForFlush);
// Expecting one metric stream.
Assert.Single(exportedItems);
var metric = exportedItems[0];
Assert.Equal(name, metric.Name);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetupSdkProviderWithNoReader(bool hasViews)
{
// This test ensures that MeterProviderSdk can be set up without any reader
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{hasViews}");
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name);
if (hasViews)
{
meterProviderBuilder.AddView("counter", "renamedCounter");
}
using var meterProvider = meterProviderBuilder.Build();
var counter = meter.CreateCounter<long>("counter");
counter.Add(10, new KeyValuePair<string, object>("key", "value"));
}
private static void ValidateMetricPointTags(List<KeyValuePair<string, object>> expectedTags, ReadOnlyTagCollection actualTags)
{
int tagIndex = 0;
foreach (var tag in actualTags)
{
Assert.Equal(expectedTags[tagIndex].Key, tag.Key);
Assert.Equal(expectedTags[tagIndex].Value, tag.Value);
tagIndex++;
}
Assert.Equal(expectedTags.Count, tagIndex);
}
private static long GetLongSum(List<Metric> metrics)
{
long sum = 0;
foreach (var metric in metrics)
{
foreach (ref readonly var metricPoint in metric.GetMetricPoints())
{
if (metric.MetricType.IsSum())
{
sum += metricPoint.GetSumLong();
}
else
{
sum += metricPoint.GetGaugeLastValueLong();
}
}
}
return sum;
}
private static double GetDoubleSum(List<Metric> metrics)
{
double sum = 0;
foreach (var metric in metrics)
{
foreach (ref readonly var metricPoint in metric.GetMetricPoints())
{
if (metric.MetricType.IsSum())
{
sum += metricPoint.GetSumDouble();
}
else
{
sum += metricPoint.GetGaugeLastValueDouble();
}
}
}
return sum;
}
private static int GetNumberOfMetricPoints(List<Metric> metrics)
{
int count = 0;
foreach (var metric in metrics)
{
foreach (ref readonly var metricPoint in metric.GetMetricPoints())
{
count++;
}
}
return count;
}
// Provide tags input sorted by Key
private static void CheckTagsForNthMetricPoint(List<Metric> metrics, List<KeyValuePair<string, object>> tags, int n)
{
var metric = metrics[0];
var metricPointEnumerator = metric.GetMetricPoints().GetEnumerator();
for (int i = 0; i < n; i++)
{
Assert.True(metricPointEnumerator.MoveNext());
}
int index = 0;
var metricPoint = metricPointEnumerator.Current;
foreach (var tag in metricPoint.Tags)
{
Assert.Equal(tags[index].Key, tag.Key);
Assert.Equal(tags[index].Value, tag.Value);
index++;
}
}
private static void CounterUpdateThread<T>(object obj)
where T : struct, IComparable
{
if (obj is not UpdateThreadArguments<T> arguments)
{
throw new Exception("Invalid args");
}
var mre = arguments.MreToBlockUpdateThread;
var mreToEnsureAllThreadsStart = arguments.MreToEnsureAllThreadsStart;
var counter = arguments.Instrument as Counter<T>;
var valueToUpdate = arguments.ValuesToRecord[0];
if (Interlocked.Increment(ref arguments.ThreadsStartedCount) == numberOfThreads)
{
mreToEnsureAllThreadsStart.Set();
}
// Wait until signalled to start calling update on aggregator
mre.WaitOne();
for (int i = 0; i < numberOfMetricUpdateByEachThread; i++)
{
counter.Add(valueToUpdate, new KeyValuePair<string, object>("verb", "GET"));
}
}
private static void HistogramUpdateThread<T>(object obj)
where T : struct, IComparable
{
if (obj is not UpdateThreadArguments<T> arguments)
{
throw new Exception("Invalid args");
}
var mre = arguments.MreToBlockUpdateThread;
var mreToEnsureAllThreadsStart = arguments.MreToEnsureAllThreadsStart;
var histogram = arguments.Instrument as Histogram<T>;
if (Interlocked.Increment(ref arguments.ThreadsStartedCount) == numberOfThreads)
{
mreToEnsureAllThreadsStart.Set();
}
// Wait until signalled to start calling update on aggregator
mre.WaitOne();
for (int i = 0; i < numberOfMetricUpdateByEachThread; i++)
{
for (int j = 0; j < arguments.ValuesToRecord.Length; j++)
{
histogram.Record(arguments.ValuesToRecord[j]);
}
}
}
private void MultithreadedCounterTest<T>(T deltaValueUpdatedByEachCall)
where T : struct, IComparable
{
var metricItems = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{typeof(T).Name}.{deltaValueUpdatedByEachCall}");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(metricItems)
.Build();
var argToThread = new UpdateThreadArguments<T>
{
ValuesToRecord = new T[] { deltaValueUpdatedByEachCall },
Instrument = meter.CreateCounter<T>("counter"),
MreToBlockUpdateThread = new ManualResetEvent(false),
MreToEnsureAllThreadsStart = new ManualResetEvent(false),
};
Thread[] t = new Thread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
{
t[i] = new Thread(CounterUpdateThread<T>);
t[i].Start(argToThread);
}
argToThread.MreToEnsureAllThreadsStart.WaitOne();
Stopwatch sw = Stopwatch.StartNew();
argToThread.MreToBlockUpdateThread.Set();
for (int i = 0; i < numberOfThreads; i++)
{
t[i].Join();
}
this.output.WriteLine($"Took {sw.ElapsedMilliseconds} msecs. Total threads: {numberOfThreads}, each thread doing {numberOfMetricUpdateByEachThread} recordings.");
meterProvider.ForceFlush();
if (typeof(T) == typeof(long))
{
var sumReceived = GetLongSum(metricItems);
var expectedSum = deltaLongValueUpdatedByEachCall * numberOfMetricUpdateByEachThread * numberOfThreads;
Assert.Equal(expectedSum, sumReceived);
}
else if (typeof(T) == typeof(double))
{
var sumReceived = GetDoubleSum(metricItems);
var expectedSum = deltaDoubleValueUpdatedByEachCall * numberOfMetricUpdateByEachThread * numberOfThreads;
Assert.Equal(expectedSum, sumReceived, 2);
}
}
private void MultithreadedHistogramTest<T>(long[] expected, T[] values)
where T : struct, IComparable
{
var bucketCounts = new long[11];
var metricReader = new BaseExportingMetricReader(new TestExporter<Metric>(batch =>
{
foreach (var metric in batch)
{
foreach (var metricPoint in metric.GetMetricPoints())
{
bucketCounts = metricPoint.GetHistogramBuckets().RunningBucketCounts;
}
}
}));
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{typeof(T).Name}");
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddReader(metricReader)
.Build();
var argsToThread = new UpdateThreadArguments<T>
{
Instrument = meter.CreateHistogram<T>("histogram"),
MreToBlockUpdateThread = new ManualResetEvent(false),
MreToEnsureAllThreadsStart = new ManualResetEvent(false),
ValuesToRecord = values,
};
Thread[] t = new Thread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
{
t[i] = new Thread(HistogramUpdateThread<T>);
t[i].Start(argsToThread);
}
argsToThread.MreToEnsureAllThreadsStart.WaitOne();
Stopwatch sw = Stopwatch.StartNew();
argsToThread.MreToBlockUpdateThread.Set();
for (int i = 0; i < numberOfThreads; i++)
{
t[i].Join();
}
this.output.WriteLine($"Took {sw.ElapsedMilliseconds} msecs. Total threads: {numberOfThreads}, each thread doing {numberOfMetricUpdateByEachThread * values.Length} recordings.");
metricReader.Collect();
Assert.Equal(expected, bucketCounts);
}
private class UpdateThreadArguments<T>
where T : struct, IComparable
{
public ManualResetEvent MreToBlockUpdateThread;
public ManualResetEvent MreToEnsureAllThreadsStart;
public int ThreadsStartedCount;
public Instrument<T> Instrument;
public T[] ValuesToRecord;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Xunit;
namespace Microsoft.Build.UnitTests.AxTlbImp_Tests
{
sealed public class AxImp_Tests
{
/// <summary>
/// Tests that the assembly being imported is passed to the command line
/// </summary>
[Fact]
public void ActiveXControlName()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = "AxInterop.Foo.dll";
Assert.Null(t.ActiveXControlName); // "ActiveXControlName should be null by default"
t.ActiveXControlName = testParameterValue;
Assert.Equal(testParameterValue, t.ActiveXControlName); // "New ActiveXControlName value should be set"
CommandLine.ValidateHasParameter(t, testParameterValue, false /* no response file */);
}
/// <summary>
/// Tests that the assembly being imported is passed to the command line
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ActiveXControlNameWithSpaces()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = @"c:\Program Files\AxInterop.Foo.dll";
Assert.Null(t.ActiveXControlName); // "ActiveXControlName should be null by default"
t.ActiveXControlName = testParameterValue;
Assert.Equal(testParameterValue, t.ActiveXControlName); // "New ActiveXControlName value should be set"
CommandLine.ValidateHasParameter(t, testParameterValue, false /* no response file */);
}
/// <summary>
/// Tests the /source switch
/// </summary>
[Fact]
public void GenerateSource()
{
var t = new ResolveComReference.AxImp();
Assert.False(t.GenerateSource); // "GenerateSource should be false by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/source",
false /* no response file */);
t.GenerateSource = true;
Assert.True(t.GenerateSource); // "GenerateSource should be true"
CommandLine.ValidateHasParameter(
t,
@"/source",
false /* no response file */);
}
/// <summary>
/// Tests the /nologo switch
/// </summary>
[Fact]
public void NoLogo()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "The /nologo switch is not available on Mono"
}
var t = new ResolveComReference.AxImp();
Assert.False(t.NoLogo); // "NoLogo should be false by default"
CommandLine.ValidateNoParameterStartsWith(t, @"/nologo", false /* no response file */);
t.NoLogo = true;
Assert.True(t.NoLogo); // "NoLogo should be true"
CommandLine.ValidateHasParameter(t, @"/nologo", false /* no response file */);
}
/// <summary>
/// Tests the /out: switch
/// </summary>
[Fact]
public void OutputAssembly()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = "AxInterop.Foo.dll";
Assert.Null(t.OutputAssembly); // "OutputAssembly should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/out:",
false /* no response file */);
t.OutputAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.OutputAssembly); // "New OutputAssembly value should be set"
CommandLine.ValidateHasParameter(
t,
@"/out:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /out: switch, with a space in the output file
/// </summary>
[Fact]
public void OutputAssemblyWithSpaces()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = @"c:\Program Files\AxInterop.Foo.dll";
Assert.Null(t.OutputAssembly); // "OutputAssembly should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/out:",
false /* no response file */);
t.OutputAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.OutputAssembly); // "New OutputAssembly value should be set"
CommandLine.ValidateHasParameter(
t,
@"/out:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /rcw: switch
/// </summary>
[Fact]
public void RuntimeCallableWrapper()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = "Interop.Foo.dll";
Assert.Null(t.RuntimeCallableWrapperAssembly); // "RuntimeCallableWrapper should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/rcw:",
false /* no response file */);
t.RuntimeCallableWrapperAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.RuntimeCallableWrapperAssembly); // "New RuntimeCallableWrapper value should be set"
CommandLine.ValidateHasParameter(
t,
@"/rcw:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /rcw: switch with a space in the filename
/// </summary>
[Fact]
public void RuntimeCallableWrapperWithSpaces()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = @"C:\Program Files\Microsoft Visual Studio 10.0\Interop.Foo.dll";
Assert.Null(t.RuntimeCallableWrapperAssembly); // "RuntimeCallableWrapper should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/rcw:",
false /* no response file */);
t.RuntimeCallableWrapperAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.RuntimeCallableWrapperAssembly); // "New RuntimeCallableWrapper value should be set"
CommandLine.ValidateHasParameter(
t,
@"/rcw:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /silent switch
/// </summary>
[Fact]
public void Silent()
{
var t = new ResolveComReference.AxImp();
Assert.False(t.Silent); // "Silent should be false by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/silent",
false /* no response file */);
t.Silent = true;
Assert.True(t.Silent); // "Silent should be true"
CommandLine.ValidateHasParameter(
t,
@"/silent",
false /* no response file */);
}
/// <summary>
/// Tests the /verbose switch
/// </summary>
[Fact]
public void Verbose()
{
var t = new ResolveComReference.AxImp();
Assert.False(t.Verbose); // "Verbose should be false by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/verbose",
false /* no response file */);
t.Verbose = true;
Assert.True(t.Verbose); // "Verbose should be true"
CommandLine.ValidateHasParameter(
t,
@"/verbose",
false /* no response file */);
}
/// <summary>
/// Tests that task does the right thing (fails) when no .ocx file is passed to it
/// </summary>
[Fact]
public void TaskFailsWithNoInputs()
{
var t = new ResolveComReference.AxImp();
Utilities.ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "AxImp.NoInputFileSpecified");
}
}
}
| |
namespace Gabtastik
{
partial class Form1
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripSeparator();
this.facebookcomToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.googlecomToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.meebocomToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.panel1 = new System.Windows.Forms.Panel();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pageSetupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.gabToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.facebookcomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.googlecomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.meebocomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.logoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.releaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.softwareLicenseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.creditsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.contactCustomerSupportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripSeparator();
this.preferencesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripSeparator();
this.checkForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutGabtastikToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.extendedWebBrowser1 = new ExtendedWebBrowser2.ExtendedWebBrowser();
this.contextMenuStrip1.SuspendLayout();
this.panel1.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// notifyIcon1
//
this.notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
this.notifyIcon1.Visible = true;
this.notifyIcon1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon1_MouseDoubleClick);
//
// contextMenuStrip1
//
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.toolStripMenuItem8,
this.facebookcomToolStripMenuItem1,
this.googlecomToolStripMenuItem1,
this.meebocomToolStripMenuItem1,
this.toolStripMenuItem7,
this.exitToolStripMenuItem1});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(162, 126);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(161, 22);
this.openToolStripMenuItem.Text = "Open";
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
this.toolStripMenuItem8.Size = new System.Drawing.Size(158, 6);
//
// facebookcomToolStripMenuItem1
//
this.facebookcomToolStripMenuItem1.Name = "facebookcomToolStripMenuItem1";
this.facebookcomToolStripMenuItem1.Size = new System.Drawing.Size(161, 22);
this.facebookcomToolStripMenuItem1.Text = "@facebook.com";
//
// googlecomToolStripMenuItem1
//
this.googlecomToolStripMenuItem1.Name = "googlecomToolStripMenuItem1";
this.googlecomToolStripMenuItem1.Size = new System.Drawing.Size(161, 22);
this.googlecomToolStripMenuItem1.Text = "@google.com";
//
// meebocomToolStripMenuItem1
//
this.meebocomToolStripMenuItem1.Name = "meebocomToolStripMenuItem1";
this.meebocomToolStripMenuItem1.Size = new System.Drawing.Size(161, 22);
this.meebocomToolStripMenuItem1.Text = "@meebo.com";
this.meebocomToolStripMenuItem1.Visible = false;
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(158, 6);
//
// exitToolStripMenuItem1
//
this.exitToolStripMenuItem1.Name = "exitToolStripMenuItem1";
this.exitToolStripMenuItem1.Size = new System.Drawing.Size(161, 22);
this.exitToolStripMenuItem1.Text = "Exit";
this.exitToolStripMenuItem1.Click += new System.EventHandler(this.exitToolStripMenuItem1_Click);
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.BackColor = System.Drawing.Color.Gainsboro;
this.panel1.BackgroundImage = global::Gabtastik.Properties.Resources.Bottom;
this.panel1.Controls.Add(this.progressBar1);
this.panel1.Controls.Add(this.button1);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(0, 359);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(480, 25);
this.panel1.TabIndex = 2;
this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
//
// progressBar1
//
this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.progressBar1.Location = new System.Drawing.Point(457, 3);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(20, 20);
this.progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
this.progressBar1.TabIndex = 2;
this.progressBar1.Visible = false;
this.progressBar1.Click += new System.EventHandler(this.progressBar1_Click);
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.BackColor = System.Drawing.Color.Transparent;
this.button1.FlatAppearance.BorderSize = 0;
this.button1.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image")));
this.button1.Location = new System.Drawing.Point(457, 3);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(18, 18);
this.button1.TabIndex = 0;
this.button1.TabStop = false;
this.button1.UseVisualStyleBackColor = false;
this.button1.Visible = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.ForeColor = System.Drawing.Color.White;
this.label1.Location = new System.Drawing.Point(3, 7);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(421, 15);
this.label1.TabIndex = 0;
this.label1.Tag = "";
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// menuStrip1
//
this.menuStrip1.BackColor = System.Drawing.Color.Gainsboro;
this.menuStrip1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("menuStrip1.BackgroundImage")));
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.gabToolStripMenuItem,
this.editToolStripMenuItem,
this.helpToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(480, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pageSetupToolStripMenuItem,
this.printToolStripMenuItem,
this.toolStripMenuItem3,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText;
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// pageSetupToolStripMenuItem
//
this.pageSetupToolStripMenuItem.Name = "pageSetupToolStripMenuItem";
this.pageSetupToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.pageSetupToolStripMenuItem.Text = "Page Setup...";
this.pageSetupToolStripMenuItem.Visible = false;
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.printToolStripMenuItem.Text = "Print...";
this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(146, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// gabToolStripMenuItem
//
this.gabToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.facebookcomToolStripMenuItem,
this.googlecomToolStripMenuItem,
this.meebocomToolStripMenuItem,
this.toolStripMenuItem9,
this.logoutToolStripMenuItem});
this.gabToolStripMenuItem.Name = "gabToolStripMenuItem";
this.gabToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.gabToolStripMenuItem.Text = "Gab";
//
// facebookcomToolStripMenuItem
//
this.facebookcomToolStripMenuItem.Name = "facebookcomToolStripMenuItem";
this.facebookcomToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D1)));
this.facebookcomToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.facebookcomToolStripMenuItem.Text = "@facebook.com";
//
// googlecomToolStripMenuItem
//
this.googlecomToolStripMenuItem.Name = "googlecomToolStripMenuItem";
this.googlecomToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D2)));
this.googlecomToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.googlecomToolStripMenuItem.Text = "@google.com";
//
// meebocomToolStripMenuItem
//
this.meebocomToolStripMenuItem.Name = "meebocomToolStripMenuItem";
this.meebocomToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D3)));
this.meebocomToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.meebocomToolStripMenuItem.Text = "@meebo.com";
this.meebocomToolStripMenuItem.Visible = false;
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(198, 6);
//
// logoutToolStripMenuItem
//
this.logoutToolStripMenuItem.Name = "logoutToolStripMenuItem";
this.logoutToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.logoutToolStripMenuItem.Text = "Logout";
this.logoutToolStripMenuItem.Click += new System.EventHandler(this.logoutToolStripMenuItem_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.toolStripMenuItem1,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.deleteToolStripMenuItem,
this.toolStripMenuItem2,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "Edit";
this.editToolStripMenuItem.Visible = false;
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.undoToolStripMenuItem.Text = "Undo";
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(161, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.cutToolStripMenuItem.Text = "Cut";
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.copyToolStripMenuItem.Text = "Copy";
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.pasteToolStripMenuItem.Text = "Paste";
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
this.deleteToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.Delete;
this.deleteToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.deleteToolStripMenuItem.Text = "Delete";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(161, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.selectAllToolStripMenuItem.Text = "Select All";
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.releaseNotesToolStripMenuItem,
this.softwareLicenseToolStripMenuItem,
this.creditsToolStripMenuItem,
this.toolStripMenuItem4,
this.contactCustomerSupportToolStripMenuItem,
this.toolStripMenuItem5,
this.preferencesToolStripMenuItem,
this.toolStripMenuItem6,
this.checkForUpdatesToolStripMenuItem,
this.aboutGabtastikToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.helpToolStripMenuItem.Text = "Help";
//
// releaseNotesToolStripMenuItem
//
this.releaseNotesToolStripMenuItem.Name = "releaseNotesToolStripMenuItem";
this.releaseNotesToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.releaseNotesToolStripMenuItem.Text = "Release Notes...";
this.releaseNotesToolStripMenuItem.Click += new System.EventHandler(this.releaseNotesToolStripMenuItem_Click);
//
// softwareLicenseToolStripMenuItem
//
this.softwareLicenseToolStripMenuItem.Name = "softwareLicenseToolStripMenuItem";
this.softwareLicenseToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.softwareLicenseToolStripMenuItem.Text = "Software License...";
this.softwareLicenseToolStripMenuItem.Click += new System.EventHandler(this.softwareLicenseToolStripMenuItem_Click);
//
// creditsToolStripMenuItem
//
this.creditsToolStripMenuItem.Name = "creditsToolStripMenuItem";
this.creditsToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.creditsToolStripMenuItem.Text = "Credits...";
this.creditsToolStripMenuItem.Click += new System.EventHandler(this.creditsToolStripMenuItem_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(222, 6);
//
// contactCustomerSupportToolStripMenuItem
//
this.contactCustomerSupportToolStripMenuItem.Name = "contactCustomerSupportToolStripMenuItem";
this.contactCustomerSupportToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.contactCustomerSupportToolStripMenuItem.Text = "Contact Customer Support...";
this.contactCustomerSupportToolStripMenuItem.Click += new System.EventHandler(this.contactCustomerSupportToolStripMenuItem_Click);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(222, 6);
//
// preferencesToolStripMenuItem
//
this.preferencesToolStripMenuItem.Name = "preferencesToolStripMenuItem";
this.preferencesToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.preferencesToolStripMenuItem.Text = "Options...";
this.preferencesToolStripMenuItem.Click += new System.EventHandler(this.preferencesToolStripMenuItem_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(222, 6);
//
// checkForUpdatesToolStripMenuItem
//
this.checkForUpdatesToolStripMenuItem.Name = "checkForUpdatesToolStripMenuItem";
this.checkForUpdatesToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.checkForUpdatesToolStripMenuItem.Text = "Check for Updates...";
this.checkForUpdatesToolStripMenuItem.Click += new System.EventHandler(this.checkForUpdatesToolStripMenuItem_Click);
//
// aboutGabtastikToolStripMenuItem
//
this.aboutGabtastikToolStripMenuItem.Name = "aboutGabtastikToolStripMenuItem";
this.aboutGabtastikToolStripMenuItem.Size = new System.Drawing.Size(225, 22);
this.aboutGabtastikToolStripMenuItem.Text = "About Gabtastik";
this.aboutGabtastikToolStripMenuItem.Click += new System.EventHandler(this.aboutGabtastikToolStripMenuItem_Click);
//
// extendedWebBrowser1
//
this.extendedWebBrowser1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.extendedWebBrowser1.IsWebBrowserContextMenuEnabled = false;
this.extendedWebBrowser1.Location = new System.Drawing.Point(0, 24);
this.extendedWebBrowser1.Margin = new System.Windows.Forms.Padding(0);
this.extendedWebBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
this.extendedWebBrowser1.Name = "extendedWebBrowser1";
this.extendedWebBrowser1.ScriptErrorsSuppressed = true;
this.extendedWebBrowser1.Size = new System.Drawing.Size(480, 335);
this.extendedWebBrowser1.TabIndex = 1;
this.extendedWebBrowser1.Url = new System.Uri("", System.UriKind.Relative);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(480, 384);
this.Controls.Add(this.panel1);
this.Controls.Add(this.extendedWebBrowser1);
this.Controls.Add(this.menuStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.MaximumSize = new System.Drawing.Size(1024, 4096);
this.MinimumSize = new System.Drawing.Size(372, 403);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Gabtastik";
this.contextMenuStrip1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem gabToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem facebookcomToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem googlecomToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem meebocomToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pageSetupToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem releaseNotesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem softwareLicenseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem creditsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem contactCustomerSupportToolStripMenuItem;
private ExtendedWebBrowser2.ExtendedWebBrowser extendedWebBrowser1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem checkForUpdatesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutGabtastikToolStripMenuItem;
private System.Windows.Forms.NotifyIcon notifyIcon1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem facebookcomToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem googlecomToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem meebocomToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem preferencesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem6;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem8;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private System.Windows.Forms.ToolStripMenuItem logoutToolStripMenuItem;
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
// using System.Data;
using System.Diagnostics;
/// <summary>
/// The SeaGrid is the grid upon which the ships are deployed.
/// </summary>
/// <remarks>
/// The grid is viewable via the ISeaGrid interface as a read only
/// grid. This can be used in conjuncture with the SeaGridAdapter to
/// mask the position of the ships.
/// </remarks>
public class SeaGrid : ISeaGrid
{
private const int _WIDTH = 10;
private const int _HEIGHT = 10;
private Tile[,] _GameTiles;
private Dictionary<ShipName, Ship> _Ships;
private int _ShipsKilled = 0;
/// <summary>
/// The sea grid has changed and should be redrawn.
/// </summary>
public event EventHandler Changed;
/// <summary>
/// The width of the sea grid.
/// </summary>
/// <value>The width of the sea grid.</value>
/// <returns>The width of the sea grid.</returns>
public int Width {
get { return _WIDTH; }
}
/// <summary>
/// The height of the sea grid
/// </summary>
/// <value>The height of the sea grid</value>
/// <returns>The height of the sea grid</returns>
public int Height {
get { return _HEIGHT; }
}
/// <summary>
/// ShipsKilled returns the number of ships killed
/// </summary>
public int ShipsKilled {
get { return _ShipsKilled; }
}
/// <summary>
/// Show the tile view
/// </summary>
/// <param name="x">x coordinate of the tile</param>
/// <param name="y">y coordiante of the tile</param>
/// <returns></returns>
public TileView this[int x, int y]
{
get { return _GameTiles[x, y].View; }
}
/// <summary>
/// AllDeployed checks if all the ships are deployed
/// </summary>
public bool AllDeployed {
get {
foreach (Ship s in _Ships.Values) {
if (!s.IsDeployed) {
return false;
}
}
return true;
}
}
/// <summary>
/// SeaGrid constructor, a seagrid has a number of tiles stored in an array
/// </summary>
public SeaGrid(Dictionary<ShipName, Ship> ships)
{
_GameTiles = new Tile[Width, Height];
//fill array with empty Tiles
int i = 0;
for (i = 0; i <= Width - 1; i++) {
for (int j = 0; j <= Height - 1; j++) {
_GameTiles[i, j] = new Tile(i, j, null);
}
}
_Ships = ships;
}
/// <summary>
/// MoveShips allows for ships to be placed on the seagrid
/// </summary>
/// <param name="row">the row selected</param>
/// <param name="col">the column selected</param>
/// <param name="ship">the ship selected</param>
/// <param name="direction">the direction the ship is going</param>
public void MoveShip(int row,int col,ShipName ship,Direction direction)
{
//Ship newShip = _Ships[ship];
Ship newShip = GetShipNamed(ship);
if (newShip == null) {
throw new ArgumentNullException("ShipName does not exist.");
}
newShip.Remove();
AddShip(row, col, direction, newShip);
}
/// <summary>
/// Gets the ship currently occupying the specified tile.
/// </summary>
/// <param name="location">The tile to check.</param>
public Ship GetShipAtTile(Tile location)
{
Ship res = null;
List<Tile> occupiedTiles;
foreach (KeyValuePair<ShipName, Ship> kvp in _Ships) {
occupiedTiles = kvp.Value.OccupiedTiles;
foreach (Tile t in occupiedTiles) {
if (t.Row == location.Row && t.Column == location.Column) {
res = kvp.Value;
break;
}
}
if (res != null) {
break;
}
}
return res;
}
/// <summary>
/// Gets the ship on this grid with the specified ShipName, or null if no such ship exists.
/// </summary>
/// <param name="name">The name of the ship to get.</param>
public Ship GetShipNamed(ShipName name)
{
return _Ships.ContainsKey(name) ? _Ships[name] : null;
}
/// <summary>
/// AddShip add a ship to the SeaGrid
/// </summary>
/// <param name="row">row coordinate</param>
/// <param name="col">col coordinate</param>
/// <param name="direction">direction of ship</param>
/// <param name="newShip">the ship</param>
private void AddShip(int row, int col, Direction direction, Ship newShip)
{
try {
int size = newShip.Size;
int currentRow = row;
int currentCol = col;
int dRow = 0;
int dCol = 0;
if (direction == Direction.LeftRight) {
dRow = 0;
dCol = 1;
} else {
dRow = 1;
dCol = 0;
}
//place ship's tiles in array and into ship object
int i = 0;
for (i = 0; i < size; i++) {
if (currentRow < 0 | currentRow >= Width | currentCol < 0 | currentCol >= Height) {
throw new InvalidOperationException("Ship can't fit on the board");
}
_GameTiles[currentRow, currentCol].Ship = newShip;
currentCol += dCol;
currentRow += dRow;
}
newShip.Deployed(direction, row, col);
} catch (Exception e) {
newShip.Remove();
//if fails remove the ship
throw new ApplicationException(e.Message);
} finally {
if (Changed != null) {
Changed(this, EventArgs.Empty);
}
}
}
/// <summary>
/// HitTile hits a tile at a row/col, and whatever tile has been hit, a
/// result will be displayed.
/// </summary>
/// <param name="row">the row at which is being shot</param>
/// <param name="col">the cloumn at which is being shot</param>
/// <returns>An attackresult (hit, miss, sunk, shotalready)</returns>
public AttackResult HitTile(int row, int col)
{
try {
//tile is already hit
if (_GameTiles[row, col].Shot) {
return new AttackResult(ResultOfAttack.ShotAlready, "have already attacked [" + col + "," + row + "]!", row, col);
}
_GameTiles[row, col].Shoot();
//there is no ship on the tile
if (_GameTiles[row, col].Ship == null) {
return new AttackResult(ResultOfAttack.Miss, "missed", row, col);
}
//all ship's tiles have been destroyed
if (_GameTiles[row, col].Ship.IsDestroyed) {
_GameTiles[row, col].Shot = true;
_ShipsKilled += 1;
return new AttackResult(ResultOfAttack.Destroyed, _GameTiles[row, col].Ship, "destroyed the enemy's", row, col);
}
//else hit but not destroyed
return new AttackResult(ResultOfAttack.Hit, "hit something!", row, col);
} finally {
if (Changed != null) {
Changed(this, EventArgs.Empty);
}
}
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: @telerik
//Facebook: facebook.com/telerik
//=======================================================
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Security.Attestation
{
/// <summary>
/// Attestation Client for the Microsoft Azure Attestation service.
///
/// The Attestation client contains the implementation of the "Attest" family of MAA apis.
/// </summary>
public class AttestationAdministrationClient : IDisposable
{
private readonly AttestationClientOptions _options;
private readonly HttpPipeline _pipeline;
private readonly ClientDiagnostics _clientDiagnostics;
private readonly PolicyRestClient _policyClient;
private readonly PolicyCertificatesRestClient _policyManagementClient;
private readonly AttestationClient _attestationClient;
private IReadOnlyList<AttestationSigner> _signers;
private SemaphoreSlim _statelock = new SemaphoreSlim(1, 1);
private bool _disposedValue;
// Default scope for data plane APIs.
private const string DefaultScope = "https://attest.azure.net/.default";
/// <summary>
/// Returns the URI used to communicate with the service.
/// </summary>
public Uri Endpoint { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AttestationClient"/> class.
/// </summary>
/// <param name="endpoint">Uri for the Microsoft Azure Attestation Service Instance to use.</param>
/// <param name="credential">Credentials to be used in the Client.</param>
public AttestationAdministrationClient(Uri endpoint, TokenCredential credential)
: this(endpoint, credential, new AttestationClientOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AttestationClient"/> class.
/// </summary>
/// <param name="endpoint">Uri for the Microsoft Azure Attestation Service Instance to use.</param>
/// <param name="credential">Credentials to be used in the Client.</param>
/// <param name="options"><see cref="AttestationClientOptions"/> used to configure the API client.</param>
public AttestationAdministrationClient(Uri endpoint, TokenCredential credential, AttestationClientOptions options)
{
Argument.AssertNotNull(endpoint, nameof(endpoint));
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNull(options, nameof(options));
_options = options;
// Add the authentication policy to our builder.
_pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, DefaultScope));
// Initialize the ClientDiagnostics.
_clientDiagnostics = new ClientDiagnostics(options);
Endpoint = endpoint;
// Initialize the Policy Rest Client.
_policyClient = new PolicyRestClient(_clientDiagnostics, _pipeline, Endpoint.AbsoluteUri, options.Version);
// Initialize the Certificates Rest Client.
_policyManagementClient = new PolicyCertificatesRestClient(_clientDiagnostics, _pipeline, Endpoint.AbsoluteUri, options.Version);
// Initialize the Attestation Rest Client.
_attestationClient = new AttestationClient(endpoint, credential, options);
}
/// <summary>
/// Parameterless constructor for mocking.
/// </summary>
protected AttestationAdministrationClient()
{
}
/// <summary>
/// Retrieves the attesttion policy for the specified <see cref="AttestationType"/>.
/// </summary>
/// <param name="attestationType"><see cref="AttestationType"/> to retrive.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{String}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// This API returns the underlying attestation policy object stored in the attestation service for this <paramref name="attestationType"/>.
///
/// The actual service response to the API is an RFC 7519 JSON Web Token. This token can be retrieved from <see cref="AttestationResponse{T}.Token"/>.
/// For the GetPolicy API, the body of the <see cref="AttestationResponse{T}.Token"/> is a <see cref="StoredAttestationPolicy"/> object, NOT a string.
/// </remarks>
public virtual AttestationResponse<string> GetPolicy(AttestationType attestationType, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(GetPolicy)}");
scope.Start();
try
{
var result = _policyClient.Get(attestationType, cancellationToken);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
token.ValidateToken(_options.TokenOptions, GetSigners(cancellationToken), cancellationToken);
}
using var document = JsonDocument.Parse(token.TokenBody);
PolicyResult policyResult = PolicyResult.DeserializePolicyResult(document.RootElement);
var response = new AttestationResponse<StoredAttestationPolicy>(result.GetRawResponse(), policyResult.PolicyToken);
return new AttestationResponse<string>(result.GetRawResponse(), policyResult.PolicyToken, response.Value.AttestationPolicy);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Retrieves the attesttion policy for the specified <see cref="AttestationType"/>.
/// </summary>
/// <param name="attestationType">Attestation Type to retrive.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{String}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// This API returns the underlying attestation policy object stored in the attestation service for this <paramref name="attestationType"/>.
///
/// The actual service response to the API is an RFC 7519 JSON Web Token. This token can be retrieved from <see cref="AttestationResponse{T}.Token"/>.
/// For the GetPolicyAsync API, the body of the <see cref="AttestationResponse{T}.Token"/> is a <see cref="StoredAttestationPolicy"/> object, NOT a string.
/// </remarks>
public virtual async Task<AttestationResponse<string>> GetPolicyAsync(AttestationType attestationType, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(GetPolicy)}");
scope.Start();
try
{
var result = await _policyClient.GetAsync(attestationType, cancellationToken).ConfigureAwait(false);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
await token.ValidateTokenAsync(_options.TokenOptions, await GetSignersAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
using var document = JsonDocument.Parse(token.TokenBody);
PolicyResult policyResult = PolicyResult.DeserializePolicyResult(document.RootElement);
var response = new AttestationResponse<StoredAttestationPolicy>(result.GetRawResponse(), policyResult.PolicyToken);
return new AttestationResponse<string>(result.GetRawResponse(), policyResult.PolicyToken, response.Value.AttestationPolicy);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Sets the attesttion policy for the specified <see cref="AttestationType"/>.
/// </summary>
/// <param name="attestationType"><see cref="AttestationType"/> whose policy should be set.</param>
/// <param name="policyToSet">Specifies the attestation policy to set.</param>
/// <param name="signingKey">If provided, specifies the signing key used to sign the request to the attestation service.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
/// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
/// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
/// The <see cref="TokenSigningKey.Certificate"/> field MUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
/// <para/>
/// Clients need to be able to verify that the attestation policy document was not modified before the policy document was received by the attestation service's enclave.
/// There are two properties provided in the [PolicyResult][attestation_policy_result] that can be used to verify that the service received the policy document:
/// <list type="bullet">
/// <item>
/// <description><see cref="PolicyResult.PolicySigner"/> - if the <see cref="SetPolicy(AttestationType, string, TokenSigningKey, CancellationToken)"/> call included a signing certificate, this will be the certificate provided at the time of the `SetPolicy` call. If no policy signer was set, this will be null. </description>
/// </item>
/// <item>
/// <description><see cref="PolicyResult.PolicyTokenHash"/> - this is the hash of the [JSON Web Token][json_web_token] sent to the service</description>
/// </item>
/// </list>
/// To verify the hash, clients can generate an attestation token and verify the hash generated from that token:
/// <code snippet="Snippet:VerifySigningHash">
/// // The SetPolicyAsync API will create an AttestationToken signed with the TokenSigningKey to transmit the policy.
/// // To verify that the policy specified by the caller was received by the service inside the enclave, we
/// // verify that the hash of the policy document returned from the Attestation Service matches the hash
/// // of an attestation token created locally.
/// TokenSigningKey signingKey = new TokenSigningKey(<Customer provided signing key>, <Customer provided certificate>)
/// var policySetToken = new AttestationToken(
/// new StoredAttestationPolicy { AttestationPolicy = attestationPolicy },
/// signingKey);
///
/// using var shaHasher = SHA256Managed.Create();
/// var attestationPolicyHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));
///
/// Debug.Assert(attestationPolicyHash.SequenceEqual(setResult.Value.PolicyTokenHash));
/// </code>
///
/// If the signing key and certificate are not provided, then the SetPolicyAsync API will create an unsecured attestation token
/// wrapping the attestation policy. To validate the <see cref="PolicyResult.PolicyTokenHash"/> return value, a developer
/// can create their own <see cref="AttestationToken"/> and create the hash of that.
/// <code>
/// using var shaHasher = SHA256Managed.Create();
/// var policySetToken = new UnsecuredAttestationToken(new StoredAttestationPolicy { AttestationPolicy = disallowDebugging });
/// disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));
/// </code>
/// </remarks>
public virtual AttestationResponse<PolicyResult> SetPolicy(
AttestationType attestationType,
string policyToSet,
TokenSigningKey signingKey = default,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrWhiteSpace(policyToSet, nameof(policyToSet));
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(SetPolicy)}");
scope.Start();
try
{
AttestationToken tokenToSet = new AttestationToken(
new StoredAttestationPolicy { AttestationPolicy = policyToSet, },
signingKey);
var result = _policyClient.Set(attestationType, tokenToSet.ToString(), cancellationToken);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
token.ValidateToken(_options.TokenOptions, GetSigners(cancellationToken), cancellationToken);
}
return new AttestationResponse<PolicyResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Sets the attesttion policy for the specified <see cref="AttestationType"/>.
/// </summary>
/// <param name="attestationType"><see cref="AttestationType"/> whose policy should be set.</param>
/// <param name="policyToSet">Specifies the attestation policy to set.</param>
/// <param name="signingKey">If provided, specifies the signing key used to sign the request to the attestation service.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
/// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
/// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
/// The <see cref="TokenSigningKey.Certificate"/> field MUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
/// <para/>
/// Clients need to be able to verify that the attestation policy document was not modified before the policy document was received by the attestation service's enclave.
/// There are two properties provided in the [PolicyResult][attestation_policy_result] that can be used to verify that the service received the policy document:
/// <list type="bullet">
/// <item>
/// <description><see cref="PolicyResult.PolicySigner"/> - if the <see cref="SetPolicy(AttestationType, string, TokenSigningKey, CancellationToken)"/> call included a signing certificate, this will be the certificate provided at the time of the `SetPolicy` call. If no policy signer was set, this will be null. </description>
/// </item>
/// <item>
/// <description><see cref="PolicyResult.PolicyTokenHash"/> - this is the hash of the [JSON Web Token][json_web_token] sent to the service</description>
/// </item>
/// </list>
/// To verify the hash, clients can generate an attestation token and verify the hash generated from that token:
/// <code snippet="Snippet:VerifySigningHash">
/// // The SetPolicyAsync API will create an AttestationToken signed with the TokenSigningKey to transmit the policy.
/// // To verify that the policy specified by the caller was received by the service inside the enclave, we
/// // verify that the hash of the policy document returned from the Attestation Service matches the hash
/// // of an attestation token created locally.
/// TokenSigningKey signingKey = new TokenSigningKey(<Customer provided signing key>, <Customer provided certificate>)
/// var policySetToken = new AttestationToken(
/// new StoredAttestationPolicy { AttestationPolicy = attestationPolicy },
/// signingKey);
///
/// using var shaHasher = SHA256Managed.Create();
/// var attestationPolicyHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));
///
/// Debug.Assert(attestationPolicyHash.SequenceEqual(setResult.Value.PolicyTokenHash));
/// </code>
///
/// If the signing key and certificate are not provided, then the SetPolicyAsync API will create an unsecured attestation token
/// wrapping the attestation policy. To validate the <see cref="PolicyResult.PolicyTokenHash"/> return value, a developer
/// can create their own <see cref="AttestationToken"/> and create the hash of that.
/// <code>
/// using var shaHasher = SHA256Managed.Create();
/// var policySetToken = new AttestationToken(new StoredAttestationPolicy { AttestationPolicy = disallowDebugging });
/// disallowDebuggingHash = shaHasher.ComputeHash(Encoding.UTF8.GetBytes(policySetToken.ToString()));
/// </code>
/// </remarks>
public virtual async Task<AttestationResponse<PolicyResult>> SetPolicyAsync(
AttestationType attestationType,
string policyToSet,
TokenSigningKey signingKey = default,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(policyToSet))
{
throw new ArgumentException($"'{nameof(policyToSet)}' cannot be null or empty.", nameof(policyToSet));
}
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(SetPolicy)}");
scope.Start();
try
{
AttestationToken tokenToSet = new AttestationToken(new StoredAttestationPolicy { AttestationPolicy = policyToSet, }, signingKey);
var result = await _policyClient.SetAsync(attestationType, tokenToSet.ToString(), cancellationToken).ConfigureAwait(false);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
await token.ValidateTokenAsync(_options.TokenOptions, await GetSignersAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
return new AttestationResponse<PolicyResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Resets the policy for the specified <see cref="AttestationType"/> to the default value.
/// </summary>
/// <param name="attestationType"><see cref="AttestationType"/> whose policy should be reset.</param>
/// <param name="signingKey">If provided, specifies the signing key and certificate used to sign the request to the attestation service.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
/// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
/// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
/// The <see cref="TokenSigningKey.Certificate"/> fieldMUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
/// <para/>
/// </remarks>
///
public virtual AttestationResponse<PolicyResult> ResetPolicy(
AttestationType attestationType,
TokenSigningKey signingKey = default,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(ResetPolicy)}");
scope.Start();
try
{
AttestationToken tokenToSet = new AttestationToken(null, signingKey);
var result = _policyClient.Reset(attestationType, tokenToSet.ToString(), cancellationToken);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
token.ValidateToken(_options.TokenOptions, GetSigners(cancellationToken), cancellationToken);
}
return new AttestationResponse<PolicyResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Resets the policy for the specified <see cref="AttestationType"/> to the default value.
/// </summary>
/// <param name="attestationType"><see cref="AttestationType"/> whose policy should be reset.</param>
/// <param name="signingKey">If provided, specifies the signing key used to sign the request to the attestation service.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyResult}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// If the <paramref name="signingKey"/> parameter is not provided, then the policy document sent to the
/// attestation service will be unsigned. Unsigned attestation policies are only allowed when the attestation instance is running in AAD mode - if the
/// attestation instance is running in Isolated mode, then a signing key and signing certificate MUST be provided to ensure that the caller of the API is authorized to change policy.
/// The <see cref="TokenSigningKey.Certificate"/> parameter MUST be one of the certificates returned by the <see cref="GetPolicyManagementCertificates(CancellationToken)"/> API.
/// <para/>
/// </remarks>
public virtual async Task<AttestationResponse<PolicyResult>> ResetPolicyAsync(
AttestationType attestationType,
TokenSigningKey signingKey = default,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(ResetPolicy)}");
scope.Start();
try
{
AttestationToken tokenToSet = new AttestationToken(null, signingKey);
var result = await _policyClient.ResetAsync(attestationType, tokenToSet.ToString(), cancellationToken).ConfigureAwait(false);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
await token.ValidateTokenAsync(_options.TokenOptions, await GetSignersAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
return new AttestationResponse<PolicyResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Returns the set of policy management certificates currently configured for the attestation service instance.
///
/// If the service instance is running in AAD mode, this list will always be empty.
/// </summary>
/// <param name="cancellationToken">Cancellation token used to cancel the operation.</param>
/// <returns>A set of <see cref="X509Certificate2"/> objects representing the set of root certificates for policy management.</returns>
public virtual AttestationResponse<PolicyCertificatesResult> GetPolicyManagementCertificates(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(GetPolicyManagementCertificates)}");
scope.Start();
try
{
var result = _policyManagementClient.Get(cancellationToken);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
token.ValidateToken(_options.TokenOptions, GetSigners(cancellationToken), cancellationToken);
}
return new AttestationResponse<PolicyCertificatesResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Returns the set of policy management certificates currently configured for the attestation service instance.
///
/// If the service instance is running in AAD mode, this list will always be empty.
/// </summary>
/// <param name="cancellationToken">Cancellation token used to cancel the operation.</param>
/// <returns>A set of <see cref="X509Certificate2"/> objects representing the set of root certificates for policy management.</returns>
public virtual async Task<AttestationResponse<PolicyCertificatesResult>> GetPolicyManagementCertificatesAsync(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(GetPolicyManagementCertificates)}");
scope.Start();
try
{
var result = await _policyManagementClient.GetAsync(cancellationToken).ConfigureAwait(false);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
await token.ValidateTokenAsync(_options.TokenOptions, await GetSignersAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
return new AttestationResponse<PolicyCertificatesResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Adds the specified new signing certificate to the set of policy management certificates.
/// </summary>
/// <param name="newSigningCertificate">The new certificate to add.</param>
/// <param name="existingSigningKey">An existing key corresponding to the existing certificate.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyCertificatesModificationResult}"/> with the policy for the specified attestation type.</returns>
/// <remarks>
/// </remarks>
public virtual AttestationResponse<PolicyCertificatesModificationResult> AddPolicyManagementCertificate(
X509Certificate2 newSigningCertificate,
TokenSigningKey existingSigningKey,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(existingSigningKey, nameof(existingSigningKey));
Argument.AssertNotNull(newSigningCertificate, nameof(newSigningCertificate));
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(AddPolicyManagementCertificate)}");
scope.Start();
try
{
var tokenToAdd = new AttestationToken(
new PolicyCertificateModification(newSigningCertificate),
existingSigningKey);
var result = _policyManagementClient.Add(tokenToAdd.ToString(), cancellationToken);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
token.ValidateToken(_options.TokenOptions, GetSigners(cancellationToken), cancellationToken);
}
return new AttestationResponse<PolicyCertificatesModificationResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Adds the specified new signing certificate to the set of policy management certificates.
/// </summary>
/// <param name="newSigningCertificate">The new certificate to add.</param>
/// <param name="existingSigningKey">An existing key corresponding to the existing certificate.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyCertificatesModificationResult}"/> with the policy for the specified attestation type.</returns>
public virtual async Task<AttestationResponse<PolicyCertificatesModificationResult>> AddPolicyManagementCertificateAsync(
X509Certificate2 newSigningCertificate,
TokenSigningKey existingSigningKey,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(existingSigningKey, nameof(existingSigningKey));
Argument.AssertNotNull(newSigningCertificate, nameof(newSigningCertificate));
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(AddPolicyManagementCertificate)}");
scope.Start();
try
{
var tokenToAdd = new AttestationToken(
new PolicyCertificateModification(newSigningCertificate),
existingSigningKey);
var result = await _policyManagementClient.AddAsync(tokenToAdd.ToString(), cancellationToken).ConfigureAwait(false);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
await token.ValidateTokenAsync(_options.TokenOptions, await GetSignersAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
return new AttestationResponse<PolicyCertificatesModificationResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Retrieves the attesttion policy for the specified <see cref="AttestationType"/>.
/// </summary>
/// <param name="certificateToRemove">The certificate to remove.</param>
/// <param name="existingSigningKey">An existing key corresponding to the existing certificate.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyCertificatesModificationResult}"/> with the policy for the specified attestation type.</returns>
public virtual AttestationResponse<PolicyCertificatesModificationResult> RemovePolicyManagementCertificate(
X509Certificate2 certificateToRemove,
TokenSigningKey existingSigningKey,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(RemovePolicyManagementCertificate)}");
scope.Start();
try
{
var tokenToRemove = new AttestationToken(
new PolicyCertificateModification(certificateToRemove),
existingSigningKey);
var result = _policyManagementClient.Remove(tokenToRemove.ToString(), cancellationToken);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
token.ValidateToken(_options.TokenOptions, GetSigners(cancellationToken), cancellationToken);
}
return new AttestationResponse<PolicyCertificatesModificationResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Removes one of the attestation policy management certificates.
/// </summary>
/// <param name="certificateToRemove">The certificate to remove.</param>
/// <param name="existingSigningKey">An existing key corresponding to the existing certificate.</param>
/// <param name="cancellationToken">Cancellation token used to cancel this operation.</param>
/// <returns>An <see cref="AttestationResponse{PolicyCertificatesModificationResult}"/> with the policy for the specified attestation type.</returns>
public virtual async Task<AttestationResponse<PolicyCertificatesModificationResult>> RemovePolicyManagementCertificateAsync(
X509Certificate2 certificateToRemove,
TokenSigningKey existingSigningKey,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(AttestationAdministrationClient)}.{nameof(RemovePolicyManagementCertificate)}");
scope.Start();
try
{
var tokenToRemove = new AttestationToken(
new PolicyCertificateModification(certificateToRemove),
existingSigningKey);
var result = await _policyManagementClient.RemoveAsync(tokenToRemove.ToString(), cancellationToken).ConfigureAwait(false);
var token = new AttestationToken(result.Value.Token);
if (_options.TokenOptions.ValidateToken)
{
await token.ValidateTokenAsync(_options.TokenOptions, await GetSignersAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
}
return new AttestationResponse<PolicyCertificatesModificationResult>(result.GetRawResponse(), token);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
private async Task<IReadOnlyList<AttestationSigner>> GetSignersAsync(CancellationToken cancellationToken)
{
await _statelock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_signers == null)
{
_signers = (await _attestationClient.GetSigningCertificatesAsync(cancellationToken).ConfigureAwait(false)).Value;
}
return _signers;
}
finally
{
_statelock.Release();
}
}
private IReadOnlyList<AttestationSigner> GetSigners(CancellationToken cancellationToken)
{
_statelock.Wait(cancellationToken);
try
{
if (_signers == null)
{
_signers = _attestationClient.GetSigningCertificates(cancellationToken).Value;
}
return _signers;
}
finally
{
_statelock.Release();
}
}
/// <summary>
/// Dispose this object.
/// </summary>
/// <param name="disposing">True if the caller wants us to dispose our underlying objects.</param>
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// Dispose managed state (managed objects)
_statelock.Dispose();
_attestationClient.Dispose();
}
_disposedValue = true;
}
}
/// <inheritdoc/>
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
| |
// LzmaEncoder.cs
using System;
namespace SevenZip.Compression.LZMA
{
using RangeCoder;
internal class Encoder : ICoder, ISetCoderProperties, IWriteCoderProperties
{
enum EMatchFinderType
{
BT2,
BT4,
};
const UInt32 kIfinityPrice = 0xFFFFFFF;
static Byte[] g_FastPos = new Byte[1 << 11];
static Encoder()
{
const Byte kFastSlots = 22;
int c = 2;
g_FastPos[0] = 0;
g_FastPos[1] = 1;
for (Byte slotFast = 2; slotFast < kFastSlots; slotFast++)
{
UInt32 k = ((UInt32)1 << ((slotFast >> 1) - 1));
for (UInt32 j = 0; j < k; j++, c++)
g_FastPos[c] = slotFast;
}
}
static UInt32 GetPosSlot(UInt32 pos)
{
if (pos < (1 << 11))
return g_FastPos[pos];
if (pos < (1 << 21))
return (UInt32)(g_FastPos[pos >> 10] + 20);
return (UInt32)(g_FastPos[pos >> 20] + 40);
}
static UInt32 GetPosSlot2(UInt32 pos)
{
if (pos < (1 << 17))
return (UInt32)(g_FastPos[pos >> 6] + 12);
if (pos < (1 << 27))
return (UInt32)(g_FastPos[pos >> 16] + 32);
return (UInt32)(g_FastPos[pos >> 26] + 52);
}
Base.State _state = new Base.State();
Byte _previousByte;
UInt32[] _repDistances = new UInt32[Base.kNumRepDistances];
void BaseInit()
{
_state.Init();
_previousByte = 0;
for (UInt32 i = 0; i < Base.kNumRepDistances; i++)
_repDistances[i] = 0;
}
const int kDefaultDictionaryLogSize = 22;
const UInt32 kNumFastBytesDefault = 0x20;
class LiteralEncoder
{
public struct Encoder2
{
BitEncoder[] m_Encoders;
public void Create() { m_Encoders = new BitEncoder[0x300]; }
public void Init() { for (int i = 0; i < 0x300; i++) m_Encoders[i].Init(); }
public void Encode(RangeCoder.Encoder rangeEncoder, byte symbol)
{
uint context = 1;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
m_Encoders[context].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public void EncodeMatched(RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
{
uint context = 1;
bool same = true;
for (int i = 7; i >= 0; i--)
{
uint bit = (uint)((symbol >> i) & 1);
uint state = context;
if (same)
{
uint matchBit = (uint)((matchByte >> i) & 1);
state += ((1 + matchBit) << 8);
same = (matchBit == bit);
}
m_Encoders[state].Encode(rangeEncoder, bit);
context = (context << 1) | bit;
}
}
public uint GetPrice(bool matchMode, byte matchByte, byte symbol)
{
uint price = 0;
uint context = 1;
int i = 7;
if (matchMode)
{
for (; i >= 0; i--)
{
uint matchBit = (uint)(matchByte >> i) & 1;
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[((1 + matchBit) << 8) + context].GetPrice(bit);
context = (context << 1) | bit;
if (matchBit != bit)
{
i--;
break;
}
}
}
for (; i >= 0; i--)
{
uint bit = (uint)(symbol >> i) & 1;
price += m_Encoders[context].GetPrice(bit);
context = (context << 1) | bit;
}
return price;
}
}
Encoder2[] m_Coders;
int m_NumPrevBits;
int m_NumPosBits;
uint m_PosMask;
public void Create(int numPosBits, int numPrevBits)
{
if (m_Coders != null && m_NumPrevBits == numPrevBits && m_NumPosBits == numPosBits)
return;
m_NumPosBits = numPosBits;
m_PosMask = ((uint)1 << numPosBits) - 1;
m_NumPrevBits = numPrevBits;
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
m_Coders = new Encoder2[numStates];
for (uint i = 0; i < numStates; i++)
m_Coders[i].Create();
}
public void Init()
{
uint numStates = (uint)1 << (m_NumPrevBits + m_NumPosBits);
for (uint i = 0; i < numStates; i++)
m_Coders[i].Init();
}
public Encoder2 GetSubCoder(UInt32 pos, Byte prevByte)
{ return m_Coders[((pos & m_PosMask) << m_NumPrevBits) + (uint)(prevByte >> (8 - m_NumPrevBits))]; }
}
class LenEncoder
{
RangeCoder.BitEncoder _choice = new RangeCoder.BitEncoder();
RangeCoder.BitEncoder _choice2 = new RangeCoder.BitEncoder();
RangeCoder.BitTreeEncoder[] _lowCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
RangeCoder.BitTreeEncoder[] _midCoder = new RangeCoder.BitTreeEncoder[Base.kNumPosStatesEncodingMax];
RangeCoder.BitTreeEncoder _highCoder = new RangeCoder.BitTreeEncoder(Base.kNumHighLenBits);
public LenEncoder()
{
for (UInt32 posState = 0; posState < Base.kNumPosStatesEncodingMax; posState++)
{
_lowCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumLowLenBits);
_midCoder[posState] = new RangeCoder.BitTreeEncoder(Base.kNumMidLenBits);
}
}
public void Init(UInt32 numPosStates)
{
_choice.Init();
_choice2.Init();
for (UInt32 posState = 0; posState < numPosStates; posState++)
{
_lowCoder[posState].Init();
_midCoder[posState].Init();
}
_highCoder.Init();
}
public void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
if (symbol < Base.kNumLowLenSymbols)
{
_choice.Encode(rangeEncoder, 0);
_lowCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
symbol -= Base.kNumLowLenSymbols;
_choice.Encode(rangeEncoder, 1);
if (symbol < Base.kNumMidLenSymbols)
{
_choice2.Encode(rangeEncoder, 0);
_midCoder[posState].Encode(rangeEncoder, symbol);
}
else
{
_choice2.Encode(rangeEncoder, 1);
_highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols);
}
}
}
public void SetPrices(UInt32 posState, UInt32 numSymbols, UInt32[] prices, UInt32 st)
{
UInt32 a0 = _choice.GetPrice0();
UInt32 a1 = _choice.GetPrice1();
UInt32 b0 = a1 + _choice2.GetPrice0();
UInt32 b1 = a1 + _choice2.GetPrice1();
UInt32 i = 0;
for (i = 0; i < Base.kNumLowLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = a0 + _lowCoder[posState].GetPrice(i);
}
for (; i < Base.kNumLowLenSymbols + Base.kNumMidLenSymbols; i++)
{
if (i >= numSymbols)
return;
prices[st + i] = b0 + _midCoder[posState].GetPrice(i - Base.kNumLowLenSymbols);
}
for (; i < numSymbols; i++)
prices[st + i] = b1 + _highCoder.GetPrice(i - Base.kNumLowLenSymbols - Base.kNumMidLenSymbols);
}
};
const UInt32 kNumLenSpecSymbols = Base.kNumLowLenSymbols + Base.kNumMidLenSymbols;
class LenPriceTableEncoder : LenEncoder
{
UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
UInt32 _tableSize;
UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];
public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; }
public UInt32 GetPrice(UInt32 symbol, UInt32 posState)
{
return _prices[posState * Base.kNumLenSymbols + symbol];
}
void UpdateTable(UInt32 posState)
{
SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols);
_counters[posState] = _tableSize;
}
public void UpdateTables(UInt32 numPosStates)
{
for (UInt32 posState = 0; posState < numPosStates; posState++)
UpdateTable(posState);
}
public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
{
base.Encode(rangeEncoder, symbol, posState);
if (--_counters[posState] == 0)
UpdateTable(posState);
}
}
const UInt32 kNumOpts = 1 << 12;
class Optimal
{
public Base.State State;
public bool Prev1IsChar;
public bool Prev2;
public UInt32 PosPrev2;
public UInt32 BackPrev2;
public UInt32 Price;
public UInt32 PosPrev;
public UInt32 BackPrev;
public UInt32 Backs0;
public UInt32 Backs1;
public UInt32 Backs2;
public UInt32 Backs3;
public void MakeAsChar() { BackPrev = 0xFFFFFFFF; Prev1IsChar = false; }
public void MakeAsShortRep() { BackPrev = 0; ; Prev1IsChar = false; }
public bool IsShortRep() { return (BackPrev == 0); }
};
Optimal[] _optimum = new Optimal[kNumOpts];
LZ.IMatchFinder _matchFinder = null;
RangeCoder.Encoder _rangeEncoder = new RangeCoder.Encoder();
RangeCoder.BitEncoder[] _isMatch = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
RangeCoder.BitEncoder[] _isRep = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG0 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG1 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRepG2 = new RangeCoder.BitEncoder[Base.kNumStates];
RangeCoder.BitEncoder[] _isRep0Long = new RangeCoder.BitEncoder[Base.kNumStates << Base.kNumPosStatesBitsMax];
RangeCoder.BitTreeEncoder[] _posSlotEncoder = new RangeCoder.BitTreeEncoder[Base.kNumLenToPosStates];
RangeCoder.BitEncoder[] _posEncoders = new RangeCoder.BitEncoder[Base.kNumFullDistances - Base.kEndPosModelIndex];
RangeCoder.BitTreeEncoder _posAlignEncoder = new RangeCoder.BitTreeEncoder(Base.kNumAlignBits);
LenPriceTableEncoder _lenEncoder = new LenPriceTableEncoder();
LenPriceTableEncoder _repMatchLenEncoder = new LenPriceTableEncoder();
LiteralEncoder _literalEncoder = new LiteralEncoder();
UInt32[] _matchDistances = new UInt32[Base.kMatchMaxLen * 2 + 2];
UInt32 _numFastBytes = kNumFastBytesDefault;
UInt32 _longestMatchLength;
UInt32 _numDistancePairs;
UInt32 _additionalOffset;
UInt32 _optimumEndIndex;
UInt32 _optimumCurrentIndex;
bool _longestMatchWasFound;
UInt32[] _posSlotPrices = new UInt32[1 << (Base.kNumPosSlotBits + Base.kNumLenToPosStatesBits)];
UInt32[] _distancesPrices = new UInt32[Base.kNumFullDistances << Base.kNumLenToPosStatesBits];
UInt32[] _alignPrices = new UInt32[Base.kAlignTableSize];
UInt32 _alignPriceCount;
UInt32 _distTableSize = (kDefaultDictionaryLogSize * 2);
int _posStateBits = 2;
UInt32 _posStateMask = (4 - 1);
int _numLiteralPosStateBits = 0;
int _numLiteralContextBits = 3;
UInt32 _dictionarySize = (1 << kDefaultDictionaryLogSize);
UInt32 _dictionarySizePrev = 0xFFFFFFFF;
UInt32 _numFastBytesPrev = 0xFFFFFFFF;
Int64 nowPos64;
bool _finished;
System.IO.Stream _inStream;
EMatchFinderType _matchFinderType = EMatchFinderType.BT4;
bool _writeEndMark = false;
bool _needReleaseMFStream;
void Create()
{
if (_matchFinder == null)
{
LZ.BinTree bt = new LZ.BinTree();
int numHashBytes = 4;
if (_matchFinderType == EMatchFinderType.BT2)
numHashBytes = 2;
bt.SetType(numHashBytes);
_matchFinder = bt;
}
_literalEncoder.Create(_numLiteralPosStateBits, _numLiteralContextBits);
if (_dictionarySize == _dictionarySizePrev && _numFastBytesPrev == _numFastBytes)
return;
_matchFinder.Create(_dictionarySize, kNumOpts, _numFastBytes, Base.kMatchMaxLen + 1);
_dictionarySizePrev = _dictionarySize;
_numFastBytesPrev = _numFastBytes;
}
public Encoder()
{
for (int i = 0; i < kNumOpts; i++)
_optimum[i] = new Optimal();
for (int i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i] = new RangeCoder.BitTreeEncoder(Base.kNumPosSlotBits);
}
void SetWriteEndMarkerMode(bool writeEndMarker)
{
_writeEndMark = writeEndMarker;
}
void Init()
{
BaseInit();
_rangeEncoder.Init();
uint i;
for (i = 0; i < Base.kNumStates; i++)
{
for (uint j = 0; j <= _posStateMask; j++)
{
uint complexState = (i << Base.kNumPosStatesBitsMax) + j;
_isMatch[complexState].Init();
_isRep0Long[complexState].Init();
}
_isRep[i].Init();
_isRepG0[i].Init();
_isRepG1[i].Init();
_isRepG2[i].Init();
}
_literalEncoder.Init();
for (i = 0; i < Base.kNumLenToPosStates; i++)
_posSlotEncoder[i].Init();
for (i = 0; i < Base.kNumFullDistances - Base.kEndPosModelIndex; i++)
_posEncoders[i].Init();
_lenEncoder.Init((UInt32)1 << _posStateBits);
_repMatchLenEncoder.Init((UInt32)1 << _posStateBits);
_posAlignEncoder.Init();
_longestMatchWasFound = false;
_optimumEndIndex = 0;
_optimumCurrentIndex = 0;
_additionalOffset = 0;
}
void ReadMatchDistances(out UInt32 lenRes, out UInt32 numDistancePairs)
{
lenRes = 0;
numDistancePairs = _matchFinder.GetMatches(_matchDistances);
if (numDistancePairs > 0)
{
lenRes = _matchDistances[numDistancePairs - 2];
if (lenRes == _numFastBytes)
lenRes += _matchFinder.GetMatchLen((int)lenRes - 1, _matchDistances[numDistancePairs - 1],
Base.kMatchMaxLen - lenRes);
}
_additionalOffset++;
}
void MovePos(UInt32 num)
{
if (num > 0)
{
_matchFinder.Skip(num);
_additionalOffset += num;
}
}
UInt32 GetRepLen1Price(Base.State state, UInt32 posState)
{
return _isRepG0[state.Index].GetPrice0() +
_isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0();
}
UInt32 GetPureRepPrice(UInt32 repIndex, Base.State state, UInt32 posState)
{
UInt32 price;
if (repIndex == 0)
{
price = _isRepG0[state.Index].GetPrice0();
price += _isRep0Long[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
}
else
{
price = _isRepG0[state.Index].GetPrice1();
if (repIndex == 1)
price += _isRepG1[state.Index].GetPrice0();
else
{
price += _isRepG1[state.Index].GetPrice1();
price += _isRepG2[state.Index].GetPrice(repIndex - 2);
}
}
return price;
}
UInt32 GetRepPrice(UInt32 repIndex, UInt32 len, Base.State state, UInt32 posState)
{
UInt32 price = _repMatchLenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
return price + GetPureRepPrice(repIndex, state, posState);
}
UInt32 GetPosLenPrice(UInt32 pos, UInt32 len, UInt32 posState)
{
UInt32 price;
UInt32 lenToPosState = Base.GetLenToPosState(len);
if (pos < Base.kNumFullDistances)
price = _distancesPrices[(lenToPosState * Base.kNumFullDistances) + pos];
else
price = _posSlotPrices[(lenToPosState << Base.kNumPosSlotBits) + GetPosSlot2(pos)] +
_alignPrices[pos & Base.kAlignMask];
return price + _lenEncoder.GetPrice(len - Base.kMatchMinLen, posState);
}
UInt32 Backward(out UInt32 backRes, UInt32 cur)
{
_optimumEndIndex = cur;
UInt32 posMem = _optimum[cur].PosPrev;
UInt32 backMem = _optimum[cur].BackPrev;
do
{
if (_optimum[cur].Prev1IsChar)
{
_optimum[posMem].MakeAsChar();
_optimum[posMem].PosPrev = posMem - 1;
if (_optimum[cur].Prev2)
{
_optimum[posMem - 1].Prev1IsChar = false;
_optimum[posMem - 1].PosPrev = _optimum[cur].PosPrev2;
_optimum[posMem - 1].BackPrev = _optimum[cur].BackPrev2;
}
}
UInt32 posPrev = posMem;
UInt32 backCur = backMem;
backMem = _optimum[posPrev].BackPrev;
posMem = _optimum[posPrev].PosPrev;
_optimum[posPrev].BackPrev = backCur;
_optimum[posPrev].PosPrev = cur;
cur = posPrev;
}
while (cur > 0);
backRes = _optimum[0].BackPrev;
_optimumCurrentIndex = _optimum[0].PosPrev;
return _optimumCurrentIndex;
}
UInt32[] reps = new UInt32[Base.kNumRepDistances];
UInt32[] repLens = new UInt32[Base.kNumRepDistances];
UInt32 GetOptimum(UInt32 position, out UInt32 backRes)
{
if (_optimumEndIndex != _optimumCurrentIndex)
{
UInt32 lenRes = _optimum[_optimumCurrentIndex].PosPrev - _optimumCurrentIndex;
backRes = _optimum[_optimumCurrentIndex].BackPrev;
_optimumCurrentIndex = _optimum[_optimumCurrentIndex].PosPrev;
return lenRes;
}
_optimumCurrentIndex = _optimumEndIndex = 0;
UInt32 lenMain, numDistancePairs;
if (!_longestMatchWasFound)
{
ReadMatchDistances(out lenMain, out numDistancePairs);
}
else
{
lenMain = _longestMatchLength;
numDistancePairs = _numDistancePairs;
_longestMatchWasFound = false;
}
UInt32 numAvailableBytes = _matchFinder.GetNumAvailableBytes() + 1;
if (numAvailableBytes < 2)
{
backRes = 0xFFFFFFFF;
return 1;
}
if (numAvailableBytes > Base.kMatchMaxLen)
numAvailableBytes = Base.kMatchMaxLen;
UInt32 repMaxIndex = 0;
UInt32 i;
for (i = 0; i < Base.kNumRepDistances; i++)
{
reps[i] = _repDistances[i];
repLens[i] = _matchFinder.GetMatchLen(0 - 1, reps[i], Base.kMatchMaxLen);
if (repLens[i] > repLens[repMaxIndex])
repMaxIndex = i;
}
if (repLens[repMaxIndex] >= _numFastBytes)
{
backRes = repMaxIndex;
UInt32 lenRes = repLens[repMaxIndex];
MovePos(lenRes - 1);
return lenRes;
}
if (lenMain >= _numFastBytes)
{
backRes = _matchDistances[numDistancePairs - 1] + Base.kNumRepDistances;
MovePos(lenMain - 1);
return lenMain;
}
Byte currentByte = _matchFinder.GetIndexByte(0 - 1);
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - 1));
if (lenMain < 2 && currentByte != matchByte && repLens[repMaxIndex] < 2)
{
backRes = (UInt32)0xFFFFFFFF;
return 1;
}
_optimum[0].State = _state;
UInt32 posState = (position & _posStateMask);
_optimum[1].Price = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _previousByte).GetPrice(!_state.IsCharState(), matchByte, currentByte);
_optimum[1].MakeAsChar();
UInt32 matchPrice = _isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
UInt32 repMatchPrice = matchPrice + _isRep[_state.Index].GetPrice1();
if (matchByte == currentByte)
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(_state, posState);
if (shortRepPrice < _optimum[1].Price)
{
_optimum[1].Price = shortRepPrice;
_optimum[1].MakeAsShortRep();
}
}
UInt32 lenEnd = ((lenMain >= repLens[repMaxIndex]) ? lenMain : repLens[repMaxIndex]);
if (lenEnd < 2)
{
backRes = _optimum[1].BackPrev;
return 1;
}
_optimum[1].PosPrev = 0;
_optimum[0].Backs0 = reps[0];
_optimum[0].Backs1 = reps[1];
_optimum[0].Backs2 = reps[2];
_optimum[0].Backs3 = reps[3];
UInt32 len = lenEnd;
do
_optimum[len--].Price = kIfinityPrice;
while (len >= 2);
for (i = 0; i < Base.kNumRepDistances; i++)
{
UInt32 repLen = repLens[i];
if (repLen < 2)
continue;
UInt32 price = repMatchPrice + GetPureRepPrice(i, _state, posState);
do
{
UInt32 curAndLenPrice = price + _repMatchLenEncoder.GetPrice(repLen - 2, posState);
Optimal optimum = _optimum[repLen];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = i;
optimum.Prev1IsChar = false;
}
}
while (--repLen >= 2);
}
UInt32 normalMatchPrice = matchPrice + _isRep[_state.Index].GetPrice0();
len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2);
if (len <= lenMain)
{
UInt32 offs = 0;
while (len > _matchDistances[offs])
offs += 2;
for (; ; len++)
{
UInt32 distance = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(distance, len, posState);
Optimal optimum = _optimum[len];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = 0;
optimum.BackPrev = distance + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (len == _matchDistances[offs])
{
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
UInt32 cur = 0;
while (true)
{
cur++;
if (cur == lenEnd)
return Backward(out backRes, cur);
UInt32 newLen;
ReadMatchDistances(out newLen, out numDistancePairs);
if (newLen >= _numFastBytes)
{
_numDistancePairs = numDistancePairs;
_longestMatchLength = newLen;
_longestMatchWasFound = true;
return Backward(out backRes, cur);
}
position++;
UInt32 posPrev = _optimum[cur].PosPrev;
Base.State state;
if (_optimum[cur].Prev1IsChar)
{
posPrev--;
if (_optimum[cur].Prev2)
{
state = _optimum[_optimum[cur].PosPrev2].State;
if (_optimum[cur].BackPrev2 < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
else
state = _optimum[posPrev].State;
state.UpdateChar();
}
else
state = _optimum[posPrev].State;
if (posPrev == cur - 1)
{
if (_optimum[cur].IsShortRep())
state.UpdateShortRep();
else
state.UpdateChar();
}
else
{
UInt32 pos;
if (_optimum[cur].Prev1IsChar && _optimum[cur].Prev2)
{
posPrev = _optimum[cur].PosPrev2;
pos = _optimum[cur].BackPrev2;
state.UpdateRep();
}
else
{
pos = _optimum[cur].BackPrev;
if (pos < Base.kNumRepDistances)
state.UpdateRep();
else
state.UpdateMatch();
}
Optimal opt = _optimum[posPrev];
if (pos < Base.kNumRepDistances)
{
if (pos == 0)
{
reps[0] = opt.Backs0;
reps[1] = opt.Backs1;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 1)
{
reps[0] = opt.Backs1;
reps[1] = opt.Backs0;
reps[2] = opt.Backs2;
reps[3] = opt.Backs3;
}
else if (pos == 2)
{
reps[0] = opt.Backs2;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs3;
}
else
{
reps[0] = opt.Backs3;
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
else
{
reps[0] = (pos - Base.kNumRepDistances);
reps[1] = opt.Backs0;
reps[2] = opt.Backs1;
reps[3] = opt.Backs2;
}
}
_optimum[cur].State = state;
_optimum[cur].Backs0 = reps[0];
_optimum[cur].Backs1 = reps[1];
_optimum[cur].Backs2 = reps[2];
_optimum[cur].Backs3 = reps[3];
UInt32 curPrice = _optimum[cur].Price;
currentByte = _matchFinder.GetIndexByte(0 - 1);
matchByte = _matchFinder.GetIndexByte((Int32)(0 - reps[0] - 1 - 1));
posState = (position & _posStateMask);
UInt32 curAnd1Price = curPrice +
_isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice0() +
_literalEncoder.GetSubCoder(position, _matchFinder.GetIndexByte(0 - 2)).
GetPrice(!state.IsCharState(), matchByte, currentByte);
Optimal nextOptimum = _optimum[cur + 1];
bool nextIsChar = false;
if (curAnd1Price < nextOptimum.Price)
{
nextOptimum.Price = curAnd1Price;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsChar();
nextIsChar = true;
}
matchPrice = curPrice + _isMatch[(state.Index << Base.kNumPosStatesBitsMax) + posState].GetPrice1();
repMatchPrice = matchPrice + _isRep[state.Index].GetPrice1();
if (matchByte == currentByte &&
!(nextOptimum.PosPrev < cur && nextOptimum.BackPrev == 0))
{
UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(state, posState);
if (shortRepPrice <= nextOptimum.Price)
{
nextOptimum.Price = shortRepPrice;
nextOptimum.PosPrev = cur;
nextOptimum.MakeAsShortRep();
nextIsChar = true;
}
}
UInt32 numAvailableBytesFull = _matchFinder.GetNumAvailableBytes() + 1;
numAvailableBytesFull = Math.Min(kNumOpts - 1 - cur, numAvailableBytesFull);
numAvailableBytes = numAvailableBytesFull;
if (numAvailableBytes < 2)
continue;
if (numAvailableBytes > _numFastBytes)
numAvailableBytes = _numFastBytes;
if (!nextIsChar && matchByte != currentByte)
{
// try Literal + rep0
UInt32 t = Math.Min(numAvailableBytesFull - 1, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen(0, reps[0], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateChar();
UInt32 posStateNext = (position + 1) & _posStateMask;
UInt32 nextRepMatchPrice = curAnd1Price +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1() +
_isRep[state2.Index].GetPrice1();
{
UInt32 offset = cur + 1 + lenTest2;
while (lenEnd < offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(
0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = false;
}
}
}
}
UInt32 startLen = 2; // speed optimization
for (UInt32 repIndex = 0; repIndex < Base.kNumRepDistances; repIndex++)
{
UInt32 lenTest = _matchFinder.GetMatchLen(0 - 1, reps[repIndex], numAvailableBytes);
if (lenTest < 2)
continue;
UInt32 lenTestTemp = lenTest;
do
{
while (lenEnd < cur + lenTest)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = repIndex;
optimum.Prev1IsChar = false;
}
}
while (--lenTest >= 2);
lenTest = lenTestTemp;
if (repIndex == 0)
startLen = lenTest + 1;
// if (_maxMode)
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, reps[repIndex], t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateRep();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice =
repMatchPrice + GetRepPrice(repIndex, lenTest, state, posState) +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).GetPrice(true,
_matchFinder.GetIndexByte((Int32)((Int32)lenTest - 1 - (Int32)(reps[repIndex] + 1))),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
// for(; lenTest2 >= 2; lenTest2--)
{
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
Optimal optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = repIndex;
}
}
}
}
}
if (newLen > numAvailableBytes)
{
newLen = numAvailableBytes;
for (numDistancePairs = 0; newLen > _matchDistances[numDistancePairs]; numDistancePairs += 2) ;
_matchDistances[numDistancePairs] = newLen;
numDistancePairs += 2;
}
if (newLen >= startLen)
{
normalMatchPrice = matchPrice + _isRep[state.Index].GetPrice0();
while (lenEnd < cur + newLen)
_optimum[++lenEnd].Price = kIfinityPrice;
UInt32 offs = 0;
while (startLen > _matchDistances[offs])
offs += 2;
for (UInt32 lenTest = startLen; ; lenTest++)
{
UInt32 curBack = _matchDistances[offs + 1];
UInt32 curAndLenPrice = normalMatchPrice + GetPosLenPrice(curBack, lenTest, posState);
Optimal optimum = _optimum[cur + lenTest];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur;
optimum.BackPrev = curBack + Base.kNumRepDistances;
optimum.Prev1IsChar = false;
}
if (lenTest == _matchDistances[offs])
{
if (lenTest < numAvailableBytesFull)
{
UInt32 t = Math.Min(numAvailableBytesFull - 1 - lenTest, _numFastBytes);
UInt32 lenTest2 = _matchFinder.GetMatchLen((Int32)lenTest, curBack, t);
if (lenTest2 >= 2)
{
Base.State state2 = state;
state2.UpdateMatch();
UInt32 posStateNext = (position + lenTest) & _posStateMask;
UInt32 curAndLenCharPrice = curAndLenPrice +
_isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice0() +
_literalEncoder.GetSubCoder(position + lenTest,
_matchFinder.GetIndexByte((Int32)lenTest - 1 - 1)).
GetPrice(true,
_matchFinder.GetIndexByte((Int32)lenTest - (Int32)(curBack + 1) - 1),
_matchFinder.GetIndexByte((Int32)lenTest - 1));
state2.UpdateChar();
posStateNext = (position + lenTest + 1) & _posStateMask;
UInt32 nextMatchPrice = curAndLenCharPrice + _isMatch[(state2.Index << Base.kNumPosStatesBitsMax) + posStateNext].GetPrice1();
UInt32 nextRepMatchPrice = nextMatchPrice + _isRep[state2.Index].GetPrice1();
UInt32 offset = lenTest + 1 + lenTest2;
while (lenEnd < cur + offset)
_optimum[++lenEnd].Price = kIfinityPrice;
curAndLenPrice = nextRepMatchPrice + GetRepPrice(0, lenTest2, state2, posStateNext);
optimum = _optimum[cur + offset];
if (curAndLenPrice < optimum.Price)
{
optimum.Price = curAndLenPrice;
optimum.PosPrev = cur + lenTest + 1;
optimum.BackPrev = 0;
optimum.Prev1IsChar = true;
optimum.Prev2 = true;
optimum.PosPrev2 = cur;
optimum.BackPrev2 = curBack + Base.kNumRepDistances;
}
}
}
offs += 2;
if (offs == numDistancePairs)
break;
}
}
}
}
}
bool ChangePair(UInt32 smallDist, UInt32 bigDist)
{
const int kDif = 7;
return (smallDist < ((UInt32)(1) << (32 - kDif)) && bigDist >= (smallDist << kDif));
}
void WriteEndMarker(UInt32 posState)
{
if (!_writeEndMark)
return;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 1);
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
UInt32 len = Base.kMatchMinLen;
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
UInt32 posSlot = (1 << Base.kNumPosSlotBits) - 1;
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
int footerBits = 30;
UInt32 posReduced = (((UInt32)1) << footerBits) - 1;
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
}
void Flush(UInt32 nowPos)
{
ReleaseMFStream();
WriteEndMarker(nowPos & _posStateMask);
_rangeEncoder.FlushData();
_rangeEncoder.FlushStream();
}
public void CodeOneBlock(out Int64 inSize, out Int64 outSize, out bool finished)
{
inSize = 0;
outSize = 0;
finished = true;
if (_inStream != null)
{
_matchFinder.SetStream(_inStream);
_matchFinder.Init();
_needReleaseMFStream = true;
_inStream = null;
if (_trainSize > 0)
_matchFinder.Skip(_trainSize);
}
if (_finished)
return;
_finished = true;
Int64 progressPosValuePrev = nowPos64;
if (nowPos64 == 0)
{
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
UInt32 len, numDistancePairs; // it's not used
ReadMatchDistances(out len, out numDistancePairs);
UInt32 posState = (UInt32)(nowPos64) & _posStateMask;
_isMatch[(_state.Index << Base.kNumPosStatesBitsMax) + posState].Encode(_rangeEncoder, 0);
_state.UpdateChar();
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
_literalEncoder.GetSubCoder((UInt32)(nowPos64), _previousByte).Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_additionalOffset--;
nowPos64++;
}
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
while (true)
{
UInt32 pos;
UInt32 len = GetOptimum((UInt32)nowPos64, out pos);
UInt32 posState = ((UInt32)nowPos64) & _posStateMask;
UInt32 complexState = (_state.Index << Base.kNumPosStatesBitsMax) + posState;
if (len == 1 && pos == 0xFFFFFFFF)
{
_isMatch[complexState].Encode(_rangeEncoder, 0);
Byte curByte = _matchFinder.GetIndexByte((Int32)(0 - _additionalOffset));
LiteralEncoder.Encoder2 subCoder = _literalEncoder.GetSubCoder((UInt32)nowPos64, _previousByte);
if (!_state.IsCharState())
{
Byte matchByte = _matchFinder.GetIndexByte((Int32)(0 - _repDistances[0] - 1 - _additionalOffset));
subCoder.EncodeMatched(_rangeEncoder, matchByte, curByte);
}
else
subCoder.Encode(_rangeEncoder, curByte);
_previousByte = curByte;
_state.UpdateChar();
}
else
{
_isMatch[complexState].Encode(_rangeEncoder, 1);
if (pos < Base.kNumRepDistances)
{
_isRep[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 0)
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 0);
if (len == 1)
_isRep0Long[complexState].Encode(_rangeEncoder, 0);
else
_isRep0Long[complexState].Encode(_rangeEncoder, 1);
}
else
{
_isRepG0[_state.Index].Encode(_rangeEncoder, 1);
if (pos == 1)
_isRepG1[_state.Index].Encode(_rangeEncoder, 0);
else
{
_isRepG1[_state.Index].Encode(_rangeEncoder, 1);
_isRepG2[_state.Index].Encode(_rangeEncoder, pos - 2);
}
}
if (len == 1)
_state.UpdateShortRep();
else
{
_repMatchLenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
_state.UpdateRep();
}
UInt32 distance = _repDistances[pos];
if (pos != 0)
{
for (UInt32 i = pos; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
}
}
else
{
_isRep[_state.Index].Encode(_rangeEncoder, 0);
_state.UpdateMatch();
_lenEncoder.Encode(_rangeEncoder, len - Base.kMatchMinLen, posState);
pos -= Base.kNumRepDistances;
UInt32 posSlot = GetPosSlot(pos);
UInt32 lenToPosState = Base.GetLenToPosState(len);
_posSlotEncoder[lenToPosState].Encode(_rangeEncoder, posSlot);
if (posSlot >= Base.kStartPosModelIndex)
{
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
UInt32 posReduced = pos - baseVal;
if (posSlot < Base.kEndPosModelIndex)
RangeCoder.BitTreeEncoder.ReverseEncode(_posEncoders,
baseVal - posSlot - 1, _rangeEncoder, footerBits, posReduced);
else
{
_rangeEncoder.EncodeDirectBits(posReduced >> Base.kNumAlignBits, footerBits - Base.kNumAlignBits);
_posAlignEncoder.ReverseEncode(_rangeEncoder, posReduced & Base.kAlignMask);
_alignPriceCount++;
}
}
UInt32 distance = pos;
for (UInt32 i = Base.kNumRepDistances - 1; i >= 1; i--)
_repDistances[i] = _repDistances[i - 1];
_repDistances[0] = distance;
_matchPriceCount++;
}
_previousByte = _matchFinder.GetIndexByte((Int32)(len - 1 - _additionalOffset));
}
_additionalOffset -= len;
nowPos64 += len;
if (_additionalOffset == 0)
{
// if (!_fastMode)
if (_matchPriceCount >= (1 << 7))
FillDistancesPrices();
if (_alignPriceCount >= Base.kAlignTableSize)
FillAlignPrices();
inSize = nowPos64;
outSize = _rangeEncoder.GetProcessedSizeAdd();
if (_matchFinder.GetNumAvailableBytes() == 0)
{
Flush((UInt32)nowPos64);
return;
}
if (nowPos64 - progressPosValuePrev >= (1 << 12))
{
_finished = false;
finished = false;
return;
}
}
}
}
void ReleaseMFStream()
{
if (_matchFinder != null && _needReleaseMFStream)
{
_matchFinder.ReleaseStream();
_needReleaseMFStream = false;
}
}
void SetOutStream(System.IO.Stream outStream) { _rangeEncoder.SetStream(outStream); }
void ReleaseOutStream() { _rangeEncoder.ReleaseStream(); }
void ReleaseStreams()
{
ReleaseMFStream();
ReleaseOutStream();
}
void SetStreams(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize)
{
_inStream = inStream;
_finished = false;
Create();
SetOutStream(outStream);
Init();
// if (!_fastMode)
{
FillDistancesPrices();
FillAlignPrices();
}
_lenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_lenEncoder.UpdateTables((UInt32)1 << _posStateBits);
_repMatchLenEncoder.SetTableSize(_numFastBytes + 1 - Base.kMatchMinLen);
_repMatchLenEncoder.UpdateTables((UInt32)1 << _posStateBits);
nowPos64 = 0;
}
public void Code(System.IO.Stream inStream, System.IO.Stream outStream,
Int64 inSize, Int64 outSize, ICodeProgress progress)
{
_needReleaseMFStream = false;
try
{
SetStreams(inStream, outStream, inSize, outSize);
while (true)
{
Int64 processedInSize;
Int64 processedOutSize;
bool finished;
CodeOneBlock(out processedInSize, out processedOutSize, out finished);
if (finished)
return;
if (progress != null)
{
progress.SetProgress(processedInSize, processedOutSize);
}
}
}
finally
{
ReleaseStreams();
}
}
const int kPropSize = 5;
Byte[] properties = new Byte[kPropSize];
public void WriteCoderProperties(System.IO.Stream outStream)
{
properties[0] = (Byte)((_posStateBits * 5 + _numLiteralPosStateBits) * 9 + _numLiteralContextBits);
for (int i = 0; i < 4; i++)
properties[1 + i] = (Byte)((_dictionarySize >> (8 * i)) & 0xFF);
outStream.Write(properties, 0, kPropSize);
}
UInt32[] tempPrices = new UInt32[Base.kNumFullDistances];
UInt32 _matchPriceCount;
void FillDistancesPrices()
{
for (UInt32 i = Base.kStartPosModelIndex; i < Base.kNumFullDistances; i++)
{
UInt32 posSlot = GetPosSlot(i);
int footerBits = (int)((posSlot >> 1) - 1);
UInt32 baseVal = ((2 | (posSlot & 1)) << footerBits);
tempPrices[i] = BitTreeEncoder.ReverseGetPrice(_posEncoders,
baseVal - posSlot - 1, footerBits, i - baseVal);
}
for (UInt32 lenToPosState = 0; lenToPosState < Base.kNumLenToPosStates; lenToPosState++)
{
UInt32 posSlot;
RangeCoder.BitTreeEncoder encoder = _posSlotEncoder[lenToPosState];
UInt32 st = (lenToPosState << Base.kNumPosSlotBits);
for (posSlot = 0; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] = encoder.GetPrice(posSlot);
for (posSlot = Base.kEndPosModelIndex; posSlot < _distTableSize; posSlot++)
_posSlotPrices[st + posSlot] += ((((posSlot >> 1) - 1) - Base.kNumAlignBits) << RangeCoder.BitEncoder.kNumBitPriceShiftBits);
UInt32 st2 = lenToPosState * Base.kNumFullDistances;
UInt32 i;
for (i = 0; i < Base.kStartPosModelIndex; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + i];
for (; i < Base.kNumFullDistances; i++)
_distancesPrices[st2 + i] = _posSlotPrices[st + GetPosSlot(i)] + tempPrices[i];
}
_matchPriceCount = 0;
}
void FillAlignPrices()
{
for (UInt32 i = 0; i < Base.kAlignTableSize; i++)
_alignPrices[i] = _posAlignEncoder.ReverseGetPrice(i);
_alignPriceCount = 0;
}
static string[] kMatchFinderIDs =
{
"BT2",
"BT4",
};
static int FindMatchFinder(string s)
{
for (int m = 0; m < kMatchFinderIDs.Length; m++)
if (s == kMatchFinderIDs[m])
return m;
return -1;
}
public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
{
for (UInt32 i = 0; i < properties.Length; i++)
{
object prop = properties[i];
switch (propIDs[i])
{
case CoderPropID.NumFastBytes:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 numFastBytes = (Int32)prop;
if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen)
throw new InvalidParamException();
_numFastBytes = (UInt32)numFastBytes;
break;
}
case CoderPropID.Algorithm:
{
/*
if (!(prop is Int32))
throw new InvalidParamException();
Int32 maximize = (Int32)prop;
_fastMode = (maximize == 0);
_maxMode = (maximize >= 2);
*/
break;
}
case CoderPropID.MatchFinder:
{
if (!(prop is String))
throw new InvalidParamException();
EMatchFinderType matchFinderIndexPrev = _matchFinderType;
int m = FindMatchFinder(((string)prop).ToUpper());
if (m < 0)
throw new InvalidParamException();
_matchFinderType = (EMatchFinderType)m;
if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType)
{
_dictionarySizePrev = 0xFFFFFFFF;
_matchFinder = null;
}
break;
}
case CoderPropID.DictionarySize:
{
const int kDicLogSizeMaxCompress = 30;
if (!(prop is Int32))
throw new InvalidParamException(); ;
Int32 dictionarySize = (Int32)prop;
if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) ||
dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress))
throw new InvalidParamException();
_dictionarySize = (UInt32)dictionarySize;
int dicLogSize;
for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++)
if (dictionarySize <= ((UInt32)(1) << dicLogSize))
break;
_distTableSize = (UInt32)dicLogSize * 2;
break;
}
case CoderPropID.PosStateBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax)
throw new InvalidParamException();
_posStateBits = (int)v;
_posStateMask = (((UInt32)1) << (int)_posStateBits) - 1;
break;
}
case CoderPropID.LitPosBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax)
throw new InvalidParamException();
_numLiteralPosStateBits = (int)v;
break;
}
case CoderPropID.LitContextBits:
{
if (!(prop is Int32))
throw new InvalidParamException();
Int32 v = (Int32)prop;
if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax)
throw new InvalidParamException(); ;
_numLiteralContextBits = (int)v;
break;
}
case CoderPropID.EndMarker:
{
if (!(prop is Boolean))
throw new InvalidParamException();
SetWriteEndMarkerMode((Boolean)prop);
break;
}
default:
throw new InvalidParamException();
}
}
}
uint _trainSize = 0;
public void SetTrainSize(uint trainSize)
{
_trainSize = trainSize;
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="TransferScheduler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//-----------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.DataMovement
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.DataMovement.TransferControllers;
using Microsoft.Azure.Storage.File;
/// <summary>
/// TransferScheduler class, used for transferring Microsoft Azure
/// Storage objects.
/// </summary>
internal sealed class TransferScheduler : IDisposable
{
/// <summary>
/// Main collection of transfer controllers.
/// </summary>
private BlockingCollection<ITransferController> controllerQueue;
/// <summary>
/// Internal queue for the main controllers collection.
/// </summary>
private ConcurrentQueue<ITransferController> internalControllerQueue;
/// <summary>
/// A buffer from which we select a transfer controller and add it into
/// active tasks when the bucket of active tasks is not full.
/// </summary>
private ConcurrentDictionary<ITransferController, object> activeControllerItems =
new ConcurrentDictionary<ITransferController, object>();
/// <summary>
/// Active controller item count used to help activeControllerItems statistics.
/// </summary>
private long activeControllerItemCount = 0;
/// <summary>
/// Active controller item prefetch ratio, used to set how much controller item could be prefetched during scheduling controllers.
/// </summary>
private const double ActiveControllerItemPrefetchRatio = 1.2; // TODO: further tune the prefetch ratio.
/// <summary>
/// Max active controller item count used to limit candidate controller items to be scheduled in parallel.
/// Note: ParallelOperations could be changing.
/// </summary>
private static int MaxActiveControllerItemCount => (int)(TransferManager.Configurations.ParallelOperations * ActiveControllerItemPrefetchRatio);
/// <summary>
/// Ongoing task used to control ongoing tasks dispatching.
/// </summary>
private int ongoingTasks;
/// <summary>
/// Ongoing task sempahore used to help ongoing task dispatching.
/// </summary>
private ManualResetEventSlim ongoingTaskEvent;
/// <summary>
/// Max controller work items count to schedule per scheduling round.
/// </summary>
private const int MaxControllerItemCountToScheduleEachRound = 100;
/// <summary>
/// CancellationToken source.
/// </summary>
private CancellationTokenSource cancellationTokenSource =
new CancellationTokenSource();
/// <summary>
/// Transfer options that this manager will pass to transfer controllers.
/// </summary>
private TransferConfigurations transferOptions;
/// <summary>
/// Wait handle event for completion.
/// </summary>
private ManualResetEventSlim controllerResetEvent =
new ManualResetEventSlim();
/// <summary>
/// A pool of memory buffer objects, used to limit total consumed memory.
/// </summary>
private MemoryManager memoryManager;
/// <summary>
/// Random object to generate random numbers.
/// </summary>
private Random randomGenerator;
/// <summary>
/// Used to lock disposing to avoid race condition between different disposing and other method calls.
/// </summary>
private object disposeLock = new object();
/// <summary>
/// Indicate whether the instance has been disposed.
/// </summary>
private bool isDisposed = false;
/// <summary>
/// Initializes a new instance of the
/// <see cref="TransferScheduler" /> class.
/// </summary>
public TransferScheduler()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="TransferScheduler" /> class.
/// </summary>
/// <param name="options">BlobTransfer options.</param>
public TransferScheduler(TransferConfigurations options)
{
// If no options specified create a default one.
this.transferOptions = options ?? new TransferConfigurations();
this.internalControllerQueue = new ConcurrentQueue<ITransferController>();
this.controllerQueue = new BlockingCollection<ITransferController>(
this.internalControllerQueue);
this.memoryManager = new MemoryManager(
this.transferOptions.MaximumCacheSize,
this.transferOptions.MemoryChunkSize);
this.randomGenerator = new Random();
this.ongoingTasks = 0;
this.ongoingTaskEvent = new ManualResetEventSlim(false);
this.StartSchedule();
}
/// <summary>
/// Finalizes an instance of the
/// <see cref="TransferScheduler" /> class.
/// </summary>
~TransferScheduler()
{
this.Dispose(false);
}
/// <summary>
/// Gets the transfer options that this manager will pass to
/// transfer controllers.
/// </summary>
internal TransferConfigurations TransferOptions => this.transferOptions;
internal CancellationTokenSource CancellationTokenSource => this.cancellationTokenSource;
internal MemoryManager MemoryManager => this.memoryManager;
/// <summary>
/// Public dispose method to release all resources owned.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Execute a transfer job asynchronously.
/// </summary>
/// <param name="job">Transfer job to be executed.</param>
/// <param name="cancellationToken">Token used to notify the job that it should stop.</param>
public Task ExecuteJobAsync(
TransferJob job,
CancellationToken cancellationToken)
{
if (null == job)
{
throw new ArgumentNullException(nameof(job));
}
lock (this.disposeLock)
{
this.CheckDisposed();
return this.ExecuteJobInternalAsync(job, cancellationToken);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Instances will be disposed in other place.")]
private async Task ExecuteJobInternalAsync(
TransferJob job,
CancellationToken cancellationToken)
{
Debug.Assert(
job.Status == TransferJobStatus.NotStarted ||
job.Status == TransferJobStatus.SkippedDueToShouldNotTransfer ||
job.Status == TransferJobStatus.Monitor ||
job.Status == TransferJobStatus.Transfer);
if (job.Status == TransferJobStatus.SkippedDueToShouldNotTransfer)
{
return;
}
TransferControllerBase controller = GenerateTransferConstroller(this, job, cancellationToken);
Utils.CheckCancellation(this.cancellationTokenSource.Token);
this.controllerQueue.Add(controller, this.cancellationTokenSource.Token);
try
{
await controller.TaskCompletionSource.Task;
}
#if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION
catch (Exception ex) when (ex is StorageException || (ex is AggregateException && ex.InnerException is StorageException))
{
var storageException = ex as StorageException ?? ex.InnerException as StorageException;
if (storageException.InnerException is OperationCanceledException)
{
throw storageException.InnerException;
}
throw new TransferException(TransferErrorCode.Unknown,
Resources.UncategorizedException,
storageException);
}
#else
catch (StorageException se)
{
throw new TransferException(
TransferErrorCode.Unknown,
Resources.UncategorizedException,
se);
}
#endif
finally
{
controller.Dispose();
}
}
private void FillInQueue(
ConcurrentDictionary<ITransferController, object> activeItems,
BlockingCollection<ITransferController> collection,
CancellationToken token)
{
while (!token.IsCancellationRequested
&& Interlocked.Read(ref this.activeControllerItemCount) < MaxActiveControllerItemCount)
{
ITransferController transferItem = null;
try
{
if (this.activeControllerItemCount <= 0)
{
transferItem = collection.Take(this.cancellationTokenSource.Token);
if (null == transferItem)
{
return;
}
}
else
{
if (!collection.TryTake(out transferItem)
|| null == transferItem)
{
return;
}
}
}
catch (OperationCanceledException)
{
return;
}
catch (InvalidOperationException)
{
// This kind of exception will be thrown when the BlockingCollection is marked as complete for adding, or is disposed.
return;
}
if (activeItems.TryAdd(transferItem, null))
{
Interlocked.Increment(ref this.activeControllerItemCount);
}
}
}
/// <summary>
/// Blocks until the queue is empty and all transfers have been
/// completed.
/// </summary>
private void WaitForCompletion()
{
this.controllerResetEvent.Wait();
}
/// <summary>
/// Cancels any remaining queued work.
/// </summary>
private void CancelWork()
{
this.cancellationTokenSource.Cancel();
this.controllerQueue.CompleteAdding();
// Move following to Cancel method.
// there might be running "work" when the transfer is cancelled.
// wait until all running "work" is done.
SpinWait sw = new SpinWait();
while (this.ongoingTasks != 0)
{
sw.SpinOnce();
}
this.controllerResetEvent.Set();
}
/// <summary>
/// Private dispose method to release managed/unmanaged objects.
/// If disposing is true clean up managed resources as well as
/// unmanaged resources.
/// If disposing is false only clean up unmanaged resources.
/// </summary>
/// <param name="disposing">Indicates whether or not to dispose
/// managed resources.</param>
private void Dispose(bool disposing)
{
if (!this.isDisposed)
{
lock (this.disposeLock)
{
// We got the lock, isDisposed is true, means that the disposing has been finished.
if (this.isDisposed)
{
return;
}
this.isDisposed = true;
this.CancelWork();
this.WaitForCompletion();
if (disposing)
{
if (null != this.controllerQueue)
{
this.controllerQueue.Dispose();
this.controllerQueue = null;
}
if (null != this.cancellationTokenSource)
{
this.cancellationTokenSource.Dispose();
this.cancellationTokenSource = null;
}
if (null != this.controllerResetEvent)
{
this.controllerResetEvent.Dispose();
this.controllerResetEvent = null;
}
if (null != this.ongoingTaskEvent)
{
this.ongoingTaskEvent.Dispose();
this.ongoingTaskEvent = null;
}
this.memoryManager = null;
}
}
}
else
{
this.WaitForCompletion();
}
}
private void CheckDisposed()
{
if (this.isDisposed)
{
throw new ObjectDisposedException("TransferScheduler");
}
}
private void StartSchedule()
{
Task.Run(() =>
{
SpinWait sw = new SpinWait();
while (!this.cancellationTokenSource.Token.IsCancellationRequested &&
(!this.controllerQueue.IsCompleted || Interlocked.Read(ref this.activeControllerItemCount) != 0))
{
this.FillInQueue(
this.activeControllerItems,
this.controllerQueue,
this.cancellationTokenSource.Token);
if (!this.cancellationTokenSource.Token.IsCancellationRequested)
{
// If we don't have the requested amount of active tasks
// running, get a task item from any active transfer item
// that has work available.
if (!this.DoWorkFrom(this.activeControllerItems))
{
sw.SpinOnce();
}
else
{
sw.Reset();
continue;
}
}
}
});
}
private void FinishedWorkItem(
ITransferController transferController)
{
object dummy;
if (this.activeControllerItems.TryRemove(transferController, out dummy))
{
Interlocked.Decrement(ref this.activeControllerItemCount);
}
}
private bool DoWorkFrom(
ConcurrentDictionary<ITransferController, object> activeItems)
{
// Filter items with work only.
// TODO: Optimize scheduling efficiency, get active items with LINQ cost a lot of time.
List<KeyValuePair<ITransferController, object>> activeItemsWithWork =
new List<KeyValuePair<ITransferController, object>>(
activeItems.Where(item => item.Key.HasWork && !item.Key.IsFinished));
int scheduledItemsCount = 0;
// In order to save time used to lock/search/addItem ConcurrentDictionary, try to schedule multipe items per DoWorkFrom round.
while (0 != activeItemsWithWork.Count
&& scheduledItemsCount < MaxControllerItemCountToScheduleEachRound)
{
// Select random item and get work delegate.
int idx = this.randomGenerator.Next(activeItemsWithWork.Count);
ITransferController transferController = activeItemsWithWork[idx].Key;
var scheduledOneItem = false;
while (!scheduledOneItem)
{
// Note: TransferManager.Configurations.ParallelOperations could be a changing value.
if (Interlocked.Increment(ref this.ongoingTasks) <= TransferManager.Configurations.ParallelOperations)
{
// Note: This is the only place where ongoing task could be scheduled.
this.DoControllerWork(transferController);
scheduledItemsCount++;
activeItemsWithWork.RemoveAt(idx);
scheduledOneItem = true;
}
else
{
Interlocked.Decrement(ref this.ongoingTasks);
this.ongoingTaskEvent.Wait();
this.ongoingTaskEvent.Reset();
}
}
}
if (scheduledItemsCount > 0)
{
return true;
}
else
{
return false;
}
}
private async void DoControllerWork(ITransferController controller)
{
bool finished = false;
try
{
finished = await controller.DoWorkAsync();
}
finally
{
Interlocked.Decrement(ref this.ongoingTasks);
this.ongoingTaskEvent.Set();
}
if (finished)
{
this.FinishedWorkItem(controller);
}
}
private static TransferControllerBase GenerateTransferConstroller(
TransferScheduler transferScheduler,
TransferJob transferJob,
CancellationToken cancellationToken)
{
TransferControllerBase controller = null;
switch (transferJob.Transfer.TransferMethod)
{
case TransferMethod.SyncCopy:
controller = new SyncTransferController(transferScheduler, transferJob, cancellationToken);
break;
case TransferMethod.ServiceSideAsyncCopy:
controller = CreateAsyncCopyController(transferScheduler, transferJob, cancellationToken);
break;
case TransferMethod.ServiceSideSyncCopy:
controller = CreateServiceSideSyncCopyConstroller(transferScheduler, transferJob, cancellationToken);
break;
case TransferMethod.DummyCopy:
controller = new DummyTransferController(transferScheduler, transferJob, cancellationToken);
break;
}
return controller;
}
private static ServiceSideSyncCopyController CreateServiceSideSyncCopyConstroller(
TransferScheduler transferScheduler,
TransferJob transferJob,
CancellationToken cancellationToken)
{
CloudBlob destinationBlob = transferJob.Destination.Instance as CloudBlob;
if (null != destinationBlob)
{
if (BlobType.PageBlob == destinationBlob.BlobType)
{
return new PageBlobServiceSideSyncCopyController(transferScheduler, transferJob, cancellationToken);
}
else if (BlobType.AppendBlob == destinationBlob.BlobType)
{
return new AppendBlobServiceSideSyncCopyController(transferScheduler, transferJob, cancellationToken);
}
else if (BlobType.BlockBlob == destinationBlob.BlobType)
{
return new BlockBlobServiceSideSyncCopyController(transferScheduler, transferJob, cancellationToken);
}
else
{
throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.NotSupportedBlobType, destinationBlob.BlobType));
}
}
else
{
CloudFile destinationFile = transferJob.Destination.Instance as CloudFile;
if (null != destinationFile)
{
return new FileServiceSideSyncCopyController(transferScheduler, transferJob, cancellationToken);
}
else
{
throw new TransferException(Resources.ServiceSideSyncCopyNotSupportException);
}
}
}
private static AsyncCopyController CreateAsyncCopyController(TransferScheduler transferScheduler, TransferJob transferJob, CancellationToken cancellationToken)
{
if (transferJob.Destination.Type == TransferLocationType.AzureFile)
{
return new FileAsyncCopyController(transferScheduler, transferJob, cancellationToken);
}
if (transferJob.Destination.Type == TransferLocationType.AzureBlob)
{
return new BlobAsyncCopyController(transferScheduler, transferJob, cancellationToken);
}
throw new InvalidOperationException(Resources.CanOnlyCopyToFileOrBlobException);
}
}
}
| |
using System;
using System.Threading;
using SDRSharp.Radio.PortAudio;
namespace SDRSharp.Radio
{
public unsafe delegate void BufferNeededDelegate(Complex* iqBuffer, float* audioBuffer, int length);
public unsafe sealed class StreamControl : IDisposable
{
private enum InputType
{
SoundCard,
Plugin,
WaveFile
}
private const int WaveBufferSize = 64 * 1024;
private const int MaxDecimationFactor = 1024;
private static readonly int _processorCount = Environment.ProcessorCount;
private static readonly int _minOutputSampleRate = Utils.GetIntSetting("minOutputSampleRate", 24000);
private float* _dspOutPtr;
private UnsafeBuffer _dspOutBuffer;
private Complex* _iqInPtr;
private UnsafeBuffer _iqInBuffer;
private Complex* _dspInPtr;
private UnsafeBuffer _dspInBuffer;
private WavePlayer _wavePlayer;
private WaveRecorder _waveRecorder;
private WaveDuplex _waveDuplex;
private WaveFile _waveFile;
private ComplexFifoStream _iqStream;
private FloatFifoStream _audioStream;
private Thread _waveReadThread;
private Thread _dspThread;
private float _audioGain;
private float _outputGain;
private int _inputDevice;
private double _inputSampleRate;
private int _inputBufferSize;
private int _bufferSizeInMs;
private int _outputDevice;
private double _outputSampleRate;
private int _outputBufferSize;
private int _decimationStageCount;
private bool _swapIQ;
private InputType _inputType;
private IFrontendController _frontend;
public event BufferNeededDelegate BufferNeeded;
public StreamControl()
{
AudioGain = 10.0f;
ScaleOutput = true;
}
~StreamControl()
{
Dispose();
}
public void Dispose()
{
Stop();
GC.SuppressFinalize(this);
}
public float AudioGain
{
get
{
return _audioGain;
}
set
{
_audioGain = value;
_outputGain = (float) Math.Pow(value / 10.0, 10);
}
}
public bool ScaleOutput { get; set; }
public bool SwapIQ
{
get
{
return _swapIQ;
}
set
{
_swapIQ = value;
}
}
public double SampleRate
{
get
{
return _inputSampleRate;
}
}
public bool IsPlaying
{
get
{
return _inputSampleRate != 0;
}
}
public int BufferSize
{
get
{
return _inputBufferSize;
}
}
public int BufferSizeInMs
{
get
{
return _bufferSizeInMs;
}
}
public int DecimationStageCount
{
get
{
return _decimationStageCount;
}
}
private void DuplexFiller(float* buffer, int frameCount)
{
#region Prepare buffers
if (_dspInBuffer == null || _dspInBuffer.Length != frameCount)
{
_dspInBuffer = UnsafeBuffer.Create(frameCount, sizeof(Complex));
_dspInPtr = (Complex*) _dspInBuffer;
}
if (_dspOutBuffer == null || _dspOutBuffer.Length != _dspInBuffer.Length * 2)
{
_dspOutBuffer = UnsafeBuffer.Create(_dspInBuffer.Length * 2, sizeof(float));
_dspOutPtr = (float*) _dspOutBuffer;
}
#endregion
Utils.Memcpy(_dspInPtr, buffer, frameCount * sizeof(Complex));
ProcessIQ();
ScaleBuffer(_dspOutPtr, _dspOutBuffer.Length);
Utils.Memcpy(buffer, _dspOutPtr, _dspOutBuffer.Length * sizeof(float));
}
private void PlayerFiller(float* buffer, int frameCount)
{
var sampleCount = frameCount * 2;
var count = _audioStream.Read(buffer, sampleCount);
ScaleBuffer(buffer, count);
for (var i = count; i < sampleCount; i++)
{
buffer[i] = 0.0f;
}
}
private void RecorderFiller(float* buffer, int frameCount)
{
if (_iqStream.Length > _inputBufferSize * 2)
{
return;
}
#region Prepare buffer
if (_iqInBuffer == null || _iqInBuffer.Length != frameCount)
{
_iqInBuffer = UnsafeBuffer.Create(frameCount, sizeof(Complex));
_iqInPtr = (Complex*) _iqInBuffer;
}
#endregion
Utils.Memcpy(_iqInPtr, buffer, frameCount * sizeof(Complex));
_iqStream.Write(_iqInPtr, frameCount);
}
private void FrontendFiller(IFrontendController sender, Complex* samples, int len)
{
if (_iqStream.Length < _inputBufferSize * 4)
{
_iqStream.Write(samples, len);
}
}
private void WaveFileFiller()
{
var waveInBuffer = new Complex[WaveBufferSize];
fixed (Complex* waveInPtr = waveInBuffer)
{
while (IsPlaying)
{
if (_iqStream.Length < _inputBufferSize * 4)
{
_waveFile.Read(waveInPtr, waveInBuffer.Length);
_iqStream.Write(waveInPtr, waveInBuffer.Length);
}
else
{
Thread.Sleep(1);
}
}
}
}
private void ScaleBuffer(float* buffer, int length)
{
if (ScaleOutput)
{
for (var i = 0; i < length; i++)
{
buffer[i] *= _outputGain;
}
}
}
private void DSPProc()
{
#region Prepare buffers
if (_dspInBuffer == null || _dspInBuffer.Length != _inputBufferSize)
{
_dspInBuffer = UnsafeBuffer.Create(_inputBufferSize, sizeof(Complex));
_dspInPtr = (Complex*) _dspInBuffer;
}
if (_dspOutBuffer == null || _dspOutBuffer.Length != _outputBufferSize)
{
_dspOutBuffer = UnsafeBuffer.Create(_outputBufferSize, sizeof(float));
_dspOutPtr = (float*) _dspOutBuffer;
}
#endregion
while (IsPlaying)
{
var total = 0;
while (IsPlaying && total < _dspInBuffer.Length)
{
var len = _dspInBuffer.Length - total;
total += _iqStream.Read(_dspInPtr, total, len); // Blocking read
}
ProcessIQ();
_audioStream.Write(_dspOutPtr, _dspOutBuffer.Length); // Blocking write
}
}
private void ProcessIQ()
{
if (BufferNeeded != null)
{
if (_swapIQ)
{
SwapIQBuffer();
}
BufferNeeded(_dspInPtr, _dspOutPtr, _dspInBuffer.Length);
}
}
private void SwapIQBuffer()
{
for (var i = 0; i < _dspInBuffer.Length; i++)
{
var temp = _dspInPtr[i].Real;
_dspInPtr[i].Real = _dspInPtr[i].Imag;
_dspInPtr[i].Imag = temp;
}
}
public void Stop()
{
if (_inputType == InputType.Plugin && _frontend != null)
{
_frontend.Stop();
_frontend = null;
}
if (_wavePlayer != null)
{
_wavePlayer.Dispose();
_wavePlayer = null;
}
if (_waveRecorder != null)
{
_waveRecorder.Dispose();
_waveRecorder = null;
}
if (_waveDuplex != null)
{
_waveDuplex.Dispose();
_waveDuplex = null;
}
_inputSampleRate = 0;
if (_waveReadThread != null)
{
_waveReadThread.Join();
_waveReadThread = null;
}
if (_iqStream != null)
{
_iqStream.Close();
}
if (_audioStream != null)
{
_audioStream.Close();
}
if (_dspThread != null)
{
_dspThread.Join();
_dspThread = null;
}
if (_waveFile != null)
{
_waveFile.Dispose();
_waveFile = null;
}
if (_iqStream != null)
{
_iqStream.Dispose();
_iqStream = null;
}
_audioStream = null;
_dspOutBuffer = null;
_iqInBuffer = null;
}
public void Play()
{
if (_wavePlayer != null || _waveDuplex != null)
{
return;
}
switch (_inputType)
{
case InputType.SoundCard:
if (_inputDevice == _outputDevice)
{
_waveDuplex = new WaveDuplex(_inputDevice, _inputSampleRate, _inputBufferSize, DuplexFiller);
}
else
{
_iqStream = new ComplexFifoStream(BlockMode.BlockingRead);
_audioStream = new FloatFifoStream(BlockMode.BlockingWrite, _outputBufferSize);
_waveRecorder = new WaveRecorder(_inputDevice, _inputSampleRate, _inputBufferSize, RecorderFiller);
_wavePlayer = new WavePlayer(_outputDevice, _outputSampleRate, _outputBufferSize / 2, PlayerFiller);
_dspThread = new Thread(DSPProc);
_dspThread.Start();
}
break;
case InputType.WaveFile:
_iqStream = new ComplexFifoStream(BlockMode.BlockingRead);
_audioStream = new FloatFifoStream(BlockMode.BlockingWrite, _outputBufferSize);
_wavePlayer = new WavePlayer(_outputDevice, _outputSampleRate, _outputBufferSize / 2, PlayerFiller);
_waveReadThread = new Thread(WaveFileFiller);
_waveReadThread.Start();
_dspThread = new Thread(DSPProc);
_dspThread.Start();
break;
case InputType.Plugin:
_iqStream = new ComplexFifoStream(BlockMode.BlockingRead);
_audioStream = new FloatFifoStream(BlockMode.BlockingWrite, _outputBufferSize);
_wavePlayer = new WavePlayer(_outputDevice, _outputSampleRate, _outputBufferSize / 2, PlayerFiller);
_frontend.Start(FrontendFiller);
_dspThread = new Thread(DSPProc);
_dspThread.Start();
break;
}
}
public void OpenSoundDevice(int inputDevice, int outputDevice, double inputSampleRate, int bufferSizeInMs)
{
Stop();
_inputType = InputType.SoundCard;
_inputDevice = inputDevice;
_outputDevice = outputDevice;
_inputSampleRate = inputSampleRate;
_bufferSizeInMs = bufferSizeInMs;
_inputBufferSize = (int)(_bufferSizeInMs * _inputSampleRate / 1000);
if (_inputDevice == _outputDevice)
{
_decimationStageCount = 0;
_outputSampleRate = _inputSampleRate;
_outputBufferSize = _inputBufferSize * 2;
}
else
{
_decimationStageCount = GetDecimationStageCount();
var decimationFactor = (int) Math.Pow(2.0, _decimationStageCount);
_inputBufferSize = _inputBufferSize / decimationFactor * decimationFactor;
_inputBufferSize = _inputBufferSize / _processorCount * _processorCount;
_bufferSizeInMs = (int) Math.Round(_inputBufferSize / _inputSampleRate * 1000);
_outputSampleRate = _inputSampleRate / decimationFactor;
_outputBufferSize = _inputBufferSize / decimationFactor * 2;
}
}
public void OpenFile(string filename, int outputDevice, int bufferSizeInMs)
{
Stop();
try
{
_inputType = InputType.WaveFile;
_waveFile = new WaveFile(filename);
_outputDevice = outputDevice;
_bufferSizeInMs = bufferSizeInMs;
_inputSampleRate = _waveFile.SampleRate;
_inputBufferSize = (int) (_bufferSizeInMs * _inputSampleRate / 1000);
_decimationStageCount = GetDecimationStageCount();
var decimationFactor = (int) Math.Pow(2.0, _decimationStageCount);
_inputBufferSize = _inputBufferSize / decimationFactor * decimationFactor;
_inputBufferSize = _inputBufferSize / _processorCount * _processorCount;
_bufferSizeInMs = (int) Math.Round(_inputBufferSize / _inputSampleRate * 1000);
_outputSampleRate = _inputSampleRate / decimationFactor;
_outputBufferSize = _inputBufferSize / decimationFactor * 2;
}
catch
{
Stop();
throw;
}
}
public void OpenPlugin(IFrontendController frontend, int outputDevice, int bufferSizeInMs)
{
Stop();
try
{
_inputType = InputType.Plugin;
_frontend = frontend;
_inputSampleRate = _frontend.Samplerate;
_outputDevice = outputDevice;
_bufferSizeInMs = bufferSizeInMs;
_inputBufferSize = (int) (_bufferSizeInMs * _inputSampleRate / 1000);
_decimationStageCount = GetDecimationStageCount();
var decimationFactor = (int) Math.Pow(2.0, _decimationStageCount);
_inputBufferSize = _inputBufferSize / decimationFactor * decimationFactor;
_inputBufferSize = _inputBufferSize / _processorCount * _processorCount;
_bufferSizeInMs = (int) Math.Round(_inputBufferSize / _inputSampleRate * 1000);
_outputSampleRate = _inputSampleRate / decimationFactor;
_outputBufferSize = _inputBufferSize / decimationFactor * 2;
}
catch
{
Stop();
throw;
}
}
private int GetDecimationStageCount()
{
if (_inputSampleRate <= _minOutputSampleRate)
{
return 0;
}
int result = MaxDecimationFactor;
while (_inputSampleRate < _minOutputSampleRate * result && result > 0)
{
result /= 2;
}
return (int) Math.Log(result, 2.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.Tests.Compute
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for exception handling on various task execution stages.
/// </summary>
public class IgniteExceptionTaskSelfTest : AbstractTaskTest
{
/** Error mode. */
private static ErrorMode _mode;
/** Observed job errors. */
private static readonly ICollection<Exception> JobErrs = new List<Exception>();
/// <summary>
/// Constructor.
/// </summary>
public IgniteExceptionTaskSelfTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected IgniteExceptionTaskSelfTest(bool fork) : base(fork) { }
/// <summary>
/// Test error occurred during map step.
/// </summary>
[Test]
public void TestMapError()
{
_mode = ErrorMode.MapErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.MapErr, e.Mode);
}
/// <summary>
/// Test not-marshalable error occurred during map step.
/// </summary>
[Test]
public void TestMapNotMarshalableError()
{
_mode = ErrorMode.MapErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.MapErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test task behavior when job produced by mapper is not marshalable.
/// </summary>
[Test]
public void TestMapNotMarshalableJob()
{
_mode = ErrorMode.MapJobNotMarshalable;
Assert.IsInstanceOf<BinaryObjectException>(ExecuteWithError());
}
/// <summary>
/// Test local job error.
/// </summary>
[Test]
public void TestLocalJobError()
{
_mode = ErrorMode.LocJobErr;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
var goodEx = JobErrs.First().InnerException as GoodException;
Assert.IsNotNull(goodEx);
Assert.AreEqual(ErrorMode.LocJobErr, goodEx.Mode);
}
/// <summary>
/// Test local not-marshalable job error.
/// </summary>
[Test]
public void TestLocalJobErrorNotMarshalable()
{
_mode = ErrorMode.LocJobErrNotMarshalable;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsInstanceOf<BadException>(JobErrs.First().InnerException); // Local job exception is not marshalled.
}
/// <summary>
/// Test local not-marshalable job result.
/// </summary>
[Test]
public void TestLocalJobResultNotMarshalable()
{
_mode = ErrorMode.LocJobResNotMarshalable;
int res = Execute();
Assert.AreEqual(2, res); // Local job result is not marshalled.
Assert.AreEqual(0, JobErrs.Count);
}
/// <summary>
/// Test remote job error.
/// </summary>
[Test]
public void TestRemoteJobError()
{
_mode = ErrorMode.RmtJobErr;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
var goodEx = JobErrs.First().InnerException as GoodException;
Assert.IsNotNull(goodEx);
Assert.AreEqual(ErrorMode.RmtJobErr, goodEx.Mode);
}
/// <summary>
/// Test remote not-marshalable job error.
/// </summary>
[Test]
public void TestRemoteJobErrorNotMarshalable()
{
_mode = ErrorMode.RmtJobErrNotMarshalable;
var ex = Assert.Throws<AggregateException>(() => Execute());
Assert.IsInstanceOf<SerializationException>(ex.InnerException);
}
/// <summary>
/// Test local not-marshalable job result.
/// </summary>
[Test]
public void TestRemoteJobResultNotMarshalable()
{
_mode = ErrorMode.RmtJobResNotMarshalable;
int res = Execute();
Assert.AreEqual(1, res);
Assert.AreEqual(4, JobErrs.Count);
Assert.IsNotNull(JobErrs.ElementAt(0) as IgniteException);
}
/// <summary>
/// Test local result error.
/// </summary>
[Test]
public void TestLocalResultError()
{
_mode = ErrorMode.LocResErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.LocResErr, e.Mode);
}
/// <summary>
/// Test local result not-marshalable error.
/// </summary>
[Test]
public void TestLocalResultErrorNotMarshalable()
{
_mode = ErrorMode.LocResErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.LocResErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test remote result error.
/// </summary>
[Test]
public void TestRemoteResultError()
{
_mode = ErrorMode.RmtResErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.RmtResErr, e.Mode);
}
/// <summary>
/// Test remote result not-marshalable error.
/// </summary>
[Test]
public void TestRemoteResultErrorNotMarshalable()
{
_mode = ErrorMode.RmtResErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.RmtResErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test reduce with error.
/// </summary>
[Test]
public void TestReduceError()
{
_mode = ErrorMode.ReduceErr;
GoodException e = ExecuteWithError() as GoodException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.ReduceErr, e.Mode);
}
/// <summary>
/// Test reduce with not-marshalable error.
/// </summary>
[Test]
public void TestReduceErrorNotMarshalable()
{
_mode = ErrorMode.ReduceErrNotMarshalable;
BadException e = ExecuteWithError() as BadException;
Assert.IsNotNull(e);
Assert.AreEqual(ErrorMode.ReduceErrNotMarshalable, e.Mode);
}
/// <summary>
/// Test reduce with not-marshalable result.
/// </summary>
[Test]
public void TestReduceResultNotMarshalable()
{
_mode = ErrorMode.ReduceResNotMarshalable;
int res = Execute();
Assert.AreEqual(2, res);
}
/// <summary>
/// Execute task successfully.
/// </summary>
/// <returns>Task result.</returns>
private int Execute()
{
JobErrs.Clear();
Func<object, int> getRes = r => r is GoodTaskResult ? ((GoodTaskResult) r).Res : ((BadTaskResult) r).Res;
var res1 = getRes(Grid1.GetCompute().Execute(new Task()));
var res2 = getRes(Grid1.GetCompute().Execute<object, object>(typeof(Task)));
var resAsync1 = getRes(Grid1.GetCompute().ExecuteAsync(new Task()).Result);
var resAsync2 = getRes(Grid1.GetCompute().ExecuteAsync<object, object>(typeof(Task)).Result);
Assert.AreEqual(res1, res2);
Assert.AreEqual(res2, resAsync1);
Assert.AreEqual(resAsync1, resAsync2);
return res1;
}
/// <summary>
/// Execute task with error.
/// </summary>
/// <returns>Task</returns>
private Exception ExecuteWithError()
{
JobErrs.Clear();
var ex = Assert.Throws<AggregateException>(() => Grid1.GetCompute().Execute(new Task()));
Assert.IsNotNull(ex.InnerException);
return ex.InnerException;
}
/// <summary>
/// Error modes.
/// </summary>
private enum ErrorMode
{
/** Error during map step. */
MapErr,
/** Error during map step which is not marshalable. */
MapErrNotMarshalable,
/** Job created by mapper is not marshalable. */
MapJobNotMarshalable,
/** Error occurred in local job. */
LocJobErr,
/** Error occurred in local job and is not marshalable. */
LocJobErrNotMarshalable,
/** Local job result is not marshalable. */
LocJobResNotMarshalable,
/** Error occurred in remote job. */
RmtJobErr,
/** Error occurred in remote job and is not marshalable. */
RmtJobErrNotMarshalable,
/** Remote job result is not marshalable. */
RmtJobResNotMarshalable,
/** Error occurred during local result processing. */
LocResErr,
/** Error occurred during local result processing and is not marshalable. */
LocResErrNotMarshalable,
/** Error occurred during remote result processing. */
RmtResErr,
/** Error occurred during remote result processing and is not marshalable. */
RmtResErrNotMarshalable,
/** Error during reduce step. */
ReduceErr,
/** Error during reduce step and is not marshalable. */
ReduceErrNotMarshalable,
/** Reduce result is not marshalable. */
ReduceResNotMarshalable
}
/// <summary>
/// Task.
/// </summary>
private class Task : IComputeTask<object, object>
{
/** Grid. */
[InstanceResource]
private readonly IIgnite _grid = null;
/** Result. */
private int _res;
/** <inheritDoc /> */
public IDictionary<IComputeJob<object>, IClusterNode> Map(IList<IClusterNode> subgrid, object arg)
{
switch (_mode)
{
case ErrorMode.MapErr:
throw new GoodException(ErrorMode.MapErr);
case ErrorMode.MapErrNotMarshalable:
throw new BadException(ErrorMode.MapErrNotMarshalable);
case ErrorMode.MapJobNotMarshalable:
{
var badJobs = new Dictionary<IComputeJob<object>, IClusterNode>();
foreach (IClusterNode node in subgrid)
badJobs.Add(new BadJob(), node);
return badJobs;
}
}
// Map completes sucessfully and we spread jobs to all nodes.
var jobs = new Dictionary<IComputeJob<object>, IClusterNode>();
foreach (IClusterNode node in subgrid)
jobs.Add(new GoodJob(!_grid.GetCluster().GetLocalNode().Id.Equals(node.Id)), node);
return jobs;
}
/** <inheritDoc /> */
public ComputeJobResultPolicy OnResult(IComputeJobResult<object> res, IList<IComputeJobResult<object>> rcvd)
{
if (res.Exception != null)
{
JobErrs.Add(res.Exception);
}
else
{
object res0 = res.Data;
var result = res0 as GoodJobResult;
bool rmt = result != null ? result.Rmt : ((BadJobResult) res0).Rmt;
if (rmt)
{
switch (_mode)
{
case ErrorMode.RmtResErr:
throw new GoodException(ErrorMode.RmtResErr);
case ErrorMode.RmtResErrNotMarshalable:
throw new BadException(ErrorMode.RmtResErrNotMarshalable);
}
}
else
{
switch (_mode)
{
case ErrorMode.LocResErr:
throw new GoodException(ErrorMode.LocResErr);
case ErrorMode.LocResErrNotMarshalable:
throw new BadException(ErrorMode.LocResErrNotMarshalable);
}
}
_res += 1;
}
return ComputeJobResultPolicy.Wait;
}
/** <inheritDoc /> */
public object Reduce(IList<IComputeJobResult<object>> results)
{
switch (_mode)
{
case ErrorMode.ReduceErr:
throw new GoodException(ErrorMode.ReduceErr);
case ErrorMode.ReduceErrNotMarshalable:
throw new BadException(ErrorMode.ReduceErrNotMarshalable);
case ErrorMode.ReduceResNotMarshalable:
return new BadTaskResult(_res);
}
return new GoodTaskResult(_res);
}
}
/// <summary>
///
/// </summary>
[Serializable]
private class GoodJob : IComputeJob<object>, ISerializable
{
/** Whether the job is remote. */
private readonly bool _rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public GoodJob(bool rmt)
{
_rmt = rmt;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodJob(SerializationInfo info, StreamingContext context)
{
_rmt = info.GetBoolean("rmt");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("rmt", _rmt);
}
/** <inheritDoc /> */
public object Execute()
{
if (_rmt)
{
switch (_mode)
{
case ErrorMode.RmtJobErr:
throw new GoodException(ErrorMode.RmtJobErr);
case ErrorMode.RmtJobErrNotMarshalable:
throw new BadException(ErrorMode.RmtJobErr);
case ErrorMode.RmtJobResNotMarshalable:
return new BadJobResult(_rmt);
}
}
else
{
switch (_mode)
{
case ErrorMode.LocJobErr:
throw new GoodException(ErrorMode.LocJobErr);
case ErrorMode.LocJobErrNotMarshalable:
throw new BadException(ErrorMode.LocJobErr);
case ErrorMode.LocJobResNotMarshalable:
return new BadJobResult(_rmt);
}
}
return new GoodJobResult(_rmt);
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
}
/// <summary>
///
/// </summary>
private class BadJob : IComputeJob<object>, IBinarizable
{
/** <inheritDoc /> */
public object Execute()
{
throw new NotImplementedException();
}
/** <inheritDoc /> */
public void Cancel()
{
// No-op.
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
///
/// </summary>
[Serializable]
private class GoodJobResult : ISerializable
{
/** */
public readonly bool Rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public GoodJobResult(bool rmt)
{
Rmt = rmt;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodJobResult(SerializationInfo info, StreamingContext context)
{
Rmt = info.GetBoolean("rmt");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("rmt", Rmt);
}
}
/// <summary>
///
/// </summary>
private class BadJobResult : IBinarizable
{
/** */
public readonly bool Rmt;
/// <summary>
///
/// </summary>
/// <param name="rmt"></param>
public BadJobResult(bool rmt)
{
Rmt = rmt;
}
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
///
/// </summary>
[Serializable]
private class GoodTaskResult : ISerializable
{
/** */
public readonly int Res;
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public GoodTaskResult(int res)
{
Res = res;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodTaskResult(SerializationInfo info, StreamingContext context)
{
Res = info.GetInt32("res");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("res", Res);
}
}
/// <summary>
///
/// </summary>
private class BadTaskResult
{
/** */
public readonly int Res;
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public BadTaskResult(int res)
{
Res = res;
}
}
/// <summary>
/// Marshalable exception.
/// </summary>
[Serializable]
private class GoodException : Exception
{
/** */
public readonly ErrorMode Mode;
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public GoodException(ErrorMode mode)
{
Mode = mode;
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected GoodException(SerializationInfo info, StreamingContext context)
{
Mode = (ErrorMode)info.GetInt32("mode");
}
/** <inheritDoc /> */
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("mode", (int)Mode);
base.GetObjectData(info, context);
}
}
/// <summary>
/// Not marshalable exception.
/// </summary>
private class BadException : Exception
{
/** */
public readonly ErrorMode Mode;
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
public BadException(ErrorMode mode)
{
Mode = mode;
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ContentTypeUtil.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
#if ASTORIA_CLIENT
namespace Microsoft.OData.Client
#else
namespace Microsoft.OData.Service
#endif
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
#if ASTORIA_CLIENT
using System.Net;
#endif
using Microsoft.OData.Core;
/// <summary>Provides helper methods for processing HTTP requests.</summary>
internal static class ContentTypeUtil
{
/// <summary>UTF-8 encoding, without the BOM preamble.</summary>
/// <remarks>
/// While a BOM preamble on UTF8 is generally benign, it seems that some MIME handlers under IE6 will not
/// process the payload correctly when included.
///
/// Because the data service should include the encoding as part of the Content-Type in the response,
/// there should be no ambiguity as to what encoding is being used.
///
/// For further information, see http://www.unicode.org/faq/utf_bom.html#BOM.
/// </remarks>
internal static readonly UTF8Encoding EncodingUtf8NoPreamble = new UTF8Encoding(false, true);
#if !ASTORIA_CLIENT
/// <summary>
/// Allowable Media Types for an Entity or Feed in V2.
/// </summary>
private static readonly string[] MediaTypesForEntityOrFeedV2 = new string[]
{
XmlConstants.MimeApplicationJson,
XmlConstants.MimeApplicationAtom,
};
/// <summary>
/// Allowable Media Types for something besides an Entity or Feed in V2.
/// </summary>
private static readonly string[] MediaTypesForOtherV2 = new string[]
{
XmlConstants.MimeApplicationJson,
XmlConstants.MimeApplicationXml,
XmlConstants.MimeTextXml,
};
/// <summary>
/// Allowable Media Types for Entities or Feeds in V3.
/// </summary>
private static readonly string[] MediaTypesForEntityOrFeedV3 = new string[]
{
XmlConstants.MimeApplicationJson,
XmlConstants.MimeApplicationAtom,
XmlConstants.MimeApplicationJsonODataMinimalMetadata,
XmlConstants.MimeApplicationJsonODataFullMetadata,
XmlConstants.MimeApplicationJsonODataNoMetadata,
};
/// <summary>
/// Allowable Media Types for something other than Entities or Feeds in V3.
/// </summary>
private static readonly string[] MediaTypesForOtherV3 = new string[]
{
XmlConstants.MimeApplicationJson,
XmlConstants.MimeApplicationXml,
XmlConstants.MimeTextXml,
XmlConstants.MimeApplicationJsonODataMinimalMetadata,
XmlConstants.MimeApplicationJsonODataFullMetadata,
XmlConstants.MimeApplicationJsonODataNoMetadata,
};
#endif
/// <summary>Encoding to fall back to an appropriate encoding is not available.</summary>
internal static Encoding FallbackEncoding
{
get
{
return EncodingUtf8NoPreamble;
}
}
/// <summary>Encoding implied by an unspecified encoding value.</summary>
/// <remarks>See http://tools.ietf.org/html/rfc2616#section-3.4.1 for details.</remarks>
private static Encoding MissingEncoding
{
get
{
#if PORTABLELIB // ISO-8859-1 not available
return Encoding.UTF8;
#else
return Encoding.GetEncoding("ISO-8859-1", new EncoderExceptionFallback(), new DecoderExceptionFallback());
#endif
}
}
#if !ASTORIA_CLIENT
/// <summary>Selects an acceptable MIME type that satisfies the Accepts header.</summary>
/// <param name="acceptTypesText">Text for Accepts header.</param>
/// <param name="availableTypes">
/// Types that the server is willing to return, in descending order
/// of preference.
/// </param>
/// <returns>The best MIME type for the client</returns>
internal static string SelectMimeType(string acceptTypesText, string[] availableTypes)
{
Debug.Assert(availableTypes != null, "acceptableTypes != null");
string selectedContentType = null;
int selectedMatchingParts = -1;
int selectedQualityValue = 0;
int selectedPreferenceIndex = Int32.MaxValue;
bool acceptable = false;
bool acceptTypesEmpty = true;
if (!String.IsNullOrEmpty(acceptTypesText))
{
IEnumerable<MediaType> acceptTypes = MimeTypesFromAcceptHeader(acceptTypesText);
foreach (MediaType acceptType in acceptTypes)
{
acceptTypesEmpty = false;
for (int i = 0; i < availableTypes.Length; i++)
{
string availableType = availableTypes[i];
int matchingParts = acceptType.GetMatchingParts(availableType);
if (matchingParts < 0)
{
continue;
}
if (matchingParts > selectedMatchingParts)
{
// A more specific type wins.
selectedContentType = availableType;
selectedMatchingParts = matchingParts;
selectedQualityValue = acceptType.SelectQualityValue();
selectedPreferenceIndex = i;
acceptable = selectedQualityValue != 0;
}
else if (matchingParts == selectedMatchingParts)
{
// A type with a higher q-value wins.
int candidateQualityValue = acceptType.SelectQualityValue();
if (candidateQualityValue > selectedQualityValue)
{
selectedContentType = availableType;
selectedQualityValue = candidateQualityValue;
selectedPreferenceIndex = i;
acceptable = selectedQualityValue != 0;
}
else if (candidateQualityValue == selectedQualityValue)
{
// A type that is earlier in the availableTypes array wins.
if (i < selectedPreferenceIndex)
{
selectedContentType = availableType;
selectedPreferenceIndex = i;
}
}
}
}
}
}
if (acceptTypesEmpty)
{
selectedContentType = availableTypes[0];
}
else if (!acceptable)
{
selectedContentType = null;
}
return selectedContentType;
}
/// <summary>Gets the appropriate MIME type for the request, throwing if there is none.</summary>
/// <param name='acceptTypesText'>Text as it appears in an HTTP Accepts header.</param>
/// <param name='exactContentType'>Preferred content type to match if an exact media type is given - this is in descending order of preference.</param>
/// <param name='inexactContentType'>Preferred fallback content type for inexact matches.</param>
/// <returns>One of exactContentType or inexactContentType.</returns>
internal static string SelectRequiredMimeType(
string acceptTypesText,
string[] exactContentType,
string inexactContentType)
{
Debug.Assert(exactContentType != null && exactContentType.Length != 0, "exactContentType != null && exactContentType.Length != 0");
Debug.Assert(inexactContentType != null, "inexactContentType != null");
string selectedContentType = null;
int selectedMatchingParts = -1;
int selectedQualityValue = 0;
bool acceptable = false;
bool acceptTypesEmpty = true;
bool foundExactMatch = false;
if (!String.IsNullOrEmpty(acceptTypesText))
{
IEnumerable<MediaType> acceptTypes = MimeTypesFromAcceptHeader(acceptTypesText);
foreach (MediaType acceptType in acceptTypes)
{
acceptTypesEmpty = false;
for (int i = 0; i < exactContentType.Length; i++)
{
if (CompareMimeType(acceptType.MimeType, exactContentType[i]))
{
selectedContentType = exactContentType[i];
selectedQualityValue = acceptType.SelectQualityValue();
acceptable = selectedQualityValue != 0;
foundExactMatch = true;
break;
}
}
if (foundExactMatch)
{
break;
}
int matchingParts = acceptType.GetMatchingParts(inexactContentType);
if (matchingParts < 0)
{
continue;
}
if (matchingParts > selectedMatchingParts)
{
// A more specific type wins.
selectedContentType = inexactContentType;
selectedMatchingParts = matchingParts;
selectedQualityValue = acceptType.SelectQualityValue();
acceptable = selectedQualityValue != 0;
}
else if (matchingParts == selectedMatchingParts)
{
// A type with a higher q-value wins.
int candidateQualityValue = acceptType.SelectQualityValue();
if (candidateQualityValue > selectedQualityValue)
{
selectedContentType = inexactContentType;
selectedQualityValue = candidateQualityValue;
acceptable = selectedQualityValue != 0;
}
}
}
}
if (!acceptable && !acceptTypesEmpty)
{
throw Error.HttpHeaderFailure(415, Strings.DataServiceException_UnsupportedMediaType);
}
if (acceptTypesEmpty)
{
Debug.Assert(selectedContentType == null, "selectedContentType == null - otherwise accept types were not empty");
selectedContentType = inexactContentType;
}
Debug.Assert(selectedContentType != null, "selectedContentType != null - otherwise no selection was made");
return selectedContentType;
}
/// <summary>Gets the best encoding available for the specified charset request.</summary>
/// <param name="acceptCharset">
/// The Accept-Charset header value (eg: "iso-8859-5, unicode-1-1;q=0.8").
/// </param>
/// <returns>An Encoding object appropriate to the specifed charset request.</returns>
internal static Encoding EncodingFromAcceptCharset(string acceptCharset)
{
// Determines the appropriate encoding mapping according to
// RFC 2616.14.2 (http://tools.ietf.org/html/rfc2616#section-14.2).
Encoding result = null;
if (!String.IsNullOrEmpty(acceptCharset))
{
// PERF: keep a cache of original strings to resolved Encoding.
List<CharsetPart> parts = new List<CharsetPart>(AcceptCharsetParts(acceptCharset));
parts.Sort((x, y) => y.Quality - x.Quality);
var encoderFallback = new EncoderExceptionFallback();
var decoderFallback = new DecoderExceptionFallback();
foreach (CharsetPart part in parts)
{
if (part.Quality > 0)
{
// When UTF-8 is specified, select the version that doesn't use the BOM.
if (String.Compare(XmlConstants.Utf8Encoding, part.Charset, StringComparison.OrdinalIgnoreCase) == 0)
{
result = FallbackEncoding;
break;
}
try
{
result = Encoding.GetEncoding(part.Charset, encoderFallback, decoderFallback);
break;
}
catch (ArgumentException)
{
// This exception is thrown when the character
// set isn't supported - it is ignored so
// other possible charsets are evaluated.
}
}
}
}
// No Charset was specifed, or if charsets were specified, no valid charset was found.
// Returning a different charset is also valid.
return result ?? FallbackEncoding;
}
/// <summary>
/// Selects a response format for the requestMessage's request and sets the appropriate response header.
/// </summary>
/// <param name="acceptTypesText">A comma-delimited list of client-supported MIME accept types.</param>
/// <param name="entityTarget">Whether the target is an entity.</param>
/// <param name="effectiveMaxResponseVersion">The effective max response version.</param>
/// <returns>The selected media type.</returns>
internal static string SelectResponseMediaType(string acceptTypesText, bool entityTarget, Version effectiveMaxResponseVersion)
{
string[] availableTypes = GetAvailableMediaTypes(effectiveMaxResponseVersion, entityTarget);
string contentType = SelectMimeType(acceptTypesText, availableTypes);
// never respond with just app/json
if (CompareMimeType(contentType, XmlConstants.MimeApplicationJson))
{
contentType = XmlConstants.MimeApplicationJsonODataMinimalMetadata;
}
return contentType;
}
/// <summary>
/// Does a ordinal ignore case comparision of the given mime types.
/// </summary>
/// <param name="mimeType1">mime type1.</param>
/// <param name="mimeType2">mime type2.</param>
/// <returns>returns true if the mime type are the same.</returns>
internal static bool CompareMimeType(string mimeType1, string mimeType2)
{
return String.Equals(mimeType1, mimeType2, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines whether the response media type would be JSON light for the given accept-header text.
/// </summary>
/// <param name="acceptTypesText">The text from the request's accept header.</param>
/// <param name="entityTarget">Whether the target is an entity.</param>
/// <param name="effectiveMaxResponseVersion">The effective max response version.</param>
/// <returns>True if the response type is Json Light.</returns>
internal static bool IsResponseMediaTypeJsonLight(string acceptTypesText, bool entityTarget, Version effectiveMaxResponseVersion)
{
string selectedMediaType;
try
{
selectedMediaType = SelectResponseMediaType(acceptTypesText, entityTarget, effectiveMaxResponseVersion);
}
catch (DataServiceException)
{
// The acceptTypesText does not contain a supported mime type.
selectedMediaType = null;
}
return string.Equals(XmlConstants.MimeApplicationJsonODataMinimalMetadata, selectedMediaType, StringComparison.OrdinalIgnoreCase)
|| string.Equals(XmlConstants.MimeApplicationJsonODataFullMetadata, selectedMediaType, StringComparison.OrdinalIgnoreCase)
|| string.Equals(XmlConstants.MimeApplicationJsonODataNoMetadata, selectedMediaType, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines whether the response media type would be JSON light for the request.
/// </summary>
/// <param name="dataService">The data service instance to determine the response media type.</param>
/// <param name="isEntryOrFeed">true if the target of the request is an entry or a feed, false otherwise.</param>
/// <returns>true if the response type is Json Light; false otherwise</returns>
internal static bool IsResponseMediaTypeJsonLight(IDataService dataService, bool isEntryOrFeed)
{
AstoriaRequestMessage requestMessage = dataService.OperationContext.RequestMessage;
Version effectiveMaxResponseVersion = VersionUtil.GetEffectiveMaxResponseVersion(dataService.Configuration.DataServiceBehavior.MaxProtocolVersion.ToVersion(), requestMessage.RequestMaxVersion);
return IsResponseMediaTypeJsonLight(requestMessage.GetAcceptableContentTypes(), isEntryOrFeed, effectiveMaxResponseVersion);
}
/// <summary>
/// Determines whether the response content type is a JSON-based format.
/// </summary>
/// <param name="responseContentType">The response content-type.</param>
/// <returns>
/// <c>true</c> if the content-type is JSON; otherwise, <c>false</c>.
/// </returns>
internal static bool IsNotJson(string responseContentType)
{
return responseContentType == null || !responseContentType.StartsWith(XmlConstants.MimeApplicationJson, StringComparison.OrdinalIgnoreCase);
}
#endif
#if ASTORIA_CLIENT
/// <summary>Reads a Content-Type header and extracts the MIME type/subtype.</summary>
/// <param name="contentType">The Content-Type header.</param>
/// <param name="mime">The MIME type in standard type/subtype form, without parameters.</param>
/// <returns>parameters of content type</returns>
internal static MediaParameter[] ReadContentType(string contentType, out string mime)
{
if (String.IsNullOrEmpty(contentType))
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_ContentTypeMissing);
}
MediaType mediaType = ReadMediaType(contentType);
mime = mediaType.MimeType;
return mediaType.Parameters;
}
/// <summary>Builds a Content-Type given the mime type and all the parameters.</summary>
/// <param name="mimeType">The MIME type in standard type/subtype form, without parameters.</param>
/// <param name="parameters">Parameters to be appended in the mime type.</param>
/// <returns>content type containing the mime type and all the parameters.</returns>
internal static string WriteContentType(string mimeType, MediaParameter[] parameters)
{
Debug.Assert(!string.IsNullOrEmpty(mimeType), "!string.IsNullOrEmpty(mimeType)");
Debug.Assert(parameters != null, "parameters != null");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(mimeType);
foreach (var parameter in parameters)
{
stringBuilder.Append(';');
stringBuilder.Append(parameter.Name);
stringBuilder.Append("=");
stringBuilder.Append(parameter.GetOriginalValue());
}
return stringBuilder.ToString();
}
#endif
/// <summary>Reads a Content-Type header and extracts the MIME type/subtype and encoding.</summary>
/// <param name="contentType">The Content-Type header.</param>
/// <param name="mime">The MIME type in standard type/subtype form, without parameters.</param>
/// <param name="encoding">Encoding (possibly null).</param>
/// <returns>parameters of content type</returns>
internal static MediaParameter[] ReadContentType(string contentType, out string mime, out Encoding encoding)
{
if (String.IsNullOrEmpty(contentType))
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_ContentTypeMissing);
}
MediaType mediaType = ReadMediaType(contentType);
mime = mediaType.MimeType;
encoding = mediaType.SelectEncoding();
return mediaType.Parameters;
}
/// <summary>Gets the named encoding if specified.</summary>
/// <param name="name">Name (possibly null or empty).</param>
/// <returns>
/// The named encoding if specified; the encoding for HTTP missing
/// charset specification otherwise.
/// </returns>
/// <remarks>
/// See http://tools.ietf.org/html/rfc2616#section-3.4.1 for details.
/// </remarks>
private static Encoding EncodingFromName(string name)
{
if (name == null)
{
return MissingEncoding;
}
name = name.Trim();
if (name.Length == 0)
{
return MissingEncoding;
}
try
{
return Encoding.GetEncoding(name);
}
catch (ArgumentException)
{
// 400 - Bad Request
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_EncodingNotSupported(name));
}
}
#if !ASTORIA_CLIENT
/// <summary>Creates a new exception for parsing errors.</summary>
/// <param name="message">Message for error.</param>
/// <returns>A new exception that can be thrown for a parsing error.</returns>
private static DataServiceException CreateParsingException(string message)
{
// Status code "400" ; Section 10.4.1: Bad Request
return Error.HttpHeaderFailure(400, message);
}
/// <summary>
/// Returns the list of available media types.
/// </summary>
/// <param name="effectiveMaxResponseVersion">The effective max response version of the request.</param>
/// <param name="isEntityOrFeed">true if the response will contain an entity or feed.</param>
/// <returns>A list of recognized media types.</returns>
private static string[] GetAvailableMediaTypes(Version effectiveMaxResponseVersion, bool isEntityOrFeed)
{
return isEntityOrFeed ? MediaTypesForEntityOrFeedV3 : MediaTypesForOtherV3;
}
/// <summary>
/// Verfies whether the specified character is a valid separator in
/// an HTTP header list of element.
/// </summary>
/// <param name="c">Character to verify.</param>
/// <returns>true if c is a valid character for separating elements; false otherwise.</returns>
private static bool IsHttpElementSeparator(char c)
{
return c == ',' || c == ' ' || c == '\t';
}
/// <summary>
/// "Reads" a literal from the specified string by verifying that
/// the exact text can be found at the specified position.
/// </summary>
/// <param name="text">Text within which a literal should be checked.</param>
/// <param name="textIndex">Index in text where the literal should be found.</param>
/// <param name="literal">Literal to check at the specified position.</param>
/// <returns>true if the end of string is found; false otherwise.</returns>
private static bool ReadLiteral(string text, int textIndex, string literal)
{
if (String.Compare(text, textIndex, literal, 0, literal.Length, StringComparison.Ordinal) != 0)
{
// Failed to find expected literal.
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
return textIndex + literal.Length == text.Length;
}
/// <summary>
/// Converts the specified character from the ASCII range to a digit.
/// </summary>
/// <param name="c">Character to convert.</param>
/// <returns>
/// The Int32 value for c, or -1 if it is an element separator.
/// </returns>
private static int DigitToInt32(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
if (IsHttpElementSeparator(c))
{
return -1;
}
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
/// <summary>Returns all MIME types from the specified (non-blank) <paramref name='text' />.</summary>
/// <param name='text'>Non-blank text, as it appears on an HTTP Accepts header.</param>
/// <returns>An enumerable object with media type descriptions.</returns>
private static IEnumerable<MediaType> MimeTypesFromAcceptHeader(string text)
{
Debug.Assert(!String.IsNullOrEmpty(text), "!String.IsNullOrEmpty(text)");
List<MediaType> mediaTypes = new List<MediaType>();
int textIndex = 0;
while (!SkipWhitespace(text, ref textIndex))
{
string type;
string subType;
ReadMediaTypeAndSubtype(text, ref textIndex, out type, out subType);
MediaParameter[] parameters = null;
while (!SkipWhitespace(text, ref textIndex))
{
if (text[textIndex] == ',')
{
textIndex++;
break;
}
if (text[textIndex] != ';')
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter);
}
textIndex++;
if (SkipWhitespace(text, ref textIndex))
{
// ';' should be a leading separator, but we choose to be a
// bit permissive and allow it as a final delimiter as well.
break;
}
ReadMediaTypeParameter(text, ref textIndex, ref parameters);
}
mediaTypes.Add(new MediaType(type, subType, parameters));
}
return mediaTypes;
}
/// <summary>
/// Reads the numeric part of a quality value substring, normalizing it to 0-1000
/// rather than the standard 0.000-1.000 ranges.
/// </summary>
/// <param name="text">Text to read qvalue from.</param>
/// <param name="textIndex">Index into text where the qvalue starts.</param>
/// <param name="qualityValue">After the method executes, the normalized qvalue.</param>
/// <remarks>
/// For more information, see RFC 2616.3.8.
/// </remarks>
private static void ReadQualityValue(string text, ref int textIndex, out int qualityValue)
{
char digit = text[textIndex++];
if (digit == '0')
{
qualityValue = 0;
}
else if (digit == '1')
{
qualityValue = 1;
}
else
{
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
if (textIndex < text.Length && text[textIndex] == '.')
{
textIndex++;
int adjustFactor = 1000;
while (adjustFactor > 1 && textIndex < text.Length)
{
char c = text[textIndex];
int charValue = DigitToInt32(c);
if (charValue >= 0)
{
textIndex++;
adjustFactor /= 10;
qualityValue *= 10;
qualityValue += charValue;
}
else
{
break;
}
}
qualityValue *= adjustFactor;
if (qualityValue > 1000)
{
// Too high of a value in qvalue.
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
}
else
{
qualityValue *= 1000;
}
}
/// <summary>
/// Enumerates each charset part in the specified Accept-Charset header.
/// </summary>
/// <param name="headerValue">Non-null and non-empty header value for Accept-Charset.</param>
/// <returns>
/// A (non-sorted) enumeration of CharsetPart elements, which include
/// a charset name and a quality (preference) value, normalized to 0-1000.
/// </returns>
private static IEnumerable<CharsetPart> AcceptCharsetParts(string headerValue)
{
Debug.Assert(!String.IsNullOrEmpty(headerValue), "!String.IsNullOrEmpty(headerValuer)");
// PERF: optimize for common patterns.
bool commaRequired = false; // Whether a comma should be found
int headerIndex = 0; // Index of character being procesed on headerValue.
int headerStart; // Index into headerValue for the start of the charset name.
int headerNameEnd; // Index into headerValue for the end of the charset name (+1).
int headerEnd; // Index into headerValue for this charset part (+1).
int qualityValue; // Normalized qvalue for this charset.
while (headerIndex < headerValue.Length)
{
if (SkipWhitespace(headerValue, ref headerIndex))
{
yield break;
}
if (headerValue[headerIndex] == ',')
{
commaRequired = false;
headerIndex++;
continue;
}
if (commaRequired)
{
// Comma missing between charset elements.
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
headerStart = headerIndex;
headerNameEnd = headerStart;
bool endReached = ReadToken(headerValue, ref headerNameEnd);
if (headerNameEnd == headerIndex)
{
// Invalid charset name.
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
if (endReached)
{
qualityValue = 1000;
headerEnd = headerNameEnd;
}
else
{
char afterNameChar = headerValue[headerNameEnd];
if (IsHttpSeparator(afterNameChar))
{
if (afterNameChar == ';')
{
if (ReadLiteral(headerValue, headerNameEnd, ";q="))
{
// Unexpected end of qvalue.
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
headerEnd = headerNameEnd + 3;
ReadQualityValue(headerValue, ref headerEnd, out qualityValue);
}
else
{
qualityValue = 1000;
headerEnd = headerNameEnd;
}
}
else
{
// Invalid separator character.
throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue);
}
}
yield return new CharsetPart(headerValue.Substring(headerStart, headerNameEnd - headerStart), qualityValue);
// Prepare for next charset; we require at least one comma before we process it.
commaRequired = true;
headerIndex = headerEnd;
}
}
#endif
/// <summary>Reads the type and subtype specifications for a MIME type.</summary>
/// <param name='text'>Text in which specification exists.</param>
/// <param name='textIndex'>Pointer into text.</param>
/// <param name='type'>Type of media found.</param>
/// <param name='subType'>Subtype of media found.</param>
private static void ReadMediaTypeAndSubtype(string text, ref int textIndex, out string type, out string subType)
{
Debug.Assert(text != null, "text != null");
int textStart = textIndex;
if (ReadToken(text, ref textIndex))
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeUnspecified);
}
if (text[textIndex] != '/')
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSlash);
}
type = text.Substring(textStart, textIndex - textStart);
textIndex++;
int subTypeStart = textIndex;
ReadToken(text, ref textIndex);
if (textIndex == subTypeStart)
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSubType);
}
subType = text.Substring(subTypeStart, textIndex - subTypeStart);
}
/// <summary>Reads a media type definition as used in a Content-Type header.</summary>
/// <param name="text">Text to read.</param>
/// <returns>The <see cref="MediaType"/> defined by the specified <paramref name="text"/></returns>
/// <remarks>All syntactic errors will produce a 400 - Bad Request status code.</remarks>
private static MediaType ReadMediaType(string text)
{
Debug.Assert(text != null, "text != null");
string type;
string subType;
int textIndex = 0;
ReadMediaTypeAndSubtype(text, ref textIndex, out type, out subType);
MediaParameter[] parameters = null;
while (!SkipWhitespace(text, ref textIndex))
{
if (text[textIndex] != ';')
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter);
}
textIndex++;
if (SkipWhitespace(text, ref textIndex))
{
// ';' should be a leading separator, but we choose to be a
// bit permissive and allow it as a final delimiter as well.
break;
}
ReadMediaTypeParameter(text, ref textIndex, ref parameters);
}
return new MediaType(type, subType, parameters);
}
/// <summary>
/// Reads a token on the specified text by advancing an index on it.
/// </summary>
/// <param name="text">Text to read token from.</param>
/// <param name="textIndex">Index for the position being scanned on text.</param>
/// <returns>true if the end of the text was reached; false otherwise.</returns>
private static bool ReadToken(string text, ref int textIndex)
{
while (textIndex < text.Length && IsHttpToken(text[textIndex]))
{
textIndex++;
}
return (textIndex == text.Length);
}
/// <summary>
/// Skips whitespace in the specified text by advancing an index to
/// the next non-whitespace character.
/// </summary>
/// <param name="text">Text to scan.</param>
/// <param name="textIndex">Index to begin scanning from.</param>
/// <returns>true if the end of the string was reached, false otherwise.</returns>
private static bool SkipWhitespace(string text, ref int textIndex)
{
Debug.Assert(text != null, "text != null");
Debug.Assert(text.Length >= 0, "text >= 0");
Debug.Assert(textIndex <= text.Length, "text <= text.Length");
while (textIndex < text.Length && Char.IsWhiteSpace(text, textIndex))
{
textIndex++;
}
return (textIndex == text.Length);
}
/// <summary>Read a parameter for a media type/range.</summary>
/// <param name="text">Text to read from.</param>
/// <param name="textIndex">Pointer in text.</param>
/// <param name="parameters">Array with parameters to grow as necessary.</param>
private static void ReadMediaTypeParameter(string text, ref int textIndex, ref MediaParameter[] parameters)
{
int startIndex = textIndex;
if (ReadToken(text, ref textIndex))
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeMissingValue);
}
string parameterName = text.Substring(startIndex, textIndex - startIndex);
if (text[textIndex] != '=')
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeMissingValue);
}
textIndex++;
MediaParameter parameter = ReadQuotedParameterValue(parameterName, text, ref textIndex);
// Add the parameter name/value pair to the list.
if (parameters == null)
{
parameters = new MediaParameter[1];
}
else
{
var grow = new MediaParameter[parameters.Length + 1];
Array.Copy(parameters, grow, parameters.Length);
parameters = grow;
}
parameters[parameters.Length - 1] = parameter;
}
/// <summary>
/// Reads Mime type parameter value for a particular parameter in the Content-Type/Accept headers.
/// </summary>
/// <param name="parameterName">Name of parameter.</param>
/// <param name="headerText">Header text.</param>
/// <param name="textIndex">Parsing index in <paramref name="headerText"/>.</param>
/// <returns>String representing the value of the <paramref name="parameterName"/> parameter.</returns>
private static MediaParameter ReadQuotedParameterValue(string parameterName, string headerText, ref int textIndex)
{
StringBuilder parameterValue = new StringBuilder();
bool isQuoted = false;
// Check if the value is quoted.
bool valueIsQuoted = false;
if (textIndex < headerText.Length)
{
if (headerText[textIndex] == '\"')
{
textIndex++;
valueIsQuoted = true;
isQuoted = true;
}
}
while (textIndex < headerText.Length)
{
char currentChar = headerText[textIndex];
if (currentChar == '\\' || currentChar == '\"')
{
if (!valueIsQuoted)
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_EscapeCharWithoutQuotes(parameterName));
}
textIndex++;
// End of quoted parameter value.
if (currentChar == '\"')
{
valueIsQuoted = false;
break;
}
if (textIndex >= headerText.Length)
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_EscapeCharAtEnd(parameterName));
}
currentChar = headerText[textIndex];
}
else
if (!IsHttpToken(currentChar))
{
// If the given character is special, we stop processing.
break;
}
parameterValue.Append(currentChar);
textIndex++;
}
if (valueIsQuoted)
{
throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_ClosingQuoteNotFound(parameterName));
}
return new MediaParameter(parameterName, parameterValue.ToString(), isQuoted);
}
/// <summary>
/// Determines whether the specified character is a valid HTTP separator.
/// </summary>
/// <param name="c">Character to verify.</param>
/// <returns>true if c is a separator; false otherwise.</returns>
/// <remarks>
/// See RFC 2616 2.2 for further information.
/// </remarks>
private static bool IsHttpSeparator(char c)
{
return
c == '(' || c == ')' || c == '<' || c == '>' || c == '@' ||
c == ',' || c == ';' || c == ':' || c == '\\' || c == '"' ||
c == '/' || c == '[' || c == ']' || c == '?' || c == '=' ||
c == '{' || c == '}' || c == ' ' || c == '\x9';
}
/// <summary>
/// Determines whether the specified character is a valid HTTP header token character.
/// </summary>
/// <param name="c">Character to verify.</param>
/// <returns>true if c is a valid HTTP header token character; false otherwise.</returns>
private static bool IsHttpToken(char c)
{
// A token character is any character (0-127) except control (0-31) or
// separators. 127 is DEL, a control character.
return c < '\x7F' && c > '\x1F' && !IsHttpSeparator(c);
}
#if !ASTORIA_CLIENT
/// <summary>Provides a struct to encapsulate a charset name and its relative desirability.</summary>
private struct CharsetPart
{
/// <summary>Name of the charset.</summary>
internal readonly string Charset;
/// <summary>Charset quality (desirability), normalized to 0-1000.</summary>
internal readonly int Quality;
/// <summary>
/// Initializes a new CharsetPart with the specified values.
/// </summary>
/// <param name="charset">Name of charset.</param>
/// <param name="quality">Charset quality (desirability), normalized to 0-1000.</param>
internal CharsetPart(string charset, int quality)
{
Debug.Assert(charset != null, "charset != null");
Debug.Assert(charset.Length > 0, "charset.Length > 0");
Debug.Assert(0 <= quality && quality <= 1000, "0 <= quality && quality <= 1000");
this.Charset = charset;
this.Quality = quality;
}
}
#endif
/// <summary>Class to store media parameter information.</summary>
internal class MediaParameter
{
/// <summary>
/// Creates a new instance of MediaParameter.
/// </summary>
/// <param name="name">Name of the parameter.</param>
/// <param name="value">Value of the parameter.</param>
/// <param name="isQuoted">True if the value of the parameter is quoted, otherwise false.</param>
public MediaParameter(string name, string value, bool isQuoted)
{
this.Name = name;
this.Value = value;
this.IsQuoted = isQuoted;
}
/// <summary>Gets the name of the parameter.</summary>
public string Name { get; private set; }
/// <summary>Value of the parameter.</summary>
public string Value { get; private set; }
/// <summary>true if the value is quoted, otherwise false.</summary>
private bool IsQuoted { get; set; }
/// <summary>
/// Gets the original value of the parameter.
/// </summary>
/// <returns>the original value of the parameter.</returns>
public string GetOriginalValue()
{
return this.IsQuoted ? "\"" + this.Value + "\"" : this.Value;
}
}
/// <summary>Use this class to represent a media type definition.</summary>
[DebuggerDisplay("MediaType [{type}/{subType}]")]
private sealed class MediaType
{
/// <summary>Parameters specified on the media type.</summary>
private readonly MediaParameter[] parameters;
/// <summary>Sub-type specification (for example, 'plain').</summary>
private readonly string subType;
/// <summary>Type specification (for example, 'text').</summary>
private readonly string type;
/// <summary>
/// Initializes a new <see cref="MediaType"/> read-only instance.
/// </summary>
/// <param name="type">Type specification (for example, 'text').</param>
/// <param name="subType">Sub-type specification (for example, 'plain').</param>
/// <param name="parameters">Parameters specified on the media type.</param>
internal MediaType(string type, string subType, MediaParameter[] parameters)
{
Debug.Assert(type != null, "type != null");
Debug.Assert(subType != null, "subType != null");
this.type = type;
this.subType = subType;
this.parameters = parameters;
}
/// <summary>Returns the MIME type in standard type/subtype form, without parameters.</summary>
internal string MimeType
{
get { return this.type + "/" + this.subType; }
}
/// <summary>media type parameters</summary>
internal MediaParameter[] Parameters
{
get { return this.parameters; }
}
#if !ASTORIA_CLIENT
/// <summary>Gets a number of non-* matching types, or -1 if not matching at all.</summary>
/// <param name="candidate">Candidate MIME type to match.</param>
/// <returns>The number of non-* matching types, or -1 if not matching at all.</returns>
internal int GetMatchingParts(string candidate)
{
Debug.Assert(candidate != null, "candidate must not be null.");
return this.GetMatchingParts(MimeTypesFromAcceptHeader(candidate).Single());
}
/// <summary>Gets a number of non-* matching types, or -1 if not matching at all.</summary>
/// <param name="candidate">Candidate MIME type to match.</param>
/// <returns>The number of non-* matching types, or -1 if not matching at all.</returns>
internal int GetMatchingParts(MediaType candidate)
{
Debug.Assert(candidate != null, "candidate must not be null.");
int result = -1;
if (candidate != null)
{
if (this.type == "*")
{
result = 0;
}
else
{
if (candidate.subType != null)
{
string candidateType = candidate.type;
if (CompareMimeType(this.type, candidateType))
{
if (this.subType == "*")
{
result = 1;
}
else
{
string candidateSubType = candidate.subType;
if (CompareMimeType(this.subType, candidateSubType))
{
if (String.Equals(this.GetParameterValue(XmlConstants.MimeODataParameterName), candidate.GetParameterValue(XmlConstants.MimeODataParameterName), StringComparison.OrdinalIgnoreCase))
{
result = 2;
}
}
}
}
}
}
}
return result;
}
/// <summary>
/// Searches for the parameter with the given name and returns its value.
/// </summary>
/// <param name="parameterName">name of the parameter whose value needs to be returned.</param>
/// <returns>returns the value of the parameter with the given name. Returns null, if the parameter is not found.</returns>
internal string GetParameterValue(string parameterName)
{
if (this.parameters == null)
{
return null;
}
foreach (MediaParameter parameterInfo in this.parameters)
{
if (String.Equals(parameterInfo.Name, parameterName, StringComparison.OrdinalIgnoreCase))
{
string parameterValue = parameterInfo.Value.Trim();
if (parameterValue.Length > 0)
{
return parameterInfo.Value;
}
}
}
return null;
}
/// <summary>Selects a quality value for the specified type.</summary>
/// <returns>The quality value, in range from 0 through 1000.</returns>
/// <remarks>See http://tools.ietf.org/html/rfc2616#section-14.1 for further details.</remarks>
internal int SelectQualityValue()
{
string qvalueText = this.GetParameterValue(XmlConstants.HttpQValueParameter);
if (qvalueText == null)
{
return 1000;
}
int result;
int textIndex = 0;
ReadQualityValue(qvalueText, ref textIndex, out result);
return result;
}
#endif
/// <summary>
/// Selects the encoding appropriate for this media type specification
/// (possibly null).
/// </summary>
/// <returns>
/// The encoding explicitly defined on the media type specification, or
/// the default encoding for well-known media types.
/// </returns>
/// <remarks>
/// As per http://tools.ietf.org/html/rfc2616#section-3.7, the type,
/// subtype and parameter name attributes are case-insensitive.
/// </remarks>
internal Encoding SelectEncoding()
{
if (this.parameters != null)
{
foreach (MediaParameter parameter in this.parameters)
{
if (String.Equals(parameter.Name, XmlConstants.HttpCharsetParameter, StringComparison.OrdinalIgnoreCase))
{
string encodingName = parameter.Value.Trim();
if (encodingName.Length > 0)
{
return EncodingFromName(parameter.Value);
}
}
}
}
// Select the default encoding for this media type.
if (String.Equals(this.type, XmlConstants.MimeTextType, StringComparison.OrdinalIgnoreCase))
{
// HTTP 3.7.1 Canonicalization and Text Defaults
// "text" subtypes default to ISO-8859-1
//
// Unless the subtype is XML, in which case we should default
// to us-ascii. Instead we return null, to let the encoding
// in the <?xml ...?> PI win (http://tools.ietf.org/html/rfc3023#section-3.1)
if (String.Equals(this.subType, XmlConstants.MimeXmlSubType, StringComparison.OrdinalIgnoreCase))
{
return null;
}
return MissingEncoding;
}
if (String.Equals(this.type, XmlConstants.MimeApplicationType, StringComparison.OrdinalIgnoreCase) &&
String.Equals(this.subType, XmlConstants.MimeJsonSubType, StringComparison.OrdinalIgnoreCase))
{
// http://tools.ietf.org/html/rfc4627#section-3
// The default encoding is UTF-8.
return FallbackEncoding;
}
return null;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DBConnectionOptions.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Versioning;
internal class DbConnectionOptions {
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
#if DEBUG
/*private const string ConnectionStringPatternV1 =
"[\\s;]*"
+"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)"
+ "\\s*=(?!=)\\s*"
+"(?<value>("
+ "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")"
+ "|"
+ "(" + "'" + "([^']|'')*" + "'" + ")"
+ "|"
+ "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")"
+ "))"
+ "[\\s;]*"
;*/
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
+ "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
+ "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private const string ConnectionStringPatternOdbc = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}])+)" // allow any visible character for keyname except '='
+ "\\s*=\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\\{([^\\}\u0000]|\\}\\})*\\})" // quoted string, starts with { and ends with }
+ "|"
+ "((?![\\{\\s])" // unquoted value must not start with { or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ ")" // VSTFDEVDIV 94761: although the spec does not allow {}
// embedded within a value, the retail code does.
// + "(?<![\\}]))" // unquoted value must not stop with }
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // traling whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex ConnectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static readonly Regex ConnectionStringRegexOdbc = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
private const string ConnectionStringValidKeyPattern = "^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$"; // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private const string ConnectionStringValidValuePattern = "^[^\u0000]*$"; // value not allowed to contain embedded null
private const string ConnectionStringQuoteValuePattern = "^[^\"'=;\\s\\p{Cc}]*$"; // generally do not quote the value if it matches the pattern
private const string ConnectionStringQuoteOdbcValuePattern = "^\\{([^\\}\u0000]|\\}\\})*\\}$"; // do not quote odbc value if it matches this pattern
internal const string DataDirectory = "|datadirectory|";
private static readonly Regex ConnectionStringValidKeyRegex = new Regex(ConnectionStringValidKeyPattern, RegexOptions.Compiled);
private static readonly Regex ConnectionStringValidValueRegex = new Regex(ConnectionStringValidValuePattern, RegexOptions.Compiled);
private static readonly Regex ConnectionStringQuoteValueRegex = new Regex(ConnectionStringQuoteValuePattern, RegexOptions.Compiled);
private static readonly Regex ConnectionStringQuoteOdbcValueRegex = new Regex(ConnectionStringQuoteOdbcValuePattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
// connection string common keywords
private static class KEY {
internal const string Integrated_Security = "integrated security";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string User_ID = "user id";
};
// known connection string common synonyms
private static class SYNONYM {
internal const string Pwd = "pwd";
internal const string UID = "uid";
};
private readonly string _usersConnectionString;
private readonly Hashtable _parsetable;
internal readonly NameValuePair KeyChain;
internal readonly bool HasPasswordKeyword;
internal readonly bool HasUserIdKeyword;
// differences between OleDb and Odbc
// ODBC:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcsqldriverconnect.asp
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbcsql/od_odbc_d_4x4k.asp
// do not support == -> = in keywords
// first key-value pair wins
// quote values using \{ and \}, only driver= and pwd= appear to generically allow quoting
// do not strip quotes from value, or add quotes except for driver keyword
// OLEDB:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/oledb/htm/oledbconnectionstringsyntax.asp
// support == -> = in keywords
// last key-value pair wins
// quote values using \" or \'
// strip quotes from value
internal readonly bool UseOdbcRules;
private System.Security.PermissionSet _permissionset;
// called by derived classes that may cache based on connectionString
public DbConnectionOptions(string connectionString)
: this(connectionString, null, false) {
}
// synonyms hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
public DbConnectionOptions(string connectionString, Hashtable synonyms, bool useOdbcRules) {
UseOdbcRules = useOdbcRules;
_parsetable = new Hashtable();
_usersConnectionString = ((null != connectionString) ? connectionString : "");
// first pass on parsing, initial syntax check
if (0 < _usersConnectionString.Length) {
KeyChain = ParseInternal(_parsetable, _usersConnectionString, true, synonyms, UseOdbcRules);
HasPasswordKeyword = (_parsetable.ContainsKey(KEY.Password) || _parsetable.ContainsKey(SYNONYM.Pwd));
HasUserIdKeyword = (_parsetable.ContainsKey(KEY.User_ID) || _parsetable.ContainsKey(SYNONYM.UID));
}
}
protected DbConnectionOptions(DbConnectionOptions connectionOptions) { // Clone used by SqlConnectionString
_usersConnectionString = connectionOptions._usersConnectionString;
HasPasswordKeyword = connectionOptions.HasPasswordKeyword;
HasUserIdKeyword = connectionOptions.HasUserIdKeyword;
UseOdbcRules = connectionOptions.UseOdbcRules;
_parsetable = connectionOptions._parsetable;
KeyChain = connectionOptions.KeyChain;
}
public string UsersConnectionString(bool hidePassword) {
return UsersConnectionString(hidePassword, false);
}
private string UsersConnectionString(bool hidePassword, bool forceHidePassword) {
string connectionString = _usersConnectionString;
if (HasPasswordKeyword && (forceHidePassword || (hidePassword && !HasPersistablePassword))) {
ReplacePasswordPwd(out connectionString, false);
}
return ((null != connectionString) ? connectionString : "");
}
internal string UsersConnectionStringForTrace() {
return UsersConnectionString(true, true);
}
internal bool HasBlankPassword {
get {
if (!ConvertValueToIntegratedSecurity()) {
if (_parsetable.ContainsKey(KEY.Password)) {
return ADP.IsEmpty((string)_parsetable[KEY.Password]);
} else
if (_parsetable.ContainsKey(SYNONYM.Pwd)) {
return ADP.IsEmpty((string)_parsetable[SYNONYM.Pwd]); // MDAC 83097
} else {
return ((_parsetable.ContainsKey(KEY.User_ID) && !ADP.IsEmpty((string)_parsetable[KEY.User_ID])) || (_parsetable.ContainsKey(SYNONYM.UID) && !ADP.IsEmpty((string)_parsetable[SYNONYM.UID])));
}
}
return false;
}
}
internal bool HasPersistablePassword {
get {
if (HasPasswordKeyword) {
return ConvertValueToBoolean(KEY.Persist_Security_Info, false);
}
return true; // no password means persistable password so we don't have to munge
}
}
public bool IsEmpty {
get { return (null == KeyChain); }
}
internal Hashtable Parsetable {
get { return _parsetable; }
}
public ICollection Keys {
get { return _parsetable.Keys; }
}
public string this[string keyword] {
get { return (string)_parsetable[keyword]; }
}
internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string keyValue, bool useOdbcRules) {
ADP.CheckArgumentNull(builder, "builder");
ADP.CheckArgumentLength(keyName, "keyName");
if ((null == keyName) || !ConnectionStringValidKeyRegex.IsMatch(keyName)) {
throw ADP.InvalidKeyname(keyName);
}
if ((null != keyValue) && !IsValueValidInternal(keyValue)) {
throw ADP.InvalidValue(keyName);
}
if ((0 < builder.Length) && (';' != builder[builder.Length-1])) {
builder.Append(";");
}
if (useOdbcRules) {
builder.Append(keyName);
}
else {
builder.Append(keyName.Replace("=", "=="));
}
builder.Append("=");
if (null != keyValue) { // else <keyword>=;
if (useOdbcRules) {
if ((0 < keyValue.Length) &&
(('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (0 == String.Compare(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) &&
!ConnectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
{
// always quote Driver value (required for ODBC Version 2.65 and earlier)
// always quote values that contain a ';'
builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
}
else {
builder.Append(keyValue);
}
}
else if (ConnectionStringQuoteValueRegex.IsMatch(keyValue)) {
// <value> -> <value>
builder.Append(keyValue);
}
else if ((-1 != keyValue.IndexOf('\"')) && (-1 == keyValue.IndexOf('\''))) {
// <val"ue> -> <'val"ue'>
builder.Append('\'');
builder.Append(keyValue);
builder.Append('\'');
}
else {
// <val'ue> -> <"val'ue">
// <=value> -> <"=value">
// <;value> -> <";value">
// < value> -> <" value">
// <va lue> -> <"va lue">
// <va'"lue> -> <"va'""lue">
builder.Append('\"');
builder.Append(keyValue.Replace("\"", "\"\""));
builder.Append('\"');
}
}
}
public bool ConvertValueToBoolean(string keyName, bool defaultValue) {
object value = _parsetable[keyName];
if (null == value) {
return defaultValue;
}
return ConvertValueToBooleanInternal(keyName, (string) value);
}
internal static bool ConvertValueToBooleanInternal(string keyName, string stringValue) {
if (CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else {
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else {
throw ADP.InvalidConnectionOptionValue(keyName);
}
}
}
// same as Boolean, but with SSPI thrown in as valid yes
public bool ConvertValueToIntegratedSecurity() {
object value = _parsetable[KEY.Integrated_Security];
if (null == value) {
return false;
}
return ConvertValueToIntegratedSecurityInternal((string) value);
}
internal bool ConvertValueToIntegratedSecurityInternal(string stringValue) {
if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes"))
return true;
else if (CompareInsensitiveInvariant(stringValue, "false") || CompareInsensitiveInvariant(stringValue, "no"))
return false;
else {
string tmp = stringValue.Trim(); // Remove leading & trailing white space.
if (CompareInsensitiveInvariant(tmp, "sspi") || CompareInsensitiveInvariant(tmp, "true") || CompareInsensitiveInvariant(tmp, "yes"))
return true;
else if (CompareInsensitiveInvariant(tmp, "false") || CompareInsensitiveInvariant(tmp, "no"))
return false;
else {
throw ADP.InvalidConnectionOptionValue(KEY.Integrated_Security);
}
}
}
public int ConvertValueToInt32(string keyName, int defaultValue) {
object value = _parsetable[keyName];
if (null == value) {
return defaultValue;
}
return ConvertToInt32Internal(keyName, (string) value);
}
internal static int ConvertToInt32Internal(string keyname, string stringValue) {
try {
return System.Int32.Parse(stringValue, System.Globalization.NumberStyles.Integer, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
catch (OverflowException e) {
throw ADP.InvalidConnectionOptionValue(keyname, e);
}
}
public string ConvertValueToString(string keyName, string defaultValue) {
string value = (string)_parsetable[keyName];
return ((null != value) ? value : defaultValue);
}
static private bool CompareInsensitiveInvariant(string strvalue, string strconst) {
return (0 == StringComparer.OrdinalIgnoreCase.Compare(strvalue, strconst));
}
public bool ContainsKey(string keyword) {
return _parsetable.ContainsKey(keyword);
}
protected internal virtual System.Security.PermissionSet CreatePermissionSet() {
return null;
}
internal void DemandPermission() {
if (null == _permissionset) {
_permissionset = CreatePermissionSet();
}
_permissionset.Demand();
}
protected internal virtual string Expand() {
return _usersConnectionString;
}
// SxS notes:
// * this method queries "DataDirectory" value from the current AppDomain.
// This string is used for to replace "!DataDirectory!" values in the connection string, it is not considered as an "exposed resource".
// * This method uses GetFullPath to validate that root path is valid, the result is not exposed out.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal static string ExpandDataDirectory(string keyword, string value, ref string datadir) {
string fullPath = null;
if ((null != value) && value.StartsWith(DataDirectory, StringComparison.OrdinalIgnoreCase)) {
string rootFolderPath = datadir;
if (null == rootFolderPath) {
// find the replacement path
object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
rootFolderPath = (rootFolderObject as string);
if ((null != rootFolderObject) && (null == rootFolderPath)) {
throw ADP.InvalidDataDirectory();
}
else if (ADP.IsEmpty(rootFolderPath)) {
rootFolderPath = AppDomain.CurrentDomain.BaseDirectory;
}
if (null == rootFolderPath) {
rootFolderPath = "";
}
// cache the |DataDir| for ExpandDataDirectories
datadir = rootFolderPath;
}
// We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
int fileNamePosition = DataDirectory.Length; // filename starts right after the '|datadirectory|' keyword
bool rootFolderEndsWith = (0 < rootFolderPath.Length) && rootFolderPath[rootFolderPath.Length-1] == '\\';
bool fileNameStartsWith = (fileNamePosition < value.Length) && value[fileNamePosition] == '\\';
// replace |datadirectory| with root folder path
if (!rootFolderEndsWith && !fileNameStartsWith) {
// need to insert '\'
fullPath = rootFolderPath + '\\' + value.Substring(fileNamePosition);
}
else if (rootFolderEndsWith && fileNameStartsWith) {
// need to strip one out
fullPath = rootFolderPath + value.Substring(fileNamePosition+1);
}
else {
// simply concatenate the strings
fullPath = rootFolderPath + value.Substring(fileNamePosition);
}
// verify root folder path is a real path without unexpected "..\"
if (!ADP.GetFullPath(fullPath).StartsWith(rootFolderPath, StringComparison.Ordinal)) {
throw ADP.InvalidConnectionOptionValue(keyword);
}
}
return fullPath;
}
internal string ExpandDataDirectories(ref string filename, ref int position) {
string value = null;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
string datadir = null;
int copyPosition = 0;
bool expanded = false;
for(NameValuePair current = KeyChain; null != current; current = current.Next) {
value = current.Value;
// remove duplicate keyswords from connectionstring
//if ((object)this[current.Name] != (object)value) {
// expanded = true;
// copyPosition += current.Length;
// continue;
//}
// There is a set of keywords we explictly do NOT want to expand |DataDirectory| on
if (UseOdbcRules) {
switch(current.Name) {
case DbConnectionOptionKeywords.Driver:
case DbConnectionOptionKeywords.Pwd:
case DbConnectionOptionKeywords.UID:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
else {
switch(current.Name) {
case DbConnectionOptionKeywords.Provider:
case DbConnectionOptionKeywords.DataProvider:
case DbConnectionOptionKeywords.RemoteProvider:
case DbConnectionOptionKeywords.ExtendedProperties:
case DbConnectionOptionKeywords.UserID:
case DbConnectionOptionKeywords.Password:
case DbConnectionOptionKeywords.UID:
case DbConnectionOptionKeywords.Pwd:
break;
default:
value = ExpandDataDirectory(current.Name, value, ref datadir);
break;
}
}
if (null == value) {
value = current.Value;
}
if (UseOdbcRules || (DbConnectionOptionKeywords.FileName != current.Name)) {
if (value != current.Value) {
expanded = true;
AppendKeyValuePairBuilder(builder, current.Name, value, UseOdbcRules);
builder.Append(';');
}
else {
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
}
else {
// strip out 'File Name=myconnection.udl' for OleDb
// remembering is value for which UDL file to open
// and where to insert the strnig
expanded = true;
filename = value;
position = builder.Length;
}
copyPosition += current.Length;
}
if (expanded) {
value = builder.ToString();
}
else {
value = null;
}
return value;
}
internal string ExpandKeyword(string keyword, string replacementValue) {
// preserve duplicates, updated keyword value with replacement value
// if keyword not specified, append to end of the string
bool expanded = false;
int copyPosition = 0;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for(NameValuePair current = KeyChain; null != current; current = current.Next) {
if ((current.Name == keyword) && (current.Value == this[keyword])) {
// only replace the parse end-result value instead of all values
// so that when duplicate-keywords occur other original values remain in place
AppendKeyValuePairBuilder(builder, current.Name, replacementValue, UseOdbcRules);
builder.Append(';');
expanded = true;
}
else {
builder.Append(_usersConnectionString, copyPosition, current.Length);
}
copyPosition += current.Length;
}
if (!expanded) {
//
Debug.Assert(!UseOdbcRules, "ExpandKeyword not ready for Odbc");
AppendKeyValuePairBuilder(builder, keyword, replacementValue, UseOdbcRules);
}
return builder.ToString();
}
#if DEBUG
[System.Diagnostics.Conditional("DEBUG")]
private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) {
if (Bid.AdvancedOn) {
Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower");
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) { // don't trace passwords ever!
if (null != keyvalue) {
Bid.Trace("<comm.DbConnectionOptions|INFO|ADV> KeyName='%ls', KeyValue='%ls'\n", keyname, keyvalue);
}
else {
Bid.Trace("<comm.DbConnectionOptions|INFO|ADV> KeyName='%ls'\n", keyname);
}
}
}
}
#endif
static private string GetKeyName(StringBuilder buffer) {
int count = buffer.Length;
while ((0 < count) && Char.IsWhiteSpace(buffer[count-1])) {
count--; // trailing whitespace
}
return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture);
}
static private string GetKeyValue(StringBuilder buffer, bool trimWhitespace) {
int count = buffer.Length;
int index = 0;
if (trimWhitespace) {
while ((index < count) && Char.IsWhiteSpace(buffer[index])) {
index++; // leading whitespace
}
while ((0 < count) && Char.IsWhiteSpace(buffer[count-1])) {
count--; // trailing whitespace
}
}
return buffer.ToString(index, count - index);
}
// transistion states used for parsing
private enum ParserState {
NothingYet=1, //start point
Key,
KeyEqual,
KeyEnd,
UnquotedValue,
DoubleQuoteValue,
DoubleQuoteValueQuote,
SingleQuoteValue,
SingleQuoteValueQuote,
BraceQuoteValue,
BraceQuoteValueQuote,
QuotedValueEnd,
NullTermination,
};
static internal int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue) {
int startposition = currentPosition;
buffer.Length = 0;
keyname = null;
keyvalue = null;
char currentChar = '\0';
ParserState parserState = ParserState.NothingYet;
int length = connectionString.Length;
for (; currentPosition < length; ++currentPosition) {
currentChar = connectionString[currentPosition];
switch(parserState) {
case ParserState.NothingYet: // [\\s;]*
if ((';' == currentChar) || Char.IsWhiteSpace(currentChar)) {
continue;
}
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } // MDAC 83540
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
startposition = currentPosition;
if ('=' != currentChar) { // MDAC 86902
parserState = ParserState.Key;
break;
}
else {
parserState = ParserState.KeyEqual;
continue;
}
case ParserState.Key: // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
if ('=' == currentChar) { parserState = ParserState.KeyEqual; continue; }
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.KeyEqual: // \\s*=(?!=)\\s*
if (!useOdbcRules && '=' == currentChar) { parserState = ParserState.Key; break; }
keyname = GetKeyName(buffer);
if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
buffer.Length = 0;
parserState = ParserState.KeyEnd;
goto case ParserState.KeyEnd;
case ParserState.KeyEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (useOdbcRules) {
if ('{' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
}
else {
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; continue; }
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; continue; }
}
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { goto ParserExit; }
if (Char.IsControl(currentChar)) { throw ADP.ConnectionStringSyntax(startposition); }
parserState = ParserState.UnquotedValue;
break;
case ParserState.UnquotedValue: // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
if (Char.IsWhiteSpace(currentChar)) { break; }
if (Char.IsControl(currentChar) || ';' == currentChar) { goto ParserExit; }
break;
case ParserState.DoubleQuoteValue: // "(\"([^\"\u0000]|\"\")*\")"
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.DoubleQuoteValueQuote:
if ('"' == currentChar) { parserState = ParserState.DoubleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.SingleQuoteValue: // "('([^'\u0000]|'')*')"
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValueQuote; continue; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.SingleQuoteValueQuote:
if ('\'' == currentChar) { parserState = ParserState.SingleQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.BraceQuoteValue: // "(\\{([^\\}\u0000]|\\}\\})*\\})"
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValueQuote; break; }
if ('\0' == currentChar) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.BraceQuoteValueQuote:
if ('}' == currentChar) { parserState = ParserState.BraceQuoteValue; break; }
keyvalue = GetKeyValue(buffer, false);
parserState = ParserState.QuotedValueEnd;
goto case ParserState.QuotedValueEnd;
case ParserState.QuotedValueEnd:
if (Char.IsWhiteSpace(currentChar)) { continue; }
if (';' == currentChar) { goto ParserExit; }
if ('\0' == currentChar) { parserState = ParserState.NullTermination; continue; } // MDAC 83540
throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote
case ParserState.NullTermination: // [\\s;\u0000]*
if ('\0' == currentChar) { continue; }
if (Char.IsWhiteSpace(currentChar)) { continue; } // MDAC 83540
throw ADP.ConnectionStringSyntax(currentPosition);
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
}
buffer.Append(currentChar);
}
ParserExit:
switch (parserState) {
case ParserState.Key:
case ParserState.DoubleQuoteValue:
case ParserState.SingleQuoteValue:
case ParserState.BraceQuoteValue:
// keyword not found/unbalanced double/single quote
throw ADP.ConnectionStringSyntax(startposition);
case ParserState.KeyEqual:
// equal sign at end of line
keyname = GetKeyName(buffer);
if (ADP.IsEmpty(keyname)) { throw ADP.ConnectionStringSyntax(startposition); }
break;
case ParserState.UnquotedValue:
// unquoted value at end of line
keyvalue = GetKeyValue(buffer, true);
char tmpChar = keyvalue[keyvalue.Length - 1];
if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar))) {
throw ADP.ConnectionStringSyntax(startposition); // unquoted value must not end in quote, except for odbc
}
break;
case ParserState.DoubleQuoteValueQuote:
case ParserState.SingleQuoteValueQuote:
case ParserState.BraceQuoteValueQuote:
case ParserState.QuotedValueEnd:
// quoted value at end of line
keyvalue = GetKeyValue(buffer, false);
break;
case ParserState.NothingYet:
case ParserState.KeyEnd:
case ParserState.NullTermination:
// do nothing
break;
default:
throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
}
if ((';' == currentChar) && (currentPosition < connectionString.Length)) {
currentPosition++;
}
return currentPosition;
}
static private bool IsValueValidInternal(string keyvalue) {
if (null != keyvalue)
{
#if DEBUG
bool compValue = ConnectionStringValidValueRegex.IsMatch(keyvalue);
Debug.Assert((-1 == keyvalue.IndexOf('\u0000')) == compValue, "IsValueValid mismatch with regex");
#endif
return (-1 == keyvalue.IndexOf('\u0000'));
}
return true;
}
static private bool IsKeyNameValid(string keyname) {
if (null != keyname) {
#if DEBUG
bool compValue = ConnectionStringValidKeyRegex.IsMatch(keyname);
Debug.Assert(((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000'))) == compValue, "IsValueValid mismatch with regex");
#endif
return ((0 < keyname.Length) && (';' != keyname[0]) && !Char.IsWhiteSpace(keyname[0]) && (-1 == keyname.IndexOf('\u0000')));
}
return false;
}
#if DEBUG
private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey) {
Hashtable parsetable = new Hashtable();
Regex parser = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex);
const int KeyIndex = 1, ValueIndex = 2;
Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");
if (null != connectionString) {
Match match = parser.Match(connectionString);
if (!match.Success || (match.Length != connectionString.Length)) {
throw ADP.ConnectionStringSyntax(match.Length);
}
int indexValue = 0;
CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
foreach(Capture keypair in match.Groups[KeyIndex].Captures) {
string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture);
string keyvalue = keyvalues[indexValue++].Value;
if (0 < keyvalue.Length) {
if (!firstKey) {
switch(keyvalue[0]) {
case '\"':
keyvalue = keyvalue.Substring(1, keyvalue.Length-2).Replace("\"\"", "\"");
break;
case '\'':
keyvalue = keyvalue.Substring(1, keyvalue.Length-2).Replace("\'\'", "\'");
break;
default:
break;
}
}
}
else {
keyvalue = null;
}
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (!IsKeyNameValid(realkeyname)) {
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.ContainsKey(realkeyname)) {
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
}
}
return parsetable;
}
private static void ParseComparison(Hashtable parsetable, string connectionString, Hashtable synonyms, bool firstKey, Exception e) {
try {
Hashtable parsedvalues = SplitConnectionString(connectionString, synonyms, firstKey);
foreach(DictionaryEntry entry in parsedvalues) {
string keyname = (string) entry.Key;
string value1 = (string) entry.Value;
string value2 = (string) parsetable[keyname];
Debug.Assert(parsetable.Contains(keyname), "ParseInternal code vs. regex mismatch keyname <" + keyname + ">");
Debug.Assert(value1 == value2, "ParseInternal code vs. regex mismatch keyvalue <" + value1 + "> <" + value2 +">");
}
}
catch(ArgumentException f) {
if (null != e) {
string msg1 = e.Message;
string msg2 = f.Message;
const string KeywordNotSupportedMessagePrefix = "Keyword not supported:";
const string WrongFormatMessagePrefix = "Format of the initialization string";
bool isEquivalent = (msg1 == msg2);
if (!isEquivalent)
{
// VSTFDEVDIV 479587: we also accept cases were Regex parser (debug only) reports "wrong format" and
// retail parsing code reports format exception in different location or "keyword not supported"
if (msg2.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) {
if (msg1.StartsWith(KeywordNotSupportedMessagePrefix, StringComparison.Ordinal) || msg1.StartsWith(WrongFormatMessagePrefix, StringComparison.Ordinal)) {
isEquivalent = true;
}
}
}
Debug.Assert(isEquivalent, "ParseInternal code vs regex message mismatch: <"+msg1+"> <"+msg2+">");
}
else {
Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
}
e = null;
}
if (null != e) {
Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
}
}
#endif
private static NameValuePair ParseInternal(Hashtable parsetable, string connectionString, bool buildChain, Hashtable synonyms, bool firstKey) {
Debug.Assert(null != connectionString, "null connectionstring");
StringBuilder buffer = new StringBuilder();
NameValuePair localKeychain = null, keychain = null;
#if DEBUG
try {
#endif
int nextStartPosition = 0;
int endPosition = connectionString.Length;
while (nextStartPosition < endPosition) {
int startPosition = nextStartPosition;
string keyname, keyvalue;
nextStartPosition = GetKeyValuePair(connectionString, startPosition, buffer, firstKey, out keyname, out keyvalue);
if (ADP.IsEmpty(keyname)) {
// if (nextStartPosition != endPosition) { throw; }
break;
}
#if DEBUG
DebugTraceKeyValuePair(keyname, keyvalue, synonyms);
Debug.Assert(IsKeyNameValid(keyname), "ParseFailure, invalid keyname");
Debug.Assert(IsValueValidInternal(keyvalue), "parse failure, invalid keyvalue");
#endif
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (!IsKeyNameValid(realkeyname)) {
throw ADP.KeywordNotSupported(keyname);
}
if (!firstKey || !parsetable.Contains(realkeyname)) {
parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
}
if(null != localKeychain) {
localKeychain = localKeychain.Next = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
else if (buildChain) { // first time only - don't contain modified chain from UDL file
keychain = localKeychain = new NameValuePair(realkeyname, keyvalue, nextStartPosition - startPosition);
}
}
#if DEBUG
}
catch(ArgumentException e) {
ParseComparison(parsetable, connectionString, synonyms, firstKey, e);
throw;
}
ParseComparison(parsetable, connectionString, synonyms, firstKey, null);
#endif
return keychain;
}
internal NameValuePair ReplacePasswordPwd(out string constr, bool fakePassword) {
bool expanded = false;
int copyPosition = 0;
NameValuePair head = null, tail = null, next = null;
StringBuilder builder = new StringBuilder(_usersConnectionString.Length);
for(NameValuePair current = KeyChain; null != current; current = current.Next) {
if ((KEY.Password != current.Name) && (SYNONYM.Pwd != current.Name)) {
builder.Append(_usersConnectionString, copyPosition, current.Length);
if (fakePassword) {
next = new NameValuePair(current.Name, current.Value, current.Length);
}
}
else if (fakePassword) { // replace user password/pwd value with *
const string equalstar = "=*;";
builder.Append(current.Name).Append(equalstar);
next = new NameValuePair(current.Name, "*", current.Name.Length + equalstar.Length);
expanded = true;
}
else { // drop the password/pwd completely in returning for user
expanded = true;
}
if (fakePassword) {
if (null != tail) {
tail = tail.Next = next;
}
else {
tail = head = next;
}
}
copyPosition += current.Length;
}
Debug.Assert(expanded, "password/pwd was not removed");
constr = builder.ToString();
return head;
}
internal static void ValidateKeyValuePair(string keyword, string value) {
if ((null == keyword) || !ConnectionStringValidKeyRegex.IsMatch(keyword)) {
throw ADP.InvalidKeyname(keyword);
}
if ((null != value) && !ConnectionStringValidValueRegex.IsMatch(value)) {
throw ADP.InvalidValue(keyword);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.