context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using System.Collections;
#if NET20
using Medivh.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Globalization;
using Medivh.Json.Serialization;
namespace Medivh.Json.Utilities
{
internal static class CollectionUtils
{
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(ICollection<T> collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Adds the elements of the specified collection to the specified generic IList.
/// </summary>
/// <param name="initial">The list to add to.</param>
/// <param name="collection">The collection of elements to add.</param>
public static void AddRange<T>(this IList<T> initial, IEnumerable<T> collection)
{
if (initial == null)
{
throw new ArgumentNullException(nameof(initial));
}
if (collection == null)
{
return;
}
foreach (T value in collection)
{
initial.Add(value);
}
}
#if (NET20 || NET35 || PORTABLE40)
public static void AddRange<T>(this IList<T> initial, IEnumerable collection)
{
ValidationUtils.ArgumentNotNull(initial, nameof(initial));
// because earlier versions of .NET didn't support covariant generics
initial.AddRange(collection.Cast<T>());
}
#endif
public static bool IsDictionaryType(Type type)
{
ValidationUtils.ArgumentNotNull(type, nameof(type));
if (typeof(IDictionary).IsAssignableFrom(type))
{
return true;
}
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>)))
{
return true;
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IReadOnlyDictionary<,>)))
{
return true;
}
#endif
return false;
}
public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType)
{
Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType);
ConstructorInfo match = null;
foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance))
{
IList<ParameterInfo> parameters = constructor.GetParameters();
if (parameters.Count == 1)
{
if (genericEnumerable == parameters[0].ParameterType)
{
// exact match
match = constructor;
break;
}
// incase we can't find an exact match, use first inexact
if (match == null)
{
if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType))
{
match = constructor;
}
}
}
}
return match;
}
public static bool AddDistinct<T>(this IList<T> list, T value)
{
return list.AddDistinct(value, EqualityComparer<T>.Default);
}
public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer)
{
if (list.ContainsValue(value, comparer))
{
return false;
}
list.Add(value);
return true;
}
// this is here because LINQ Bridge doesn't support Contains with IEqualityComparer<T>
public static bool ContainsValue<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
{
if (comparer == null)
{
comparer = EqualityComparer<TSource>.Default;
}
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
foreach (TSource local in source)
{
if (comparer.Equals(local, value))
{
return true;
}
}
return false;
}
public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer)
{
bool allAdded = true;
foreach (T value in values)
{
if (!list.AddDistinct(value, comparer))
{
allAdded = false;
}
}
return allAdded;
}
public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
int index = 0;
foreach (T value in collection)
{
if (predicate(value))
{
return index;
}
index++;
}
return -1;
}
public static bool Contains(this IEnumerable list, object value, IEqualityComparer comparer)
{
foreach (object item in list)
{
if (comparer.Equals(item, value))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer{TSource}.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="list">A sequence in which to locate a value.</param>
/// <param name="value">The object to locate in the sequence</param>
/// <param name="comparer">An equality comparer to compare values.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, ?.</returns>
public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value, IEqualityComparer<TSource> comparer)
{
int index = 0;
foreach (TSource item in list)
{
if (comparer.Equals(item, value))
{
return index;
}
index++;
}
return -1;
}
private static IList<int> GetDimensions(IList values, int dimensionsCount)
{
IList<int> dimensions = new List<int>();
IList currentArray = values;
while (true)
{
dimensions.Add(currentArray.Count);
// don't keep calculating dimensions for arrays inside the value array
if (dimensions.Count == dimensionsCount)
{
break;
}
if (currentArray.Count == 0)
{
break;
}
object v = currentArray[0];
if (v is IList)
{
currentArray = (IList)v;
}
else
{
break;
}
}
return dimensions;
}
private static void CopyFromJaggedToMultidimensionalArray(IList values, Array multidimensionalArray, int[] indices)
{
int dimension = indices.Length;
if (dimension == multidimensionalArray.Rank)
{
multidimensionalArray.SetValue(JaggedArrayGetValue(values, indices), indices);
return;
}
int dimensionLength = multidimensionalArray.GetLength(dimension);
IList list = (IList)JaggedArrayGetValue(values, indices);
int currentValuesLength = list.Count;
if (currentValuesLength != dimensionLength)
{
throw new Exception("Cannot deserialize non-cubical array as multidimensional array.");
}
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
for (int i = 0; i < multidimensionalArray.GetLength(dimension); i++)
{
newIndices[dimension] = i;
CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, newIndices);
}
}
private static object JaggedArrayGetValue(IList values, int[] indices)
{
IList currentList = values;
for (int i = 0; i < indices.Length; i++)
{
int index = indices[i];
if (i == indices.Length - 1)
{
return currentList[index];
}
else
{
currentList = (IList)currentList[index];
}
}
return currentList;
}
public static Array ToMultidimensionalArray(IList values, Type type, int rank)
{
IList<int> dimensions = GetDimensions(values, rank);
while (dimensions.Count < rank)
{
dimensions.Add(0);
}
Array multidimensionalArray = Array.CreateInstance(type, dimensions.ToArray());
CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, new int[0]);
return multidimensionalArray;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace SuperPMICollection
{
public class SpmiException : Exception
{
public SpmiException() : base()
{ }
public SpmiException(string message)
: base(message)
{ }
public SpmiException(string message, Exception innerException)
: base(message, innerException)
{ }
}
internal class Global
{
// Arguments to the program. These should not be touched by Initialize(), as they are set earlier than that.
internal static bool SkipCleanup = false; // Should we skip all cleanup? That is, should we keep all temporary files? Useful for debugging.
// Computed values based on the environment and platform.
internal static bool IsWindows { get; private set; }
internal static bool IsOSX { get; private set; }
internal static bool IsLinux { get; private set; }
internal static string CoreRoot { get; private set; }
internal static string StandaloneJitName { get; private set; }
internal static string CollectorShimName { get; private set; }
internal static string SuperPmiToolName { get; private set; }
internal static string McsToolName { get; private set; }
internal static string JitPath { get; private set; } // Path to the standalone JIT
internal static string SuperPmiPath { get; private set; } // Path to superpmi.exe
internal static string McsPath { get; private set; } // Path to mcs.exe
// Initialize the global state. Don't use a class constructor, because we might throw exceptions
// that we want to catch.
public static void Initialize()
{
string core_root_raw = System.Environment.GetEnvironmentVariable("CORE_ROOT");
if (String.IsNullOrEmpty(core_root_raw))
{
throw new SpmiException("Environment variable CORE_ROOT is not set");
}
try
{
CoreRoot = System.IO.Path.GetFullPath(core_root_raw);
}
catch (Exception ex)
{
throw new SpmiException("Illegal CORE_ROOT environment variable (" + core_root_raw + "), exception: " + ex.Message);
}
IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
IsOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
if (IsWindows)
{
StandaloneJitName = "clrjit.dll";
CollectorShimName = "superpmi-shim-collector.dll";
SuperPmiToolName = "superpmi.exe";
McsToolName = "mcs.exe";
}
else if (IsLinux)
{
StandaloneJitName = "libclrjit.so";
CollectorShimName = "libsuperpmi-shim-collector.so";
SuperPmiToolName = "superpmi";
McsToolName = "mcs";
}
else if (IsOSX)
{
StandaloneJitName = "libclrjit.dylib";
CollectorShimName = "libsuperpmi-shim-collector.dylib";
SuperPmiToolName = "superpmi";
McsToolName = "mcs";
}
else
{
throw new SpmiException("Unknown platform");
}
JitPath = Path.Combine(CoreRoot, StandaloneJitName);
SuperPmiPath = Path.Combine(CoreRoot, SuperPmiToolName);
McsPath = Path.Combine(CoreRoot, McsToolName);
}
}
internal class SuperPMICollectionClass
{
private static string s_tempDir = null; // Temporary directory where we will put the MC files, MCH files, MCL files, and TOC.
private static string s_baseFailMclFile = null; // Pathname for a temporary .MCL file used for noticing superpmi replay failures against base MCH.
private static string s_finalFailMclFile = null; // Pathname for a temporary .MCL file used for noticing superpmi replay failures against final MCH.
private static string s_baseMchFile = null; // The base .MCH file path
private static string s_cleanMchFile = null; // The clean .MCH file path
private static string s_finalMchFile = null; // The clean thin unique .MCH file path
private static string s_tocFile = null; // The .TOC file path for the clean thin unique .MCH file
private static string s_errors = ""; // Collect non-fatal file delete errors to display at the end of the collection process.
private static bool s_saveFinalMchFile = false; // Should we save the final MCH file, or delete it?
private static void SafeFileDelete(string filePath)
{
try
{
File.Delete(filePath);
}
catch(Exception ex)
{
string err = string.Format("Error deleting file \"{0}\": {1}", filePath, ex.Message);
s_errors += err + System.Environment.NewLine;
Console.Error.WriteLine(err);
}
}
private static void CreateTempDirectory(string tempPath)
{
if (tempPath == null)
{
tempPath = Path.GetTempPath();
}
s_tempDir = Path.Combine(tempPath, Path.GetRandomFileName() + "SPMI");
if (Directory.Exists(s_tempDir))
{
throw new SpmiException("temporary directory already exists: " + s_tempDir);
}
DirectoryInfo di = Directory.CreateDirectory(s_tempDir);
}
private static void ChooseFilePaths(string outputMchPath)
{
s_baseFailMclFile = Path.Combine(s_tempDir, "basefail.mcl");
s_finalFailMclFile = Path.Combine(s_tempDir, "finalfail.mcl");
s_baseMchFile = Path.Combine(s_tempDir, "base.mch");
s_cleanMchFile = Path.Combine(s_tempDir, "clean.mch");
if (outputMchPath == null)
{
s_saveFinalMchFile = false;
s_finalMchFile = Path.Combine(s_tempDir, "final.mch");
s_tocFile = Path.Combine(s_tempDir, "final.mch.mct");
}
else
{
s_saveFinalMchFile = true;
s_finalMchFile = Path.GetFullPath(outputMchPath);
s_tocFile = s_finalMchFile + ".mct";
}
}
private static int RunProgram(string program, string arguments)
{
// If the program is a script, move the program name into the arguments, and run it
// under the appropriate shell.
if (Global.IsWindows)
{
if ((program.LastIndexOf(".bat") != -1) || (program.LastIndexOf(".cmd") != -1))
{
string programArgumentSep = String.IsNullOrEmpty(arguments) ? "" : " ";
arguments = "/c " + program + programArgumentSep + arguments;
program = Environment.GetEnvironmentVariable("ComSpec"); // path to CMD.exe
}
}
else
{
if (program.LastIndexOf(".sh") != -1)
{
string programArgumentSep = String.IsNullOrEmpty(arguments) ? "" : " ";
arguments = "bash " + program + programArgumentSep + arguments;
program = "/usr/bin/env";
}
}
Console.WriteLine("Running: " + program + " " + arguments);
Process p = Process.Start(program, arguments);
p.WaitForExit();
return p.ExitCode;
}
// Run a single test from the coreclr test binary drop.
// This works even if given a test path in Windows file system format (e.g.,
// "c:\foo\bar\runit.cmd") when run on Unix. It converts to Unix path format and replaces
// the ".cmd" with ".sh" before attempting to run the script.
private static void RunTest(string testName)
{
string testDir;
if (Global.IsWindows)
{
int lastIndex = testName.LastIndexOf("\\");
if (lastIndex == -1)
{
throw new SpmiException("test path doesn't have any directory separators? " + testName);
}
testDir = testName.Substring(0, lastIndex);
}
else
{
// Just in case we've been given a test name in Windows format, convert it to Unix format here.
testName = testName.Replace("\\", "/");
testName = testName.Replace(".cmd", ".sh");
testName = testName.Replace(".bat", ".sh");
// The way tests are run on Linux, we might need to do some setup. In particular,
// if the test scripts are copied from Windows, we need to convert line endings
// to Unix line endings, and make the script executable. We can always do this
// more than once. This same transformation is done in runtest.sh.
// Review: RunProgram doesn't seem to work if the program isn't a full path.
RunProgram("/usr/bin/perl", @"-pi -e 's/\r\n|\n|\r/\n/g' " + "\"" + testName + "\"");
RunProgram("/bin/chmod", "+x \"" + testName + "\"");
// Now, figure out how to run the test.
int lastIndex = testName.LastIndexOf("/");
if (lastIndex == -1)
{
throw new SpmiException("test path doesn't have any directory separators? " + testName);
}
testDir = testName.Substring(0, lastIndex);
}
// Run the script in the same directory where the test lives.
string originalDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(testDir);
try
{
RunProgram(testName, "");
}
finally
{
// Restore the original current directory from before the test run.
Directory.SetCurrentDirectory(originalDir);
}
}
// Run all the programs from the CoreCLR test binary drop we wish to run while collecting MC files.
private static void RunTestProgramsWhileCollecting()
{
// The list of all programs from the CoreCLR repo test binary drop that
// we should run when doing the SuperPMI collection. This is currently a
// hard-coded list of the relative paths within the test build binaries
// directory of the Windows .cmd files used to run a test. For non-Windows
// platforms, the .cmd is replaced by .sh, and the path separator character
// is changed.
//
// TODO: this should probably be loaded dynamically from a .json/.xml file.
string[] SuperPMICollectionTestProgramsList =
{
@"JIT\Performance\CodeQuality\Roslyn\CscBench\CscBench.cmd",
@"JIT\Methodical\fp\exgen\10w5d_cs_do\10w5d_cs_do.cmd",
@"JIT\Generics\Coverage\chaos65204782cs\chaos65204782cs.cmd"
};
// Figure out the root of the test binaries directory.
// Perhaps this (or something similar) would be a better way to figure out the binary root dir:
// testBinaryRootDir = System.IO.Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
string thisTestDir = Directory.GetCurrentDirectory();
int lastIndex = thisTestDir.LastIndexOf("JIT");
if (lastIndex == -1)
{
throw new SpmiException("we expect the current directory when the test is run to be within the JIT test binaries tree, but it is not: " + thisTestDir);
}
string testBinaryRootDir = thisTestDir.Substring(0, lastIndex);
// Run the tests
foreach (string test in SuperPMICollectionTestProgramsList)
{
string testFullPath = Path.Combine(testBinaryRootDir, test);
try
{
RunTest(testFullPath);
}
catch (SpmiException ex)
{
// Ignore failures running the test. We don't really care if they pass or not
// as long as they generate some .MC files. Plus, I'm not sure how confident
// we can be in getting a correct error code.
Console.Error.WriteLine("WARNING: test failed (ignoring): " + ex.Message);
}
}
}
// Run all the programs we wish to run while collecting MC files.
private static void RunProgramsWhileCollecting(string runProgramPath, string runProgramArguments)
{
if (runProgramPath == null)
{
// No program was given to use for collection, so use our default set.
RunTestProgramsWhileCollecting();
}
else
{
RunProgram(runProgramPath, runProgramArguments);
}
}
// Collect MC files:
// a. Set environment variables
// b. Run tests
// c. Un-set environment variables
// d. Check that something was generated
private static void CollectMCFiles(string runProgramPath, string runProgramArguments)
{
// Set environment variables.
Console.WriteLine("Setting environment variables:");
Console.WriteLine(" SuperPMIShimLogPath=" + s_tempDir);
Console.WriteLine(" SuperPMIShimPath=" + Global.JitPath);
Console.WriteLine(" COMPlus_AltJit=*");
Console.WriteLine(" COMPlus_AltJitName=" + Global.CollectorShimName);
Environment.SetEnvironmentVariable("SuperPMIShimLogPath", s_tempDir);
Environment.SetEnvironmentVariable("SuperPMIShimPath", Global.JitPath);
Environment.SetEnvironmentVariable("COMPlus_AltJit", "*");
Environment.SetEnvironmentVariable("COMPlus_AltJitName", Global.CollectorShimName);
RunProgramsWhileCollecting(runProgramPath, runProgramArguments);
// Un-set environment variables
Environment.SetEnvironmentVariable("SuperPMIShimLogPath", "");
Environment.SetEnvironmentVariable("SuperPMIShimPath", "");
Environment.SetEnvironmentVariable("COMPlus_AltJit", "");
Environment.SetEnvironmentVariable("COMPlus_AltJitName", "");
// Did any .mc files get generated?
string[] mcFiles = Directory.GetFiles(s_tempDir, "*.mc");
if (mcFiles.Length == 0)
{
throw new SpmiException("no .mc files generated");
}
}
// Merge MC files:
// mcs -merge <s_baseMchFile> <s_tempDir>\*.mc -recursive
private static void MergeMCFiles()
{
string pattern = Path.Combine(s_tempDir, "*.mc");
RunProgram(Global.McsPath, "-merge " + s_baseMchFile + " " + pattern + " -recursive");
if (!File.Exists(s_baseMchFile))
{
throw new SpmiException("file missing: " + s_baseMchFile);
}
if (!Global.SkipCleanup)
{
// All the individual MC files are no longer necessary, now that we've merged them into the base.mch. Delete them.
string[] mcFiles = Directory.GetFiles(s_tempDir, "*.mc");
foreach (string mcFile in mcFiles)
{
SafeFileDelete(mcFile);
}
}
}
// Create clean MCH file:
// <superPmiPath> -p -f <s_baseFailMclFile> <s_baseMchFile> <jitPath>
// if <s_baseFailMclFile> is non-empty:
// <mcl> -strip <s_baseFailMclFile> <s_baseMchFile> <s_cleanMchFile>
// else:
// s_cleanMchFile = s_baseMchFile // no need to copy; just change string names (and null out s_baseMchFile so we don't try to delete twice)
// del <s_baseFailMclFile>
private static void CreateCleanMCHFile()
{
RunProgram(Global.SuperPmiPath, "-p -f " + s_baseFailMclFile + " " + s_baseMchFile + " " + Global.JitPath);
if (File.Exists(s_baseFailMclFile) && !String.IsNullOrEmpty(File.ReadAllText(s_baseFailMclFile)))
{
RunProgram(Global.McsPath, "-strip " + s_baseMchFile + " " + s_cleanMchFile);
}
else
{
// Instead of stripping the file, just set s_cleanMchFile = s_baseMchFile and
// null out s_baseMchFile so we don't try to delete the same file twice.
// Note that we never use s_baseMchFile after this function is called.
s_cleanMchFile = s_baseMchFile;
s_baseMchFile = null;
}
if (!File.Exists(s_cleanMchFile))
{
throw new SpmiException("file missing: " + s_cleanMchFile);
}
if (!Global.SkipCleanup)
{
if (File.Exists(s_baseFailMclFile))
{
SafeFileDelete(s_baseFailMclFile);
s_baseFailMclFile = null;
}
// The base file is no longer used (unless there was no cleaning done, in which case
// s_baseMchFile has been null-ed and s_cleanMchFile points at the base file).
if ((s_baseMchFile != null) && File.Exists(s_baseMchFile))
{
SafeFileDelete(s_baseMchFile);
s_baseMchFile = null;
}
}
}
// Create a thin unique MCH:
// <mcl> -removeDup -thin <s_cleanMchFile> <s_finalMchFile>
private static void CreateThinUniqueMCH()
{
RunProgram(Global.McsPath, "-removeDup -thin " + s_cleanMchFile + " " + s_finalMchFile);
if (!File.Exists(s_finalMchFile))
{
throw new SpmiException("file missing: " + s_finalMchFile);
}
if (!Global.SkipCleanup)
{
// The clean file is no longer used; delete it.
if ((s_cleanMchFile != null) && File.Exists(s_cleanMchFile))
{
SafeFileDelete(s_cleanMchFile);
s_cleanMchFile = null;
}
}
}
// Create a TOC file:
// <mcl> -toc <s_finalMchFile>
// // check that .mct file was created
private static void CreateTOC()
{
RunProgram(Global.McsPath, "-toc " + s_finalMchFile);
if (!File.Exists(s_tocFile))
{
throw new SpmiException("file missing: " + s_tocFile);
}
}
// Verify the resulting MCH file is error-free when running superpmi against it with the same JIT used for collection.
// <superPmiPath> -p -f <s_finalFailMclFile> <s_finalMchFile> <jitPath>
// if <s_finalFailMclFile> is non-empty:
// // error!
private static void VerifyFinalMCH()
{
RunProgram(Global.SuperPmiPath, "-p -f " + s_finalFailMclFile + " " + s_finalMchFile + " " + Global.JitPath);
if (!File.Exists(s_finalFailMclFile) || !String.IsNullOrEmpty(File.ReadAllText(s_finalFailMclFile)))
{
throw new SpmiException("replay of final file is not error free");
}
if (!Global.SkipCleanup)
{
if (File.Exists(s_finalFailMclFile))
{
SafeFileDelete(s_finalFailMclFile);
s_finalFailMclFile = null;
}
}
}
// Cleanup. If we get here due to a failure of some kind, we want to do full cleanup. If we get here as part
// of normal shutdown processing, we want to keep the s_finalMchFile and s_tocFile if s_saveFinalMchFile == true.
// del <s_baseMchFile>
// del <s_cleanMchFile>
// del <s_finalMchFile>
// del <s_tocFile>
// rmdir <s_tempDir>
private static void Cleanup()
{
if (Global.SkipCleanup)
return;
try
{
if ((s_baseFailMclFile != null) && File.Exists(s_baseFailMclFile))
{
SafeFileDelete(s_baseFailMclFile);
s_baseFailMclFile = null;
}
if ((s_baseMchFile != null) && File.Exists(s_baseMchFile))
{
SafeFileDelete(s_baseMchFile);
s_baseMchFile = null;
}
if ((s_cleanMchFile != null) && File.Exists(s_cleanMchFile))
{
SafeFileDelete(s_cleanMchFile);
s_cleanMchFile = null;
}
if (!s_saveFinalMchFile)
{
// Note that if we fail to create the TOC, but we already
// successfully created the MCH file, and the user wants to
// keep the final result, then we will still keep the final
// MCH file. We'll also keep it if the verify pass fails.
if ((s_finalMchFile != null) && File.Exists(s_finalMchFile))
{
SafeFileDelete(s_finalMchFile);
}
if ((s_tocFile != null) && File.Exists(s_tocFile))
{
SafeFileDelete(s_tocFile);
}
}
if ((s_finalFailMclFile != null) && File.Exists(s_finalFailMclFile))
{
SafeFileDelete(s_finalFailMclFile);
s_finalFailMclFile = null;
}
if ((s_tempDir != null) && Directory.Exists(s_tempDir))
{
Directory.Delete(s_tempDir, /* delete recursively */ true);
}
}
catch (Exception ex)
{
Console.Error.WriteLine("ERROR during cleanup: " + ex.Message);
}
}
public static int Collect(string outputMchPath, string runProgramPath, string runProgramArguments, string tempPath)
{
// Do a basic SuperPMI collect and validation:
// 1. Collect MC files by running a set of sample apps.
// 2. Merge the MC files into a single MCH using "mcs -merge *.mc -recursive".
// 3. Create a clean MCH by running superpmi over the MCH, and using "mcs -strip" to filter
// out any failures (if any).
// 4. Create a thin unique MCH by using "mcs -removeDup -thin".
// 5. Create a TOC using "mcs -toc".
// 6. Verify the resulting MCH file is error-free when running superpmi against it with the
// same JIT used for collection.
//
// MCH files are big. If we don't need them anymore, clean them up right away to avoid
// running out of disk space in disk constrained situations.
string thisTask = "SuperPMI collection and playback";
Console.WriteLine(thisTask + " - BEGIN");
int result = 101; // assume error (!= 100)
try
{
CreateTempDirectory(tempPath);
ChooseFilePaths(outputMchPath);
CollectMCFiles(runProgramPath, runProgramArguments);
MergeMCFiles();
CreateCleanMCHFile();
CreateThinUniqueMCH();
CreateTOC();
VerifyFinalMCH();
// Success!
result = 100;
}
catch (SpmiException ex)
{
Console.Error.WriteLine("ERROR: " + ex.Message);
result = 101;
}
catch (Exception ex)
{
Console.Error.WriteLine("ERROR: unknown exception running collection: " + ex.Message);
result = 101;
}
finally
{
Cleanup();
}
// Re-display the file delete errors, if any, in case they got lost in the output so far.
if (!String.IsNullOrEmpty(s_errors))
{
Console.Error.WriteLine("Non-fatal errors occurred during processing:");
Console.Error.Write(s_errors);
}
if (result == 100)
{
Console.WriteLine(thisTask + " - SUCCESS");
}
else
{
Console.WriteLine(thisTask + " - FAILED");
}
return result;
}
}
internal class Program
{
private static void Usage()
{
// Unfortunately, under CoreCLR, this just gets is the path to CoreRun.exe:
// string thisProgram = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
string thisProgram = "superpmicollect";
Console.WriteLine("Usage: {0} [arguments]", thisProgram);
Console.WriteLine(" where [arguments] is zero or more of:");
Console.WriteLine(" -? | -help : Display this help text.");
Console.WriteLine(" -mch <file> : Specify the name of the generated clean/thin/unique MCH file.");
Console.WriteLine(" The MCH file is retained (by default, the final MCH file is deleted).");
Console.WriteLine(" -run <program> [arguments...] : This program (or script) is invoked to run any number");
Console.WriteLine(" of programs during MC collection. All arguments after");
Console.WriteLine(" <program> are passed to <program> as its arguments.");
Console.WriteLine(" Thus, -run must be the last argument.");
Console.WriteLine(" -skipCleanup : Do not delete any intermediate files created during processing.");
Console.WriteLine(" -temp <dir> : A newly created, randomly-named, subdirectory of this");
Console.WriteLine(" directory will be used to store all temporary files.");
Console.WriteLine(" By default, the user temporary directory is used");
Console.WriteLine(" (%TEMP% on Windows, /tmp on Unix).");
Console.WriteLine(" Since SuperPMI collections generate a lot of data, this option");
Console.WriteLine(" is useful if the normal temporary directory doesn't have enough space.");
Console.WriteLine("");
Console.WriteLine("This program performs a collection of SuperPMI data. With no arguments, a hard-coded list of");
Console.WriteLine("programs are run during collection. With the -run argument, the user species which apps are run.");
Console.WriteLine("");
Console.WriteLine("If -mch is not given, all generated files are deleted, and the result is simply the exit code");
Console.WriteLine("indicating whether the collection succeeded. This is useful as a test.");
Console.WriteLine("");
Console.WriteLine("If the COMPlus_AltJit variable is already set, it is assumed SuperPMI collection is already happening,");
Console.WriteLine("and the program exits with success.");
Console.WriteLine("");
Console.WriteLine("On success, the return code is 100.");
}
private static int Main(string[] args)
{
string outputMchPath = null;
string runProgramPath = null;
string runProgramArguments = null;
string tempPath = null;
// Parse arguments
if (args.Length > 0)
{
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
default:
Usage();
return 101;
case "-?":
Usage();
return 101;
case "-help":
Usage();
return 101;
case "-skipCleanup":
Global.SkipCleanup = true;
break;
case "-mch":
i++;
if (i >= args.Length)
{
Console.Error.WriteLine("Error: missing argument to -mch");
Usage();
return 101;
}
outputMchPath = args[i];
if (!outputMchPath.EndsWith(".mch"))
{
// We need the resulting file to end with ".mch". If the user didn't specify this, then simply add it.
// Thus, if the user specifies "-mch foo", we'll generate foo.mch (and TOC file foo.mch.mct).
outputMchPath += ".mch";
}
outputMchPath = Path.GetFullPath(outputMchPath);
break;
case "-run":
i++;
if (i >= args.Length)
{
Console.Error.WriteLine("Error: missing argument to -run");
Usage();
return 101;
}
runProgramPath = Path.GetFullPath(args[i]);
if (!File.Exists(runProgramPath))
{
Console.Error.WriteLine("Error: couldn't find program {0}", runProgramPath);
return 101;
}
// The rest of the arguments, if any, are passed as arguments to the run program.
i++;
if (i < args.Length)
{
string[] runArgumentsArray = new string[args.Length - i];
for (int j = 0; i < args.Length; i++, j++)
{
runArgumentsArray[j] = args[i];
}
runProgramArguments = string.Join(" ", runArgumentsArray);
}
break;
case "-temp":
i++;
if (i >= args.Length)
{
Console.Error.WriteLine("Error: missing argument to -temp");
Usage();
return 101;
}
tempPath = args[i];
break;
}
}
}
// Done with argument parsing.
string altjitvar = System.Environment.GetEnvironmentVariable("COMPlus_AltJit");
if (!String.IsNullOrEmpty(altjitvar))
{
// Someone already has the COMPlus_AltJit variable set. We don't want to override
// that. Perhaps someone is already doing a SuperPMI collection and invokes this
// program as part of a full test path in which this program exists.
Console.WriteLine("COMPlus_AltJit already exists: skipping SuperPMI collection and returning success");
return 100;
}
int result;
try
{
Global.Initialize();
result = SuperPMICollectionClass.Collect(outputMchPath, runProgramPath, runProgramArguments, tempPath);
}
catch (SpmiException ex)
{
Console.Error.WriteLine("ERROR: " + ex.Message);
result = 101;
}
catch (Exception ex)
{
Console.Error.WriteLine("ERROR: unknown exception running collection: " + ex.Message);
result = 101;
}
return result;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using osu.Framework.Configuration;
using osu.Framework.Configuration.Tracking;
using osu.Framework.Extensions;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osu.Game.Localisation;
using osu.Game.Overlays;
using osu.Game.Rulesets.Scoring;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Configuration
{
[ExcludeFromDynamicCompile]
public class OsuConfigManager : IniConfigManager<OsuSetting>
{
protected override void InitialiseDefaults()
{
// UI/selection defaults
SetDefault(OsuSetting.Ruleset, string.Empty);
SetDefault(OsuSetting.Skin, 0, -1, int.MaxValue);
SetDefault(OsuSetting.BeatmapDetailTab, PlayBeatmapDetailArea.TabType.Details);
SetDefault(OsuSetting.BeatmapDetailModsFilter, false);
SetDefault(OsuSetting.ShowConvertedBeatmaps, true);
SetDefault(OsuSetting.DisplayStarsMinimum, 0.0, 0, 10, 0.1);
SetDefault(OsuSetting.DisplayStarsMaximum, 10.1, 0, 10.1, 0.1);
SetDefault(OsuSetting.SongSelectGroupingMode, GroupMode.All);
SetDefault(OsuSetting.SongSelectSortingMode, SortMode.Title);
SetDefault(OsuSetting.RandomSelectAlgorithm, RandomSelectAlgorithm.RandomPermutation);
SetDefault(OsuSetting.ChatDisplayHeight, ChatOverlay.DEFAULT_HEIGHT, 0.2f, 1f);
// Online settings
SetDefault(OsuSetting.Username, string.Empty);
SetDefault(OsuSetting.Token, string.Empty);
SetDefault(OsuSetting.AutomaticallyDownloadWhenSpectating, false);
SetDefault(OsuSetting.SavePassword, false).ValueChanged += enabled =>
{
if (enabled.NewValue) SetValue(OsuSetting.SaveUsername, true);
};
SetDefault(OsuSetting.SaveUsername, true).ValueChanged += enabled =>
{
if (!enabled.NewValue) SetValue(OsuSetting.SavePassword, false);
};
SetDefault(OsuSetting.ExternalLinkWarning, true);
SetDefault(OsuSetting.PreferNoVideo, false);
SetDefault(OsuSetting.ShowOnlineExplicitContent, false);
SetDefault(OsuSetting.NotifyOnUsernameMentioned, true);
SetDefault(OsuSetting.NotifyOnPrivateMessage, true);
// Audio
SetDefault(OsuSetting.VolumeInactive, 0.25, 0, 1, 0.01);
SetDefault(OsuSetting.MenuVoice, true);
SetDefault(OsuSetting.MenuMusic, true);
SetDefault(OsuSetting.AudioOffset, 0, -500.0, 500.0, 1);
// Input
SetDefault(OsuSetting.MenuCursorSize, 1.0f, 0.5f, 2f, 0.01f);
SetDefault(OsuSetting.GameplayCursorSize, 1.0f, 0.1f, 2f, 0.01f);
SetDefault(OsuSetting.AutoCursorSize, false);
SetDefault(OsuSetting.MouseDisableButtons, false);
SetDefault(OsuSetting.MouseDisableWheel, false);
SetDefault(OsuSetting.ConfineMouseMode, OsuConfineMouseMode.DuringGameplay);
// Graphics
SetDefault(OsuSetting.ShowFpsDisplay, false);
SetDefault(OsuSetting.ShowStoryboard, true);
SetDefault(OsuSetting.BeatmapSkins, true);
SetDefault(OsuSetting.BeatmapColours, true);
SetDefault(OsuSetting.BeatmapHitsounds, true);
SetDefault(OsuSetting.CursorRotation, true);
SetDefault(OsuSetting.MenuParallax, true);
// Gameplay
SetDefault(OsuSetting.DimLevel, 0.8, 0, 1, 0.01);
SetDefault(OsuSetting.BlurLevel, 0, 0, 1, 0.01);
SetDefault(OsuSetting.LightenDuringBreaks, true);
SetDefault(OsuSetting.HitLighting, true);
SetDefault(OsuSetting.HUDVisibilityMode, HUDVisibilityMode.Always);
SetDefault(OsuSetting.ShowProgressGraph, true);
SetDefault(OsuSetting.ShowHealthDisplayWhenCantFail, true);
SetDefault(OsuSetting.FadePlayfieldWhenHealthLow, true);
SetDefault(OsuSetting.KeyOverlay, false);
SetDefault(OsuSetting.PositionalHitSounds, true);
SetDefault(OsuSetting.AlwaysPlayFirstComboBreak, true);
SetDefault(OsuSetting.FloatingComments, false);
SetDefault(OsuSetting.ScoreDisplayMode, ScoringMode.Standardised);
SetDefault(OsuSetting.IncreaseFirstObjectVisibility, true);
SetDefault(OsuSetting.GameplayDisableWinKey, true);
// Update
SetDefault(OsuSetting.ReleaseStream, ReleaseStream.Lazer);
SetDefault(OsuSetting.Version, string.Empty);
SetDefault(OsuSetting.ScreenshotFormat, ScreenshotFormat.Jpg);
SetDefault(OsuSetting.ScreenshotCaptureMenuCursor, false);
SetDefault(OsuSetting.SongSelectRightMouseScroll, false);
SetDefault(OsuSetting.Scaling, ScalingMode.Off);
SetDefault(OsuSetting.ScalingSizeX, 0.8f, 0.2f, 1f);
SetDefault(OsuSetting.ScalingSizeY, 0.8f, 0.2f, 1f);
SetDefault(OsuSetting.ScalingPositionX, 0.5f, 0f, 1f);
SetDefault(OsuSetting.ScalingPositionY, 0.5f, 0f, 1f);
SetDefault(OsuSetting.UIScale, 1f, 0.8f, 1.6f, 0.01f);
SetDefault(OsuSetting.UIHoldActivationDelay, 200f, 0f, 500f, 50f);
SetDefault(OsuSetting.IntroSequence, IntroSequence.Triangles);
SetDefault(OsuSetting.MenuBackgroundSource, BackgroundSource.Skin);
SetDefault(OsuSetting.SeasonalBackgroundMode, SeasonalBackgroundMode.Sometimes);
SetDefault(OsuSetting.DiscordRichPresence, DiscordRichPresenceMode.Full);
SetDefault(OsuSetting.EditorWaveformOpacity, 0.25f);
SetDefault(OsuSetting.EditorHitAnimations, false);
}
public OsuConfigManager(Storage storage)
: base(storage)
{
Migrate();
}
public void Migrate()
{
// arrives as 2020.123.0
string rawVersion = Get<string>(OsuSetting.Version);
if (rawVersion.Length < 6)
return;
string[] pieces = rawVersion.Split('.');
// on a fresh install or when coming from a non-release build, execution will end here.
// we don't want to run migrations in such cases.
if (!int.TryParse(pieces[0], out int year)) return;
if (!int.TryParse(pieces[1], out int monthDay)) return;
int combined = (year * 10000) + monthDay;
if (combined < 20210413)
{
SetValue(OsuSetting.EditorWaveformOpacity, 0.25f);
}
}
public override TrackedSettings CreateTrackedSettings()
{
// these need to be assigned in normal game startup scenarios.
Debug.Assert(LookupKeyBindings != null);
Debug.Assert(LookupSkinName != null);
return new TrackedSettings
{
new TrackedSetting<bool>(OsuSetting.MouseDisableButtons, disabledState => new SettingDescription(
rawValue: !disabledState,
name: GlobalActionKeyBindingStrings.ToggleGameplayMouseButtons,
value: disabledState ? CommonStrings.Disabled.ToLower() : CommonStrings.Enabled.ToLower(),
shortcut: LookupKeyBindings(GlobalAction.ToggleGameplayMouseButtons))
),
new TrackedSetting<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode, visibilityMode => new SettingDescription(
rawValue: visibilityMode,
name: GameplaySettingsStrings.HUDVisibilityMode,
value: visibilityMode.GetLocalisableDescription(),
shortcut: new TranslatableString(@"_", @"{0}: {1} {2}: {3}",
GlobalActionKeyBindingStrings.ToggleInGameInterface,
LookupKeyBindings(GlobalAction.ToggleInGameInterface),
GlobalActionKeyBindingStrings.HoldForHUD,
LookupKeyBindings(GlobalAction.HoldForHUD)))
),
new TrackedSetting<ScalingMode>(OsuSetting.Scaling, scalingMode => new SettingDescription(
rawValue: scalingMode,
name: GraphicsSettingsStrings.ScreenScaling,
value: scalingMode.GetLocalisableDescription()
)
),
new TrackedSetting<int>(OsuSetting.Skin, skin =>
{
string skinName = LookupSkinName(skin) ?? string.Empty;
return new SettingDescription(
rawValue: skinName,
name: SkinSettingsStrings.SkinSectionHeader,
value: skinName,
shortcut: new TranslatableString(@"_", @"{0}: {1}",
GlobalActionKeyBindingStrings.RandomSkin,
LookupKeyBindings(GlobalAction.RandomSkin))
);
}),
new TrackedSetting<float>(OsuSetting.UIScale, scale => new SettingDescription(
rawValue: scale,
name: GraphicsSettingsStrings.UIScaling,
value: $"{scale:N2}x"
// TODO: implement lookup for framework platform key bindings
)
),
};
}
public Func<int, string> LookupSkinName { private get; set; }
public Func<GlobalAction, LocalisableString> LookupKeyBindings { get; set; }
}
// IMPORTANT: These are used in user configuration files.
// The naming of these keys should not be changed once they are deployed in a release, unless migration logic is also added.
public enum OsuSetting
{
Ruleset,
Token,
MenuCursorSize,
GameplayCursorSize,
AutoCursorSize,
DimLevel,
BlurLevel,
LightenDuringBreaks,
ShowStoryboard,
KeyOverlay,
PositionalHitSounds,
AlwaysPlayFirstComboBreak,
FloatingComments,
HUDVisibilityMode,
ShowProgressGraph,
ShowHealthDisplayWhenCantFail,
FadePlayfieldWhenHealthLow,
MouseDisableButtons,
MouseDisableWheel,
ConfineMouseMode,
AudioOffset,
VolumeInactive,
MenuMusic,
MenuVoice,
CursorRotation,
MenuParallax,
BeatmapDetailTab,
BeatmapDetailModsFilter,
Username,
ReleaseStream,
SavePassword,
SaveUsername,
DisplayStarsMinimum,
DisplayStarsMaximum,
SongSelectGroupingMode,
SongSelectSortingMode,
RandomSelectAlgorithm,
ShowFpsDisplay,
ChatDisplayHeight,
Version,
ShowConvertedBeatmaps,
Skin,
ScreenshotFormat,
ScreenshotCaptureMenuCursor,
SongSelectRightMouseScroll,
BeatmapSkins,
BeatmapColours,
BeatmapHitsounds,
IncreaseFirstObjectVisibility,
ScoreDisplayMode,
ExternalLinkWarning,
PreferNoVideo,
Scaling,
ScalingPositionX,
ScalingPositionY,
ScalingSizeX,
ScalingSizeY,
UIScale,
IntroSequence,
NotifyOnUsernameMentioned,
NotifyOnPrivateMessage,
UIHoldActivationDelay,
HitLighting,
MenuBackgroundSource,
GameplayDisableWinKey,
SeasonalBackgroundMode,
EditorWaveformOpacity,
EditorHitAnimations,
DiscordRichPresence,
AutomaticallyDownloadWhenSpectating,
ShowOnlineExplicitContent,
}
}
| |
// Copyright (c) 2017 Jean Ressouche @SouchProd. All rights reserved.
// https://github.com/souchprod/SouchProd.EntityFrameworkCore.Firebird
// This code inherit from the .Net Foundation Entity Core repository (Apache licence)
// and from the Pomelo Foundation Mysql provider repository (MIT licence).
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using FirebirdSql.Data.FirebirdClient;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.Migrations
{
public class FbMigrationsSqlGenerator : MigrationsSqlGenerator
{
private static readonly Regex TypeRe = new Regex(@"([a-z0-9]+)\s*?(?:\(\s*(\d+)?\s*\))?", RegexOptions.IgnoreCase);
private readonly IFirebirdOptions _options;
public FbMigrationsSqlGenerator(
[NotNull] MigrationsSqlGeneratorDependencies dependencies,
[NotNull] IFirebirdOptions options)
: base(dependencies)
{
_options = options;
}
protected override void Generate([NotNull] MigrationOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
var createDatabaseOperation = operation as FbCreateDatabaseOperation;
if (createDatabaseOperation != null)
{
Generate(createDatabaseOperation, model, builder);
builder.EndCommand();
return;
}
var dropDatabaseOperation = operation as FbDropDatabaseOperation;
if (dropDatabaseOperation is FbDropDatabaseOperation)
{
Generate(dropDatabaseOperation, model, builder);
builder.EndCommand();
return;
}
base.Generate(operation, model, builder);
}
protected override void Generate(DropColumnOperation operation, IModel model, MigrationCommandListBuilder builder)
{
var identifier = Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema);
var alterBase = $"ALTER TABLE {identifier} DROP {Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)}";
builder.Append(alterBase).Append(Dependencies.SqlGenerationHelper.StatementTerminator);
EndStatement(builder);
}
protected override void Generate(AlterColumnOperation operation, IModel model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
var type = operation.ColumnType;
if (operation.ColumnType == null)
{
var property = FindProperty(model, operation.Schema, operation.Table, operation.Name);
type = property != null
? Dependencies.TypeMapper.GetMapping(property).StoreType
: Dependencies.TypeMapper.GetMapping(operation.ClrType).StoreType;
}
var identifier = Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema);
var alterBase = $"ALTER TABLE {identifier} ALTER COLUMN {Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)}";
// TYPE
builder.Append(alterBase)
.Append(" ")
.Append(type)
.Append(operation.IsNullable ? " NULL" : " NOT NULL")
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
if(!type.StartsWith("BLOB", StringComparison.Ordinal))
{
alterBase = $"ALTER TABLE {identifier} ALTER COLUMN {Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)}";
builder.Append(alterBase);
if (operation.DefaultValue != null)
{
var typeMapping = Dependencies.TypeMapper.GetMapping(operation.DefaultValue.GetType());
builder.Append(" SET DEFAULT ")
.Append(typeMapping.GenerateSqlLiteral(operation.DefaultValue))
.AppendLine(Dependencies.SqlGenerationHelper.BatchTerminator);
}
else if (!string.IsNullOrWhiteSpace(operation.DefaultValueSql))
{
builder.Append(" SET DEFAULT ")
.Append(operation.DefaultValueSql)
.AppendLine(Dependencies.SqlGenerationHelper.BatchTerminator);
}
else
{
builder.Append(" DROP DEFAULT;");
}
}
EndStatement(builder);
}
protected override void Generate(CreateSequenceOperation operation, IModel model, MigrationCommandListBuilder builder)
{
throw new NotSupportedException("Firebird doesn't support sequence operation.");
}
protected override void Generate(RenameIndexOperation operation, IModel model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
if (operation.NewName != null)
{
var createTableSyntax = _options.GetCreateTable(Dependencies.SqlGenerationHelper, operation.Table, operation.Schema);
if (createTableSyntax == null)
throw new InvalidOperationException($"Could not find the CREATE TABLE DDL for the table: '{Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)}'");
var indexDefinitionRe = new Regex($"^\\s*((?:UNIQUE\\s)?KEY\\s)?{operation.Name}?(.*)$", RegexOptions.Multiline);
var match = indexDefinitionRe.Match(createTableSyntax);
string newIndexDefinition;
if (match.Success)
newIndexDefinition = match.Groups[1].Value + Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName) + " " + match.Groups[2].Value.Trim().TrimEnd(',');
else
throw new InvalidOperationException($"Could not find column definition for table: '{Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema)}' column: {operation.Name}");
builder
.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" DROP INDEX ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name))
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
EndStatement(builder);
builder
.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" ADD ")
.Append(newIndexDefinition)
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
EndStatement(builder);
}
}
protected override void Generate(RenameSequenceOperation operation, IModel model, MigrationCommandListBuilder builder)
{
throw new NotSupportedException("Firebird doesn't support sequence operation.");
}
protected override void Generate(RenameTableOperation operation, IModel model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
// In Progress: Create a new temp table, move the data into, delete previous table.
var createTableSyntax = _options.GetCreateTable(Dependencies.SqlGenerationHelper, operation.Name, operation.Schema);
createTableSyntax = createTableSyntax?.Replace(operation.Name, operation.NewName) ?? throw new InvalidOperationException($"Could not find the CREATE TABLE DDL for the table: '{Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.Schema)}'");
builder.Append(createTableSyntax);
builder
.Append("INSERT INTO")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName, operation.Schema))
.Append(" SELECT * FROM ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name, operation.NewSchema));
EndStatement(builder);
}
protected override void Generate([NotNull] CreateIndexOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder, bool terminate)
{
var method = (string)operation[FbAnnotationNames.Prefix];
builder.Append("CREATE ");
if (operation.IsUnique)
{
builder.Append("UNIQUE ");
}
builder
.Append("INDEX ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name.LimitLength(64)))
.Append(" ON ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema));
if (method != null)
{
builder
.Append(" USING ")
.Append(method);
}
builder
.Append(" (")
.Append(ColumnList(operation.Columns))
.Append(")");
if (terminate)
{
builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
EndStatement(builder);
}
}
protected override void Generate(
[NotNull] CreateIndexOperation operation,
[CanBeNull] IModel model,
[NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
Generate(operation, model, builder, true);
}
protected override void Generate(EnsureSchemaOperation operation, IModel model, MigrationCommandListBuilder builder)
{
throw new NotSupportedException("Firebird doesn't support EnsureSchema operation.");
}
public virtual void Generate(FbCreateDatabaseOperation operation, IModel model, MigrationCommandListBuilder builder)
{
throw new NotSupportedException("Firebird doesn't support CreateDatabase operation.");
}
public virtual void Generate(FbDropDatabaseOperation operation, IModel model, MigrationCommandListBuilder builder)
{
throw new NotSupportedException("Firebird doesn't support DropDatabase operation.");
}
protected override void Generate(DropIndexOperation operation, IModel model, MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder
.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" DROP CONSTRAINT ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name))
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
EndStatement(builder);
}
protected override void Generate(
[NotNull] RenameColumnOperation operation,
[CanBeNull] IModel model,
[NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" ALTER ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name))
.Append(" TO ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.NewName));
EndStatement(builder);
}
protected override void ColumnDefinition(
[CanBeNull] string schema,
[NotNull] string table,
[NotNull] string name,
[NotNull] Type clrType,
[CanBeNull] string type,
[CanBeNull] bool? unicode,
[CanBeNull] int? maxLength,
bool rowVersion,
bool nullable,
[CanBeNull] object defaultValue,
[CanBeNull] string defaultValueSql,
[CanBeNull] string computedColumnSql,
[NotNull] IAnnotatable annotatable,
[CanBeNull] IModel model,
[NotNull] MigrationCommandListBuilder builder)
{
Check.NotEmpty(name, nameof(name));
Check.NotNull(annotatable, nameof(annotatable));
Check.NotNull(clrType, nameof(clrType));
Check.NotNull(builder, nameof(builder));
var matchType = type;
var matchLen = "";
var match = TypeRe.Match(type ?? "-");
if (match.Success)
{
matchType = match.Groups[1].Value.ToLower();
if (!string.IsNullOrWhiteSpace(match.Groups[2].Value))
matchLen = match.Groups[2].Value;
}
var autoIncrement = false;
var valueGenerationStrategy = annotatable[FbAnnotationNames.ValueGenerationStrategy] as FirebirdValueGenerationStrategy?;
if ((valueGenerationStrategy == FirebirdValueGenerationStrategy.IdentityColumn) && string.IsNullOrWhiteSpace(defaultValueSql) && defaultValue == null)
{
switch (matchType)
{
case "BIGINT":
case "INTEGER":
autoIncrement = true;
break;
case "TIMESTAMP":
defaultValueSql = $"CURRENT_TIMESTAMP";
break;
}
}
string onUpdateSql = null;
if (valueGenerationStrategy == FirebirdValueGenerationStrategy.ComputedColumn)
{
switch (matchType)
{
case "TIMESTAMP":
if (string.IsNullOrWhiteSpace(defaultValueSql) && defaultValue == null)
defaultValueSql = $"CURRENT_TIMESTAMP";
onUpdateSql = $"CURRENT_TIMESTAMP";
break;
}
}
builder
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(name))
.Append(" ")
.Append(type ?? GetColumnType(schema, table, name, clrType, unicode, maxLength, rowVersion, model));
if (!nullable)
{
builder.Append((autoIncrement && _options.ConnectionSettings.ServerVersion.IdentityColumnsSupported
? " GENERATED BY DEFAULT AS IDENTITY": "") + " NOT NULL");
}
if (!autoIncrement)
{
if (defaultValueSql != null)
{
builder
.Append(" DEFAULT ")
.Append(defaultValueSql);
}
else if (defaultValue != null)
{
var defaultValueLiteral = Dependencies.TypeMapper.GetMapping(clrType);
builder
.Append(" DEFAULT ")
.Append(defaultValueLiteral.GenerateSqlLiteral(defaultValue));
}
if (onUpdateSql != null)
{
builder
.Append(" ON UPDATE ")
.Append(onUpdateSql);
}
}
}
protected override void DefaultValue(object defaultValue, string defaultValueSql, MigrationCommandListBuilder builder)
{
Check.NotNull(builder, nameof(builder));
if (defaultValueSql != null)
{
builder
.Append(" DEFAULT ")
.Append(defaultValueSql);
}
else if (defaultValue != null)
{
var typeMapping = Dependencies.TypeMapper.GetMapping(defaultValue.GetType());
builder
.Append(" DEFAULT ")
.Append(typeMapping.GenerateSqlLiteral(defaultValue));
}
}
protected override void Generate([NotNull] DropForeignKeyOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder
.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" DROP CONSTRAINT ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name))
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
EndStatement(builder);
}
protected override void Generate([NotNull] AddPrimaryKeyOperation operation, [CanBeNull] IModel model, [NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder
.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" ADD ");
PrimaryKeyConstraint(operation, model, builder);
builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator);
var annotations = model.GetAnnotations();
if (operation.Columns.Count() == 1)
{
// TODO
}
EndStatement(builder);
}
protected override void Generate([NotNull] DropPrimaryKeyOperation operation, [CanBeNull] IModel model,
[NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
builder
.Append("ALTER TABLE ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Table, operation.Schema))
.Append(" DROP CONSTRAINT ")
.Append(operation.Name);
EndStatement(builder);
}
public virtual void Rename(
[CanBeNull] string schema,
[NotNull] string name,
[NotNull] string newName,
[NotNull] string type,
[NotNull] MigrationCommandListBuilder builder)
{
Check.NotEmpty(name, nameof(name));
Check.NotEmpty(newName, nameof(newName));
Check.NotEmpty(type, nameof(type));
Check.NotNull(builder, nameof(builder));
builder
.Append("ALTER ")
.Append(type)
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(name, schema))
.Append(" TO ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(newName, schema));
}
protected override void ForeignKeyAction(ReferentialAction referentialAction, MigrationCommandListBuilder builder)
{
Check.NotNull(builder, nameof(builder));
if (referentialAction == ReferentialAction.Restrict)
{
builder.Append("NO ACTION");
}
else
{
base.ForeignKeyAction(referentialAction, builder);
}
}
protected override void ForeignKeyConstraint(
[NotNull] AddForeignKeyOperation operation,
[CanBeNull] IModel model,
[NotNull] MigrationCommandListBuilder builder)
{
Check.NotNull(operation, nameof(operation));
Check.NotNull(builder, nameof(builder));
if (operation.Name != null)
{
builder
.Append("CONSTRAINT ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name.Substring(0, Math.Min(operation.Name.Length, 64))))
.Append(" ");
}
builder
.Append("FOREIGN KEY (")
.Append(ColumnList(operation.Columns))
.Append(") REFERENCES ")
.Append(Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.PrincipalTable, operation.PrincipalSchema));
if (operation.PrincipalColumns != null)
{
builder
.Append(" (")
.Append(ColumnList(operation.PrincipalColumns))
.Append(")");
}
if (operation.OnUpdate != ReferentialAction.NoAction)
{
builder.Append(" ON UPDATE ");
ForeignKeyAction(operation.OnUpdate, builder);
}
if (operation.OnDelete != ReferentialAction.NoAction)
{
builder.Append(" ON DELETE ");
ForeignKeyAction(operation.OnDelete, builder);
}
}
protected override string ColumnList(string[] columns) => string.Join(", ", columns.Select(Dependencies.SqlGenerationHelper.DelimitIdentifier));
}
public static class StringExtensions
{
/// <summary>
/// Method that limits the length of text to a defined length.
/// </summary>
/// <param name="source">The source text.</param>
/// <param name="maxLength">The maximum limit of the string to return.</param>
public static string LimitLength(this string source, int maxLength)
{
if (source.Length <= maxLength)
{
return source;
}
return source.Substring(0, maxLength);
}
}
}
| |
using CommandLineParser.Arguments;
using CommandLineParser.Compatibility;
using CommandLineParser.Exceptions;
using CommandLineParser.Validation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace CommandLineParser
{
/// <summary>
/// CommandLineParser allows user to define command line arguments and then parse
/// the arguments from the command line.
/// </summary>
/// <include file='Doc/CommandLineParser.xml' path='CommandLineParser/Parser/*' />
public class CommandLineParser : IDisposable
{
#region property backing fields
private List<Argument> _arguments = new List<Argument>();
private List<ArgumentCertification> _certifications = new List<ArgumentCertification>();
private Dictionary<char, Argument> _shortNameLookup;
private Dictionary<string, Argument> _longNameLookup;
readonly Dictionary<string, Argument> _ignoreCaseLookupDirectory = new Dictionary<string, Argument>();
private string[] _argsNotParsed;
private bool _checkMandatoryArguments = true;
private bool _checkArgumentCertifications = true;
private bool _allowShortSwitchGrouping = true;
private readonly AdditionalArgumentsSettings _additionalArgumentsSettings = new AdditionalArgumentsSettings();
private readonly List<string> _showUsageCommands = new List<string> { "--help", "/?", "/help" };
private bool _acceptSlash = true;
private bool _acceptHyphen = true;
private bool _ignoreCase;
private char[] equalsSignSyntaxValuesSeparators = new char[] { ',', ';' };
private static Regex lettersOnly = new Regex("^[a-zA-Z]$");
#endregion
/// <summary>
/// Defined command line arguments
/// </summary>
public List<Argument> Arguments
{
get { return _arguments; }
set { _arguments = value; }
}
/// <summary>
/// Set of <see cref="ArgumentCertification">certifications</see> - certifications can be used to define
/// which argument combinations are allowed and such type of validations.
/// </summary>
/// <seealso cref="CheckArgumentCertifications"/>
/// <seealso cref="ArgumentCertification"/>
/// <seealso cref="ArgumentGroupCertification"/>
/// <seealso cref="DistinctGroupsCertification"/>
public List<ArgumentCertification> Certifications
{
get { return _certifications; }
set { _certifications = value; }
}
/// <summary>
/// Allows more specific definition of additional arguments
/// (arguments after those with - and -- prefix).
/// </summary>
public AdditionalArgumentsSettings AdditionalArgumentsSettings
{
get { return _additionalArgumentsSettings; }
}
/// <summary>
/// Text printed in the beginning of 'show usage'
/// </summary>
public string ShowUsageHeader { get; set; }
/// <summary>
/// Text printed in the end of 'show usage'
/// </summary>
public string ShowUsageFooter { get; set; }
/// <summary>
/// Arguments that directly invoke <see cref="ShowUsage()"/>. By default this is --help and /?.
/// </summary>
public IList<string> ShowUsageCommands
{
get
{
return _showUsageCommands;
}
}
/// <summary>
/// When set to true, usage help is printed on the console when command line is without arguments.
/// Default is false.
/// </summary>
public bool ShowUsageOnEmptyCommandline { get; set; }
/// <summary>
/// When set to true, <see cref="MandatoryArgumentNotSetException"/> is thrown when some of the non-optional argument
/// is not found on the command line. Default is true.
/// See: <see cref="Argument.Optional"/>
/// </summary>
public bool CheckMandatoryArguments
{
get { return _checkMandatoryArguments; }
set { _checkMandatoryArguments = value; }
}
/// <summary>
/// When set to true, arguments are certified (using set of <see cref="Certifications"/>) after parsing.
/// Default is true.
/// </summary>
public bool CheckArgumentCertifications
{
get { return _checkArgumentCertifications; }
set { _checkArgumentCertifications = value; }
}
/// <summary>
/// When set to true (default) <see cref="SwitchArgument">switch arguments</see> can be grouped on the command line.
/// (e.g. -a -b -c can be written as -abc). When set to false and such a group is found, <see cref="CommandLineFormatException"/> is thrown.
/// </summary>
public bool AllowShortSwitchGrouping
{
get { return _allowShortSwitchGrouping; }
set { _allowShortSwitchGrouping = value; }
}
/// <summary>
/// Allows arguments in /a and /arg format
/// </summary>
public bool AcceptSlash
{
get { return _acceptSlash; }
set { _acceptSlash = value; }
}
/// <summary>
/// Allows arguments in -a and --arg format
/// </summary>
public bool AcceptHyphen
{
get { return _acceptHyphen; }
set { _acceptHyphen = value; }
}
/// <summary>
/// Argument names case insensitive (--OUTPUT or --output are treated equally)
/// </summary>
public bool IgnoreCase
{
get { return _ignoreCase; }
set { _ignoreCase = value; }
}
/// <summary>
/// When set to true, values of <see cref="ValueArgument{TValue}"/> are separeted by space,
/// otherwise, they are separeted by equal sign and enclosed in quotation marks
/// </summary>
/// <example>
/// --output="somefile.txt"
/// </example>
public bool AcceptEqualSignSyntaxForValueArguments { get; set; }
public bool PreserveValueQuotesForEqualsSignSyntax { get; set; }
public char[] EqualsSignSyntaxValuesSeparators
{
get
{
return equalsSignSyntaxValuesSeparators;
}
set
{
equalsSignSyntaxValuesSeparators = value;
}
}
/// <summary>
/// Value is set to true after parsing finishes successfuly
/// </summary>
public bool ParsingSucceeded { get; private set; }
/// <summary>
/// Fills lookup dictionaries with arguments names and aliases
/// </summary>
private void InitializeArgumentLookupDictionaries()
{
_shortNameLookup = new Dictionary<char, Argument>();
_longNameLookup = new Dictionary<string, Argument>();
foreach (Argument argument in _arguments)
{
if (argument.ShortName.HasValue)
{
_shortNameLookup.Add(argument.ShortName.Value, argument);
}
foreach (char aliasChar in argument.ShortAliases)
{
_shortNameLookup.Add(aliasChar, argument);
}
if (!string.IsNullOrEmpty(argument.LongName))
{
_longNameLookup.Add(argument.LongName, argument);
}
foreach (string aliasString in argument.LongAliases)
{
_longNameLookup.Add(aliasString, argument);
}
}
_ignoreCaseLookupDirectory.Clear();
if (IgnoreCase)
{
var allLookups = _shortNameLookup
.Select(kvp => new KeyValuePair<string, Argument>(kvp.Key.ToString(), kvp.Value))
.Concat(_longNameLookup);
foreach (KeyValuePair<string, Argument> keyValuePair in allLookups)
{
var icString = keyValuePair.Key.ToString().ToUpper();
if (_ignoreCaseLookupDirectory.ContainsKey(icString))
{
throw new ArgumentException("Clash in ignore case argument names: " + icString);
}
_ignoreCaseLookupDirectory.Add(icString, keyValuePair.Value);
}
}
}
/// <summary>
/// Resolves arguments from the command line and calls <see cref="Argument.Parse"/> on each argument.
/// Additional arguments are stored in AdditionalArgumentsSettings.AdditionalArguments
/// if AdditionalArgumentsSettings.AcceptAdditionalArguments is set to true.
/// </summary>
/// <exception cref="CommandLineFormatException">Command line arguments are not in correct format</exception>
/// <param name="args">Command line arguments</param>
public void ParseCommandLine(string[] args)
{
ParsingSucceeded = false;
_arguments.ForEach(action => action.Init());
List<string> argsList = new List<string>(args);
InitializeArgumentLookupDictionaries();
ExpandValueArgumentsWithEqualSigns(argsList);
ExpandShortSwitches(argsList);
AdditionalArgumentsSettings.AdditionalArguments = new string[0];
_argsNotParsed = args;
if ((args.Length == 0 && ShowUsageOnEmptyCommandline) ||
(args.Length == 1 && _showUsageCommands.Contains(args[0])))
{
ShowUsage();
return;
}
if (args.Length > 0)
{
int argIndex;
for (argIndex = 0; argIndex < argsList.Count;)
{
string curArg = argsList[argIndex];
Argument argument = ParseArgument(curArg);
if (argument == null)
break;
argument.Parse(argsList, ref argIndex);
argument.UpdateBoundObject();
}
ParseAdditionalArguments(argsList, argIndex);
}
foreach (Argument argument in _arguments)
{
if (argument is IArgumentWithDefaultValue && !argument.Parsed)
{
argument.UpdateBoundObject();
}
}
if (CheckMandatoryArguments)
{
PerformMandatoryArgumentsCheck();
}
if (CheckArgumentCertifications)
{
PerformCertificationCheck();
}
ParsingSucceeded = true;
}
/// <summary>
/// Searches <paramref name="parsingTarget"/> for fields with
/// <see cref="ArgumentAttribute">ArgumentAttributes</see> or some of its descendants. Adds new argument
/// for each such a field and defines binding of the argument to the field.
/// Also adds <see cref="ArgumentCertification"/> object to <see cref="Certifications"/> collection
/// for each <see cref="ArgumentCertificationAttribute"/> of <paramref name="parsingTarget"/>.
/// </summary>
/// <seealso cref="Argument.Bind"/>
/// <param name="parsingTarget">object where you with some ArgumentAttributes</param>
public void ExtractArgumentAttributes(object parsingTarget)
{
Type targetType = parsingTarget.GetType();
MemberInfo[] fields = targetType.GetFields();
MemberInfo[] properties = targetType.GetProperties();
List<MemberInfo> fieldAndProps = new List<MemberInfo>(fields);
fieldAndProps.AddRange(properties);
foreach (MemberInfo info in fieldAndProps)
{
var attrs = info.GetCustomAttributes(typeof(ArgumentAttribute), true).ToArray();
if (attrs.Length == 1 && attrs[0] is ArgumentAttribute)
{
Arguments.Add(((ArgumentAttribute)attrs[0]).Argument);
((ArgumentAttribute)attrs[0]).Argument.Bind =
new FieldArgumentBind(parsingTarget, info.Name);
}
}
object[] typeAttrs = targetType.GetTypeInfo().GetCustomAttributes(typeof(ArgumentCertificationAttribute), true).ToArray();
foreach (object certificationAttr in typeAttrs)
{
Certifications.Add(((ArgumentCertificationAttribute)certificationAttr).Certification);
}
}
/// <summary>
/// Parses one argument on the command line, lookups argument in <see cref="Arguments"/> using
/// lookup dictionaries.
/// </summary>
/// <param name="curArg">argument string (including '-' or '--' prefixes)</param>
/// <returns>Look-uped Argument class</returns>
/// <exception cref="CommandLineFormatException">Command line is in the wrong format</exception>
/// <exception cref="UnknownArgumentException">Unknown argument found.</exception>
private Argument ParseArgument(string curArg)
{
if (curArg[0] == '-')
{
if (AcceptHyphen)
{
string argName;
if (curArg.Length > 1)
{
if (curArg[1] == '-')
{
//long name
argName = curArg.Substring(2);
if (argName.Length == 1)
{
throw new CommandLineFormatException(string.Format(Messages.EXC_FORMAT_SHORTNAME_PREFIX, argName));
}
}
else
{
//short name
argName = curArg.Substring(1);
if (argName.Length != 1)
{
throw new CommandLineFormatException(string.Format(Messages.EXC_FORMAT_LONGNAME_PREFIX, argName));
}
}
Argument argument = LookupArgument(argName);
if (argument != null)
{
return argument;
}
throw new UnknownArgumentException(string.Format(Messages.EXC_ARG_UNKNOWN, argName), argName);
}
throw new CommandLineFormatException(Messages.EXC_FORMAT_SINGLEHYPHEN);
}
return null;
}
if (curArg[0] == '/')
{
if (AcceptSlash)
{
if (curArg.Length > 1)
{
if (curArg[1] == '/')
{
throw new CommandLineFormatException(Messages.EXC_FORMAT_SINGLESLASH);
}
string argName = curArg.Substring(1);
Argument argument = LookupArgument(argName);
if (argument != null)
{
return argument;
}
throw new UnknownArgumentException(string.Format(Messages.EXC_ARG_UNKNOWN, argName), argName);
}
throw new CommandLineFormatException(Messages.EXC_FORMAT_DOUBLESLASH);
}
return null;
}
/*
* curArg does not start with '-' character and therefore it is considered additional argument.
* Argument parsing ends here.
*/
return null;
}
/// <summary>
/// Checks whether non-optional arguments were defined on the command line.
/// </summary>
/// <exception cref="MandatoryArgumentNotSetException"><see cref="Argument.Optional">Non-optional</see> argument not defined.</exception>
/// <seealso cref="CheckMandatoryArguments"/>, <seealso cref="Argument.Optional"/>
private void PerformMandatoryArgumentsCheck()
{
_arguments.ForEach(delegate (Argument arg)
{
if (!arg.Optional && !arg.Parsed)
throw new MandatoryArgumentNotSetException(string.Format(Messages.EXC_MISSING_MANDATORY_ARGUMENT, arg.Name), arg.Name);
});
}
/// <summary>
/// Performs certifications
/// </summary>
private void PerformCertificationCheck()
{
_certifications.ForEach(delegate (ArgumentCertification certification)
{
certification.Certify(this);
});
}
/// <summary>
/// Parses the rest of the command line for additional arguments
/// </summary>
/// <param name="argsList">list of thearguments</param>
/// <param name="i">index of the first additional argument in <paramref name="argsList"/></param>
/// <exception cref="CommandLineFormatException">Additional arguments found, but they are
/// not accepted</exception>
private void ParseAdditionalArguments(List<string> argsList, int i)
{
if (AdditionalArgumentsSettings.AcceptAdditionalArguments)
{
AdditionalArgumentsSettings.AdditionalArguments = new string[argsList.Count - i];
if (i < argsList.Count)
{
Array.Copy(argsList.ToArray(), i, AdditionalArgumentsSettings.AdditionalArguments, 0, argsList.Count - i);
}
AdditionalArgumentsSettings.ProcessArguments();
}
else if (i < argsList.Count)
{
// only throw when there are any additional arguments
throw new CommandLineFormatException(
Messages.EXC_ADDITIONAL_ARGUMENTS_FOUND);
}
}
/// <summary>
/// If <see cref="AllowShortSwitchGrouping"/> is set to true, each group of switch arguments (e. g. -abcd)
/// is expanded into full format (-a -b -c -d) in the list.
/// </summary>
/// <exception cref="CommandLineFormatException">Argument of type differnt from SwitchArgument found in one of the groups. </exception>
/// <param name="argsList">List of arguments</param>
/// <exception cref="CommandLineFormatException">Arguments that are not <see cref="SwitchArgument">switches</see> found
/// in a group.</exception>
/// <seealso cref="AllowShortSwitchGrouping"/>
private void ExpandShortSwitches(IList<string> argsList)
{
if (AllowShortSwitchGrouping)
{
for (int i = 0; i < argsList.Count; i++)
{
string arg = argsList[i];
if (arg.Length > 2)
{
if (arg[0] == '/' && arg[1] != '/' && AcceptSlash && _longNameLookup.ContainsKey(arg.Substring(1)))
continue;
if (arg.Contains('='))
continue;
if (ShowUsageCommands.Contains(arg))
continue;
char sep = arg[0];
if ((arg[0] == '-' && AcceptHyphen && lettersOnly.IsMatch(arg.Substring(1)))
|| (arg[0] == '/' && AcceptSlash && lettersOnly.IsMatch(arg.Substring(1))))
{
argsList.RemoveAt(i);
//arg ~ -xyz
foreach (char c in arg.Substring(1))
{
if (_shortNameLookup.ContainsKey(c) && !(_shortNameLookup[c] is SwitchArgument))
{
throw new CommandLineFormatException(
string.Format(Messages.EXC_BAD_ARG_IN_GROUP, c));
}
argsList.Insert(i, sep.ToString() + c);
i++;
}
}
}
}
}
}
private void ExpandValueArgumentsWithEqualSigns(IList<string> argsList)
{
if (AcceptEqualSignSyntaxForValueArguments)
{
for (int i = 0; i < argsList.Count; i++)
{
string arg = argsList[i];
Regex r = new Regex("([^=]*)=(.*)");
if (AcceptEqualSignSyntaxForValueArguments && r.IsMatch(arg))
{
Match m = r.Match(arg);
string argNameWithSep = m.Groups[1].Value;
string argName = argNameWithSep;
while (argName.StartsWith("-") && AcceptHyphen)
argName = argName.Substring(1);
while (argName.StartsWith("/") && AcceptSlash)
argName = argName.Substring(1);
string argValue = m.Groups[2].Value;
if (!PreserveValueQuotesForEqualsSignSyntax && !string.IsNullOrEmpty(argValue) && argValue.StartsWith("\"") && argValue.EndsWith("\""))
{
argValue = argValue.Trim('"');
}
Argument argument = LookupArgument(argName);
if (argument is IValueArgument)
{
argsList.RemoveAt(i);
if (argument.AllowMultiple)
{
var splitted = argValue.Split(equalsSignSyntaxValuesSeparators);
foreach (var singleValue in splitted)
{
argsList.Insert(i, argNameWithSep);
i++;
if (!string.IsNullOrEmpty(singleValue))
{
argsList.Insert(i, singleValue);
i++;
}
}
i--;
}
else
{
argsList.Insert(i, argNameWithSep);
i++;
argsList.Insert(i, argValue);
}
}
}
}
}
}
/// <summary>
/// Returns argument of given name
/// </summary>
/// <param name="argName">Name of the argument (<see cref="Argument.ShortName"/>, <see cref="Argument.LongName"/>, or alias)</param>
/// <returns>Found argument or null when argument is not present</returns>
public Argument LookupArgument(string argName)
{
if (argName.Length == 1)
{
if (_shortNameLookup.ContainsKey(argName[0]))
{
return _shortNameLookup[argName[0]];
}
}
else
{
if (_longNameLookup.ContainsKey(argName))
{
return _longNameLookup[argName];
}
}
if (IgnoreCase && _ignoreCaseLookupDirectory.ContainsKey(argName.ToUpper()))
{
return _ignoreCaseLookupDirectory[argName.ToUpper()];
}
// argument not found anywhere
return null;
}
/// <summary>
/// Prints arguments information and usage information to
/// the <paramref name="outputStream"/>.
/// </summary>
public void PrintUsage(TextWriter outputStream)
{
outputStream.WriteLine(ShowUsageHeader);
outputStream.WriteLine(Messages.MSG_USAGE);
foreach (Argument argument in _arguments)
{
outputStream.Write("\t");
bool comma = false;
if (argument.ShortName.HasValue)
{
outputStream.Write("-" + argument.ShortName);
comma = true;
}
foreach (char c in argument.ShortAliases)
{
if (comma)
outputStream.WriteLine(", ");
outputStream.Write("-" + c);
comma = true;
}
if (!string.IsNullOrEmpty(argument.LongName))
{
if (comma)
outputStream.Write(", ");
outputStream.Write("--" + argument.LongName);
comma = true;
}
foreach (string str in argument.LongAliases)
{
if (comma)
outputStream.Write(", ");
outputStream.Write("--" + str);
comma = true;
}
if (argument.Optional)
outputStream.Write(Messages.MSG_OPTIONAL);
outputStream.WriteLine("... {0} ", argument.Description);
if (!string.IsNullOrEmpty(argument.Example))
{
outputStream.WriteLine(Messages.MSG_EXAMPLE_FORMAT, argument.Example);
}
if (!string.IsNullOrEmpty(argument.FullDescription))
{
outputStream.WriteLine();
outputStream.WriteLine(argument.FullDescription);
}
outputStream.WriteLine();
}
if (Certifications.Count > 0)
{
outputStream.WriteLine(Messages.CERT_REMARKS);
foreach (ArgumentCertification certification in Certifications)
{
outputStream.WriteLine("\t" + certification.Description);
}
outputStream.WriteLine();
}
outputStream.WriteLine(ShowUsageFooter);
}
/// <summary>
/// Prints arguments information and usage information to the console.
/// </summary>
public void ShowUsage()
{
PrintUsage(Console.Out);
}
/// <summary>
/// Prints values of parsed arguments. Can be used for debugging.
/// </summary>
public void ShowParsedArguments(bool showOmittedArguments = false)
{
Console.WriteLine(Messages.MSG_PARSING_RESULTS);
Console.WriteLine("\t" + Messages.MSG_COMMAND_LINE);
foreach (string arg in _argsNotParsed)
{
Console.Write(arg);
Console.Write(" ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("\t" + Messages.MSG_PARSED_ARGUMENTS);
foreach (Argument argument in _arguments)
{
if (argument.Parsed)
argument.PrintValueInfo();
}
Console.WriteLine();
Console.WriteLine("\t" + Messages.MSG_NOT_PARSED_ARGUMENTS);
foreach (Argument argument in _arguments)
{
if (!argument.Parsed)
argument.PrintValueInfo();
}
Console.WriteLine();
if (AdditionalArgumentsSettings.AcceptAdditionalArguments)
{
Console.WriteLine("\t" + Messages.MSG_ADDITIONAL_ARGUMENTS);
foreach (string simpleArgument in AdditionalArgumentsSettings.AdditionalArguments)
{
Console.Write(simpleArgument + " ");
}
Console.WriteLine();
Console.WriteLine();
}
}
/// <summary>
/// <para>
/// Fills FullDescription of all the difined arguments from a resource file.
/// For each argument selects a string from a resource that has the same resource key
/// as is the currrent value of the argument's FullDescription.
/// </para>
/// <para>
/// This way the value of FullDescription's can be set to keys and these keys are replaced by
/// the resource values when the method is called.
/// </para>
/// </summary>
/// <param name="resource">The resource.</param>
public void FillDescFromResource(IResource resource)
{
foreach (Argument argument in Arguments)
{
if (!string.IsNullOrEmpty(argument.FullDescription))
{
string ld = resource.ResourceManager.GetString(argument.FullDescription);
argument.FullDescription = ld;
}
}
foreach (Argument argument in AdditionalArgumentsSettings.TypedAdditionalArguments)
{
if (!string.IsNullOrEmpty(argument.FullDescription))
{
string ld = resource.ResourceManager.GetString(argument.FullDescription);
argument.FullDescription = ld;
}
}
}
public void Dispose()
{
_arguments.Clear();
_certifications.Clear();
_shortNameLookup.Clear();
_longNameLookup.Clear();
_ignoreCaseLookupDirectory.Clear();
}
}
}
| |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
$MaterialSelector_SkipTerrainMaterials = true;
function MaterialSelector::clearFilterArray( %this ) {
%filterArray = MaterialSelector-->tagFilters;
foreach(%obj in %filterArray) {
if (%obj.internalName $= "CustomFilter" && %obj.superClass !$= "NoDeleteCtrl" )
%deleteList = strAddWord(%deleteList,%obj.getId());
}
foreach$(%objID in %deleteList)
delObj(%objID);
}
//------------------------------------------------------------------------------
//oldmatSelector.buildStaticFilters();
function MaterialSelector::buildTerrainStaticFilters( %this ) {
%mats = ETerrainEditor.getTerrainBlocksMaterialList();
%count = getRecordCount( %mats );
for(%i = 0; %i < %count; %i++) {
// Process terrain materials
%matInternalName = getRecord( %mats, %i );
%material = TerrainMaterialSet.findObjectByInternalName( %matInternalName );
// Is there no material info for this slot?
if ( !isObject( %material ) )
continue;
// Add to the appropriate filters
MaterialFilterMappedArray.add( "", %material );
MaterialFilterAllArray.add( "", %material );
if (%material.terrainMaterials && $MaterialSelector_SkipTerrainMaterials )
continue;
}
}
//------------------------------------------------------------------------------
//==============================================================================
// Build materials filters data by checking all materials and adding it to filter groups
//oldmatSelector.buildStaticFilters();
function MaterialSelector::buildStaticFilters( %this ) {
%this.clearFilterArray();
MaterialSelector.staticFilterObjCount = MaterialSelector-->tagFilters.getCount() - 1;// Remove the header box
//%staticFilterContainer.delete();
// Create our category array used in the selector, this code should be taken out
// in order to make the material selector agnostic
delObj(MaterialFilterAllArray);
delObj(MaterialFilterMappedArray);
delObj(MaterialFilterUnmappedArray);
new ArrayObject(MaterialFilterAllArray);
new ArrayObject(MaterialFilterMappedArray);
new ArrayObject(MaterialFilterUnmappedArray);
%mats = "";
%count = 0;
//If in terrainMaterials mode, get terrain Materials list, else get materials
if( MaterialSelector.terrainMaterials ) {
//Used by GroundCover to select terrainMat
%this.buildTerrainStaticFilters();
return;
}
%count = materialSet.getCount();
for(%i = 0; %i < %count; %i++) {
// Process regular materials here
%material = materialSet.getObject(%i);
for( %k = 0; %k < UnlistedMaterials.count(); %k++ ) {
%unlistedFound = 0;
if( UnlistedMaterials.getValue(%k) $= %material.name ) {
%unlistedFound = 1;
break;
}
}
// Don't build filters for unlisted mats
if( %unlistedFound )
continue;
//------------------------------------------------------------------------
// Add it to appropriate group is mapped or not
//If Unmapped, add to unmapped
if( %material.mapTo $= "" || %material.mapTo $= "unmapped_mat" ) {
MaterialFilterUnmappedArray.add( "", %material.name );
//running through the existing tag names
for( %j = 0; %material.getFieldValue("materialTag" @ %j) !$= ""; %j++ )
MaterialFilterUnmappedArray.add( %material.getFieldValue("materialTag" @ %j), %material.name );
}
//Else add to mapped array
else {
MaterialFilterMappedArray.add( "", %material.name );
for( %j = 0; %material.getFieldValue("materialTag" @ %j) !$= ""; %j++ )
MaterialFilterMappedArray.add( %material.getFieldValue("materialTag" @ %j), %material.name );
}
//Add to all filters Array
MaterialFilterAllArray.add( "", %material.name );
for( %j = 0; %material.getFieldValue("materialTag" @ %j) !$= ""; %j++ )
MaterialFilterAllArray.add( %material.getFieldValue("materialTag" @ %j), %material.name );
}
//Update the filter checkbox and add group count referemce
MaterialFilterAllArrayCheckbox.setText("All ( " @ MaterialFilterAllArray.count() @" ) ");
MaterialFilterMappedArrayCheckbox.setText("Mapped ( " @ MaterialFilterMappedArray.count() @" ) ");
MaterialFilterUnmappedArrayCheckbox.setText("Unmapped ( " @ MaterialFilterUnmappedArray.count() @" ) ");
devLog("Mat filtering built! Unmapped:",MaterialFilterUnmappedArray.count(),"Mapped:",MaterialFilterMappedArray.count(),"Total",MaterialFilterAllArray.count() );
}
//------------------------------------------------------------------------------
//==============================================================================
// Preload filter: Need to examine what it actually do
//==============================================================================
//==============================================================================
function MaterialSelector::preloadFilter( %this ) {
%selectedFilter = "";
for( %i = MaterialSelector.staticFilterObjCount; %i < MaterialSelector-->tagFilters.getCount(); %i++ ) {
if( MaterialSelector-->tagFilters.getObject(%i).getObject(0).getValue() == 1 ) {
if( %selectedFilter $= "" )
%selectedFilter = MaterialSelector-->tagFilters.getObject(%i).getObject(0).filter;
else
%selectedFilter = %selectedFilter @ " " @ MaterialSelector-->tagFilters.getObject(%i).getObject(0).filter;
}
}
MaterialSelector.loadFilter( %selectedFilter );
}
//------------------------------------------------------------------------------
//==============================================================================
// Load the filtered materials (called also when thumbnail count change)
function MaterialSelector::loadFilter( %this, %selectedFilter, %staticFilter ) {
MatSel_ListFilterText.active = 0;
// manage schedule array properly
if(!isObject(MatEdScheduleArray))
new ArrayObject(MatEdScheduleArray);
// if we select another list... delete all schedules that were created by
// previous load
for( %i = 0; %i < MatEdScheduleArray.count(); %i++ )
cancel(MatEdScheduleArray.getKey(%i));
// we have to empty out the list; so when we create new schedules, these dont linger
MatEdScheduleArray.empty();
// manage preview array
if(!isObject(MatEdPreviewArray))
new ArrayObject(MatEdPreviewArray);
// we have to empty out the list; so when we create new guicontrols, these dont linger
MatEdPreviewArray.empty();
MaterialSelector-->materialSelection.deleteAllObjects();
MaterialSelector-->materialPreviewPagesStack.deleteAllObjects();
// changed to accomadate tagging. dig through the array for each tag name,
// call unique value, sort, and we have a perfect set of materials
//if (!isObject(%staticFilter)){
//%this.buildStaticFilters();
//%staticFilter = MaterialFilterAllArray;
//}
if (isObject(%staticFilter))
MaterialSelector.currentStaticFilter = %staticFilter;
if (!isObject(MaterialSelector.currentStaticFilter)) {
MaterialSelector.currentStaticFilter = MaterialFilterAllArray;
}
MaterialSelector.currentFilter = %selectedFilter;
%filteredObjectsArray = new ArrayObject();
%previewsPerPage = MaterialSelector-->materialPreviewCountPopup.getTextById( MaterialSelector-->materialPreviewCountPopup.getSelected() );
if (%previewsPerPage $= "All")
%previewsPerPage = "999999";
%tagCount = getWordCount( MaterialSelector.currentFilter );
if (!isObject(MaterialSelector.currentStaticFilter))
%this.buildStaticFilters();
//---------------------------------------------------------------------------
// There's filtered tags, update filters
if( %tagCount != 0 ) {
for( %j = 0; %j < %tagCount; %j++ ) {
for( %i = 0; %i < MaterialSelector.currentStaticFilter.count(); %i++ ) {
%currentTag = getWord( MaterialSelector.currentFilter, %j );
if( MaterialSelector.currentStaticFilter.getKey(%i) $= %currentTag)
%filteredObjectsArray.add( MaterialSelector.currentStaticFilter.getKey(%i), MaterialSelector.currentStaticFilter.getValue(%i) );
}
}
%filteredObjectsArray.uniqueValue();
%filteredObjectsArray.sortd();
%this.buildPages(%filteredObjectsArray);
%filteredObjectsArray.delete();
} else {
//---------------------------------------------------------------------------
// There's NO filtered tags, update filters differently...
MaterialSelector.currentStaticFilter.sortd();
// Rebuild the static filter list without tagged materials
%noTagArray = new ArrayObject();
for( %i = 0; %i < MaterialSelector.currentStaticFilter.count(); %i++ ) {
if( MaterialSelector.currentStaticFilter.getKey(%i) !$= "")
continue;
%material = MaterialSelector.currentStaticFilter.getValue(%i);
// CustomMaterials are not available for selection
if ( !isObject( %material ) || %material.isMemberOfClass( "CustomMaterial" ) )
continue;
%noTagArray.add( "", %material );
}
%this.buildPages(%noTagArray);
}
MaterialSelector.loadImages( 0 );
MatSel_ListFilterText.active = 1;
}
function MaterialSelector::clearMaterialFilters( %this ) {
for( %i = MaterialSelector.staticFilterObjCount; %i < MaterialSelector-->filterArray.getCount(); %i++ )
MaterialSelector-->filterArray.getObject(%i).getObject(0).setStateOn(0);
MaterialSelector.loadFilter( "", "" );
}
//------------------------------------------------------------------------------
function MaterialSelector::loadMaterialFilters( %this ) {
%filteredTypesArray = new ArrayObject();
%filteredTypesArray.duplicate( MaterialFilterAllArray );
%filteredTypesArray.uniqueKey();
// sort the the keys before we do anything
%filteredTypesArray.sortkd();
eval( MaterialSelector.currentStaticFilter @ "Checkbox.setStateOn(1);" );
// it may seem goofy why the checkbox can't be instanciated inside the container
// reason being its because we need to store the checkbox ctrl in order to make changes
// on it later in the function.
%selectedFilter = "";
for( %i = 0; %i < %filteredTypesArray.count(); %i++ ) {
%filter = %filteredTypesArray.getKey(%i);
if(%filter $= "")
continue;
%container = cloneObject(MatSelector_FilterSamples-->filterPillSample);
%container.internalName = "CustomFilter";
%checkbox = %container.getObject(0);
%checkbox.text = %filter @ " ( " @ MaterialFilterAllArray.countKey(%filter) @ " )";
%checkbox.filter = %filter;
if (!isObject(%container)) {
%container = new GuiControl() {
profile = "ToolsDefaultProfile";
Position = "0 0";
Extent = "128 18";
HorizSizing = "right";
VertSizing = "bottom";
isContainer = "1";
};
%checkbox = new GuiCheckBoxCtrl() {
Profile = "ToolsCheckBoxProfile";
position = "5 1";
Extent = "118 18";
Command = "";
groupNum = "0";
buttonType = "ToggleButton";
text = %filter @ " ( " @ MaterialFilterAllArray.countKey(%filter) @ " )";
filter = %filter;
Command = "MaterialSelector.preloadFilter();";
};
%container.add( %checkbox );
}
//%checkbox = %container.getObject(0);
MaterialSelector-->filterArray.add( %container );
%tagCount = getWordCount( MaterialSelector.currentFilter );
for( %j = 0; %j < %tagCount; %j++ ) {
if( %filter $= getWord( MaterialSelector.currentFilter, %j ) ) {
if( %selectedFilter $= "" )
%selectedFilter = %filter;
else
%selectedFilter = %selectedFilter @ " " @ %filter;
%checkbox.setStateOn(1);
}
}
}
MaterialSelector.loadFilter( %selectedFilter );
%filteredTypesArray.delete();
}
//------------------------------------------------------------------------------
// create category and update current material if there is one
function MaterialSelector::createFilter( %this, %filter ) {
if( %filter $= %existingFilters ) {
MessageBoxOK( "Error", "Can not create blank filter.");
return;
}
for( %i = MaterialSelector.staticFilterObjCount; %i < MaterialSelector-->filterArray.getCount() ; %i++ ) {
%existingFilters = MaterialSelector-->filterArray.getObject(%i).getObject(0).filter;
if( %filter $= %existingFilters ) {
MessageBoxOK( "Error", "Can not create two filters of the same name.");
return;
}
}
devLog("createFilter:",%filter);
%container = cloneObject(MatSelector_FilterSamples-->filterPillSample);
%container.internalName = "CustomFilter";
%checkbox = %container.getObject(0);
%checkbox.text = %filter @ " ( " @ MaterialFilterAllArray.countKey(%filter) @ " )";
%checkbox.filter = %filter;
if (!isObject(%container)) {
%container = new GuiControl() {
profile = "ToolsDefaultProfile";
Position = "0 0";
Extent = "128 18";
HorizSizing = "right";
VertSizing = "bottom";
isContainer = "1";
new GuiCheckBoxCtrl() {
Profile = "ToolsCheckBoxProfile";
position = "5 1";
Extent = "118 18";
Command = "";
groupNum = "0";
buttonType = "ToggleButton";
text = %filter @ " ( " @ MaterialFilterAllArray.countKey(%filter) @ " )";
filter = %filter;
Command = "MaterialSelector.preloadFilter();";
};
};
}
MaterialSelector-->filterArray.add( %container );
// if selection exists, lets reselect it to refresh it
if( isObject(MaterialSelector.selectedMaterial) )
MaterialSelector.updateSelection( MaterialSelector.selectedMaterial, MaterialSelector.selectedPreviewImagePath );
// material category text field to blank
MaterialSelector_addFilterWindow-->tagName.setText("");
}
//------------------------------------------------------------------------------
function MaterialSelector::updateFilterCount( %this, %tag, %add ) {
for( %i = MaterialSelector.staticFilterObjCount; %i < MaterialSelector-->filterArray.getCount() ; %i++ ) {
if( %tag $= MaterialSelector-->filterArray.getObject(%i).getObject(0).filter ) {
// Get the filter count and apply the operation
%idx = getWord( MaterialSelector-->filterArray.getObject(%i).getObject(0).getText(), 2 );
if( %add )
%idx++;
else
%idx--;
MaterialSelector-->filterArray.getObject(%i).getObject(0).setText( %tag @ " ( "@ %idx @ " )");
}
}
}
//------------------------------------------------------------------------------
function MaterialSelector::switchStaticFilters( %this, %staticFilter) {
switch$(%staticFilter) {
case "MaterialFilterAllArray":
MaterialFilterAllArrayCheckbox.setStateOn(1);
MaterialFilterMappedArrayCheckbox.setStateOn(0);
MaterialFilterUnmappedArrayCheckbox.setStateOn(0);
case "MaterialFilterMappedArray":
MaterialFilterMappedArrayCheckbox.setStateOn(1);
MaterialFilterAllArrayCheckbox.setStateOn(0);
MaterialFilterUnmappedArrayCheckbox.setStateOn(0);
case "MaterialFilterUnmappedArray":
MaterialFilterUnmappedArrayCheckbox.setStateOn(1);
MaterialFilterAllArrayCheckbox.setStateOn(0);
MaterialFilterMappedArrayCheckbox.setStateOn(0);
}
// kinda goofy were passing a class variable... we can't do an empty check right now
// on load filter because we actually pass "" as a filter...
MaterialSelector.loadFilter( MaterialSelector.currentFilter, %staticFilter );
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
namespace OpenSim.Framework.Monitoring
{
public class ServerStatsCollector
{
private readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly string LogHeader = "[SERVER STATS]";
public bool Enabled = false;
private static Dictionary<string, Stat> RegisteredStats = new Dictionary<string, Stat>();
public readonly string CategoryServer = "server";
public readonly string ContainerThreadpool = "threadpool";
public readonly string ContainerProcessor = "processor";
public readonly string ContainerMemory = "memory";
public readonly string ContainerNetwork = "network";
public readonly string ContainerProcess = "process";
public string NetworkInterfaceTypes = "Ethernet";
readonly int performanceCounterSampleInterval = 500;
// int lastperformanceCounterSampleTime = 0;
private class PerfCounterControl
{
public PerformanceCounter perfCounter;
public int lastFetch;
public string name;
public PerfCounterControl(PerformanceCounter pPc)
: this(pPc, String.Empty)
{
}
public PerfCounterControl(PerformanceCounter pPc, string pName)
{
perfCounter = pPc;
lastFetch = 0;
name = pName;
}
}
PerfCounterControl processorPercentPerfCounter = null;
// IRegionModuleBase.Initialize
public void Initialise(IConfigSource source)
{
if (source == null)
return;
IConfig cfg = source.Configs["Monitoring"];
if (cfg != null)
Enabled = cfg.GetBoolean("ServerStatsEnabled", true);
if (Enabled)
{
NetworkInterfaceTypes = cfg.GetString("NetworkInterfaceTypes", "Ethernet");
}
}
public void Start()
{
if (RegisteredStats.Count == 0)
RegisterServerStats();
}
public void Close()
{
if (RegisteredStats.Count > 0)
{
foreach (Stat stat in RegisteredStats.Values)
{
StatsManager.DeregisterStat(stat);
stat.Dispose();
}
RegisteredStats.Clear();
}
}
private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act)
{
MakeStat(pName, pDesc, pUnit, pContainer, act, MeasuresOfInterest.None);
}
private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act, MeasuresOfInterest moi)
{
string desc = pDesc;
if (desc == null)
desc = pName;
Stat stat = new Stat(pName, pName, desc, pUnit, CategoryServer, pContainer, StatType.Pull, moi, act, StatVerbosity.Debug);
StatsManager.RegisterStat(stat);
RegisteredStats.Add(pName, stat);
}
public void RegisterServerStats()
{
// lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
PerformanceCounter tempPC;
Stat tempStat;
string tempName;
try
{
tempName = "CPUPercent";
tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
processorPercentPerfCounter = new PerfCounterControl(tempPC);
// A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
RegisteredStats.Add(tempName, tempStat);
MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); });
MakeStat("UserProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().UserProcessorTime.TotalSeconds, 3); });
MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds, 3); });
MakeStat("Threads", null, "threads", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e);
}
MakeStat("BuiltinThreadpoolWorkerThreadsAvailable", null, "threads", ContainerThreadpool,
s =>
{
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
s.Value = workerThreads;
});
MakeStat("BuiltinThreadpoolIOCPThreadsAvailable", null, "threads", ContainerThreadpool,
s =>
{
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
s.Value = iocpThreads;
});
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool && Util.GetSmartThreadPoolInfo() != null)
{
MakeStat("STPMaxThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxThreads);
MakeStat("STPMinThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MinThreads);
MakeStat("STPConcurrency", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxConcurrentWorkItems);
MakeStat("STPActiveThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().ActiveThreads);
MakeStat("STPInUseThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().InUseThreads);
MakeStat("STPWorkItemsWaiting", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().WaitingCallbacks);
}
MakeStat(
"HTTPRequestsMade",
"Number of outbound HTTP requests made",
"requests",
ContainerNetwork,
s => s.Value = WebUtil.RequestNumber,
MeasuresOfInterest.AverageChangeOverTime);
try
{
List<string> okInterfaceTypes = new List<string>(NetworkInterfaceTypes.Split(','));
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (nic.OperationalStatus != OperationalStatus.Up)
continue;
string nicInterfaceType = nic.NetworkInterfaceType.ToString();
if (!okInterfaceTypes.Contains(nicInterfaceType))
{
m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.",
LogHeader, nic.Name, nicInterfaceType);
m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}",
LogHeader, NetworkInterfaceTypes);
continue;
}
if (nic.Supports(NetworkInterfaceComponent.IPv4))
{
IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics();
if (nicStats != null)
{
MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesReceived; }, 1024.0); });
MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesSent; }, 1024.0); });
MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesSent + ns.BytesReceived; }, 1024.0); });
}
}
// TODO: add IPv6 (it may actually happen someday)
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e);
}
MakeStat("ProcessMemory", null, "MB", ContainerMemory,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d, 3); });
MakeStat("HeapMemory", null, "MB", ContainerMemory,
(s) => { s.Value = Math.Round(GC.GetTotalMemory(false) / 1024d / 1024d, 3); });
MakeStat("LastHeapAllocationRate", null, "MB/sec", ContainerMemory,
(s) => { s.Value = Math.Round(MemoryWatchdog.LastHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
MakeStat("AverageHeapAllocationRate", null, "MB/sec", ContainerMemory,
(s) => { s.Value = Math.Round(MemoryWatchdog.AverageHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
MakeStat("ProcessResident", null, "MB", ContainerProcess,
(s) =>
{
Process myprocess = Process.GetCurrentProcess();
myprocess.Refresh();
s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0);
});
MakeStat("ProcessPaged", null, "MB", ContainerProcess,
(s) =>
{
Process myprocess = Process.GetCurrentProcess();
myprocess.Refresh();
s.Value = Math.Round(Process.GetCurrentProcess().PagedMemorySize64 / 1024.0 / 1024.0);
});
MakeStat("ProcessVirtual", null, "MB", ContainerProcess,
(s) =>
{
Process myprocess = Process.GetCurrentProcess();
myprocess.Refresh();
s.Value = Math.Round(Process.GetCurrentProcess().VirtualMemorySize64 / 1024.0 / 1024.0);
});
MakeStat("PeakProcessResident", null, "MB", ContainerProcess,
(s) =>
{
Process myprocess = Process.GetCurrentProcess();
myprocess.Refresh();
s.Value = Math.Round(Process.GetCurrentProcess().PeakWorkingSet64 / 1024.0 / 1024.0);
});
MakeStat("PeakProcessPaged", null, "MB", ContainerProcess,
(s) =>
{
Process myprocess = Process.GetCurrentProcess();
myprocess.Refresh();
s.Value = Math.Round(Process.GetCurrentProcess().PeakPagedMemorySize64 / 1024.0 / 1024.0);
});
MakeStat("PeakProcessVirtual", null, "MB", ContainerProcess,
(s) =>
{
Process myprocess = Process.GetCurrentProcess();
myprocess.Refresh();
s.Value = Math.Round(Process.GetCurrentProcess().PeakVirtualMemorySize64 / 1024.0 / 1024.0);
});
}
// Notes on performance counters:
// "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
// "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
// "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
private delegate double PerfCounterNextValue();
private void GetNextValue(Stat stat, PerfCounterControl perfControl)
{
if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
{
if (perfControl != null && perfControl.perfCounter != null)
{
try
{
stat.Value = Math.Round(perfControl.perfCounter.NextValue(), 3);
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
}
perfControl.lastFetch = Util.EnvironmentTickCount();
}
}
}
// Lookup the nic that goes with this stat and set the value by using a fetch action.
// Not sure about closure with delegates inside delegates.
private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
{
// Get the one nic that has the name of this stat
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
(network) => network.Name == stat.Description);
try
{
foreach (NetworkInterface nic in nics)
{
IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
if (intrStats != null)
{
double newVal = Math.Round(getter(intrStats) / factor, 3);
stat.Value = newVal;
}
break;
}
}
catch
{
// There are times interfaces go away so we just won't update the stat for this
m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
}
}
}
public class ServerStatsAggregator : Stat
{
public ServerStatsAggregator(
string shortName,
string name,
string description,
string unitName,
string category,
string container
)
: base(
shortName,
name,
description,
unitName,
category,
container,
StatType.Push,
MeasuresOfInterest.None,
null,
StatVerbosity.Info)
{
}
public override string ToConsoleString()
{
StringBuilder sb = new StringBuilder();
return sb.ToString();
}
public override OSDMap ToOSDMap()
{
OSDMap ret = new OSDMap();
return ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
/// <summary>
/// Defines a particular format for text, including font face, size, and style attributes.
/// </summary>
#if netcoreapp || netcoreapp30
[TypeConverter("System.Drawing.FontConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")]
#endif
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public sealed partial class Font : MarshalByRefObject, ICloneable, IDisposable, ISerializable
{
private IntPtr _nativeFont;
private float _fontSize;
private FontStyle _fontStyle;
private FontFamily _fontFamily;
private GraphicsUnit _fontUnit;
private byte _gdiCharSet = SafeNativeMethods.DEFAULT_CHARSET;
private bool _gdiVerticalFont;
private string _systemFontName = "";
private string _originalFontName;
// Return value is in Unit (the unit the font was created in)
/// <summary>
/// Gets the size of this <see cref='Font'/>.
/// </summary>
public float Size => _fontSize;
/// <summary>
/// Gets style information for this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontStyle Style => _fontStyle;
/// <summary>
/// Gets a value indicating whether this <see cref='System.Drawing.Font'/> is bold.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Bold => (Style & FontStyle.Bold) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is Italic.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Italic => (Style & FontStyle.Italic) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it).
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Strikeout => (Style & FontStyle.Strikeout) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is underlined.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Underline => (Style & FontStyle.Underline) != 0;
/// <summary>
/// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontFamily FontFamily => _fontFamily;
/// <summary>
/// Gets the face name of this <see cref='Font'/> .
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#if !NETCORE
[Editor ("System.Drawing.Design.FontNameEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
[TypeConverter (typeof (FontConverter.FontNameConverter))]
#endif
public string Name => FontFamily.Name;
/// <summary>
/// Gets the unit of measure for this <see cref='Font'/>.
/// </summary>
#if !NETCORE
[TypeConverter (typeof (FontConverter.FontUnitConverter))]
#endif
public GraphicsUnit Unit => _fontUnit;
/// <summary>
/// Returns the GDI char set for this instance of a font. This will only
/// be valid if this font was created from a classic GDI font definition,
/// like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls
/// on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public byte GdiCharSet => _gdiCharSet;
/// <summary>
/// Determines if this font was created to represent a GDI vertical font. This will only be valid if this font
/// was created from a classic GDIfont definition, like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool GdiVerticalFont => _gdiVerticalFont;
/// <summary>
/// This property is required by the framework and not intended to be used directly.
/// </summary>
[Browsable(false)]
public string OriginalFontName => _originalFontName;
/// <summary>
/// Gets the name of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public string SystemFontName => _systemFontName;
/// <summary>
/// Returns true if this <see cref='Font'/> is a SystemFont.
/// </summary>
[Browsable(false)]
public bool IsSystemFont => !string.IsNullOrEmpty(_systemFontName);
/// <summary>
/// Gets the height of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public int Height => (int)Math.Ceiling(GetHeight());
/// <summary>
/// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet.
/// </summary>
internal IntPtr NativeFont => _nativeFont;
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
~Font() => Dispose(false);
private Font(SerializationInfo info, StreamingContext context)
{
string name = info.GetString("Name"); // Do not rename (binary serialization)
FontStyle style = (FontStyle)info.GetValue("Style", typeof(FontStyle)); // Do not rename (binary serialization)
GraphicsUnit unit = (GraphicsUnit)info.GetValue("Unit", typeof(GraphicsUnit)); // Do not rename (binary serialization)
float size = info.GetSingle("Size"); // Do not rename (binary serialization)
Initialize(name, size, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(name));
}
void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
{
string name = string.IsNullOrEmpty(OriginalFontName) ? Name : OriginalFontName;
si.AddValue("Name", name); // Do not rename (binary serialization)
si.AddValue("Size", Size); // Do not rename (binary serialization)
si.AddValue("Style", Style); // Do not rename (binary serialization)
si.AddValue("Unit", Unit); // Do not rename (binary serialization)
}
private static bool IsVerticalName(string familyName) => familyName?.Length > 0 && familyName[0] == '@';
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_nativeFont != IntPtr.Zero)
{
try
{
#if DEBUG
int status = !Gdip.Initialized ? Gdip.Ok :
#endif
Gdip.GdipDeleteFont(new HandleRef(this, _nativeFont));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
}
finally
{
_nativeFont = IntPtr.Zero;
}
}
}
/// <summary>
/// Returns the height of this Font in the specified graphics context.
/// </summary>
public float GetHeight(Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
float height;
int status = Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out height);
Gdip.CheckStatus(status);
return height;
}
public float GetHeight(float dpi)
{
float size;
int status = Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out size);
Gdip.CheckStatus(status);
return size;
}
/// <summary>
/// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this
/// <see cref='Font'/>.
/// </summary>
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (!(obj is Font font))
{
return false;
}
// Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties
// here.
// We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't
// have access to private/internal fields.
return font.FontFamily.Equals(FontFamily) &&
font.GdiVerticalFont == GdiVerticalFont &&
font.GdiCharSet == GdiCharSet &&
font.Style == Style &&
font.Size == Size &&
font.Unit == Unit;
}
/// <summary>
/// Gets the hash code for this <see cref='Font'/>.
/// </summary>
public override int GetHashCode()
{
return unchecked((int)((((uint)_fontStyle << 13) | ((uint)_fontStyle >> 19)) ^
(((uint)_fontUnit << 26) | ((uint)_fontUnit >> 6)) ^
(((uint)_fontSize << 7) | ((uint)_fontSize >> 25))));
}
/// <summary>
/// Returns a human-readable string representation of this <see cref='Font'/>.
/// </summary>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2}, Units={3}, GdiCharSet={4}, GdiVerticalFont={5}]",
GetType().Name,
FontFamily.Name,
_fontSize,
(int)_fontUnit,
_gdiCharSet,
_gdiVerticalFont);
}
// This is used by SystemFonts when constructing a system Font objects.
internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName;
public unsafe void ToLogFont(object logFont, Graphics graphics)
{
if (logFont == null)
{
throw new ArgumentNullException(nameof(logFont));
}
Type type = logFont.GetType();
int nativeSize = sizeof(SafeNativeMethods.LOGFONT);
if (Marshal.SizeOf(type) != nativeSize)
{
// If we don't actually have an object that is LOGFONT in size, trying to pass
// it to GDI+ is likely to cause an AV.
throw new ArgumentException();
}
SafeNativeMethods.LOGFONT nativeLogFont = ToLogFontInternal(graphics);
// PtrToStructure requires that the passed in object not be a value type.
if (!type.IsValueType)
{
Marshal.PtrToStructure(new IntPtr(&nativeLogFont), logFont);
}
else
{
GCHandle handle = GCHandle.Alloc(logFont, GCHandleType.Pinned);
Buffer.MemoryCopy(&nativeLogFont, (byte*)handle.AddrOfPinnedObject(), nativeSize, nativeSize);
handle.Free();
}
}
private unsafe SafeNativeMethods.LOGFONT ToLogFontInternal(Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
SafeNativeMethods.LOGFONT logFont = new SafeNativeMethods.LOGFONT();
Gdip.CheckStatus(Gdip.GdipGetLogFontW(
new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), ref logFont));
// Prefix the string with '@' if this is a gdiVerticalFont.
if (_gdiVerticalFont)
{
Span<char> faceName = logFont.lfFaceName;
faceName.Slice(0, faceName.Length - 1).CopyTo(faceName.Slice(1));
faceName[0] = '@';
// Docs require this to be null terminated
faceName[faceName.Length - 1] = '\0';
}
if (logFont.lfCharSet == 0)
{
logFont.lfCharSet = _gdiCharSet;
}
return logFont;
}
}
}
| |
// 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.Contracts;
using System.Linq;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter
{
private void WriteMethodDefinition(IMethodDefinition method)
{
if (method.IsPropertyOrEventAccessor())
return;
if (method.IsDestructor())
{
WriteDestructor(method);
return;
}
string name = method.GetMethodName();
WriteMethodPseudoCustomAttributes(method);
WriteAttributes(method.Attributes);
WriteAttributes(method.SecurityAttributes);
if (!method.ContainingTypeDefinition.IsInterface)
{
if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility);
WriteMethodModifiers(method);
}
WriteInterfaceMethodModifiers(method);
WriteMethodDefinitionSignature(method, name);
WriteMethodBody(method);
}
private void WriteDestructor(IMethodDefinition method)
{
WriteSymbol("~");
WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name);
WriteSymbol("(");
WriteSymbol(")", false);
WriteEmptyBody();
}
private void WriteMethodDefinitionSignature(IMethodDefinition method, string name)
{
bool isOperator = method.IsConversionOperator();
if (!isOperator && !method.IsConstructor)
{
WriteAttributes(method.ReturnValueAttributes, true);
// We are ignoring custom modifiers right now, we might need to add them later.
WriteTypeName(method.Type, isDynamic: IsDynamic(method.ReturnValueAttributes));
}
WriteIdentifier(name);
if (isOperator)
{
WriteSpace();
WriteTypeName(method.Type);
}
Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances");
if (method.IsGeneric)
WriteGenericParameters(method.GenericParameters);
WriteParameters(method.Parameters, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments);
if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod())
WriteGenericContraints(method.GenericParameters);
}
private void WriteParameters(IEnumerable<IParameterDefinition> parameters, bool property = false, bool extensionMethod = false, bool acceptsExtraArguments = false)
{
string start = property ? "[" : "(";
string end = property ? "]" : ")";
WriteSymbol(start);
_writer.WriteList(parameters, p =>
{
WriteParameter(p, extensionMethod);
extensionMethod = false;
});
if (acceptsExtraArguments)
{
if (parameters.Any())
_writer.WriteSymbol(",");
_writer.WriteSpace();
_writer.Write("__arglist");
}
WriteSymbol(end);
}
private void WriteParameter(IParameterDefinition parameter, bool extensionMethod)
{
WriteAttributes(parameter.Attributes, true);
if (extensionMethod)
WriteKeyword("this");
if (parameter.IsParameterArray)
WriteKeyword("params");
if (parameter.IsOut && !parameter.IsIn && parameter.IsByReference)
{
WriteKeyword("out");
}
else
{
// For In/Out we should not emit them until we find a scenario that is needs thems.
//if (parameter.IsIn)
// WriteFakeAttribute("System.Runtime.InteropServices.In", writeInline: true);
//if (parameter.IsOut)
// WriteFakeAttribute("System.Runtime.InteropServices.Out", writeInline: true);
if (parameter.IsByReference)
WriteKeyword("ref");
}
WriteTypeName(parameter.Type, isDynamic: IsDynamic(parameter.Attributes));
WriteIdentifier(parameter.Name);
if (parameter.IsOptional && parameter.HasDefaultValue)
{
WriteSymbol("=");
WriteMetadataConstant(parameter.DefaultValue, parameter.Type);
}
}
private void WriteInterfaceMethodModifiers(IMethodDefinition method)
{
if (method.GetHiddenBaseMethod(_filter) != Dummy.Method)
WriteKeyword("new");
}
private void WriteMethodModifiers(IMethodDefinition method)
{
if (method.IsMethodUnsafe())
WriteKeyword("unsafe");
if (method.IsStatic)
WriteKeyword("static");
if (method.IsVirtual)
{
if (method.IsNewSlot)
{
if (method.IsAbstract)
WriteKeyword("abstract");
else if (!method.IsSealed) // non-virtual interfaces implementations are sealed virtual newslots
WriteKeyword("virtual");
}
else
{
if (method.IsAbstract)
WriteKeyword("abstract");
else if (method.IsSealed)
WriteKeyword("sealed");
WriteKeyword("override");
}
}
}
private void WriteMethodBody(IMethodDefinition method)
{
if (method.IsAbstract || !_forCompilation)
{
WriteSymbol(";");
return;
}
if (method.IsConstructor)
WriteBaseConstructorCall(method.ContainingTypeDefinition);
// Write Dummy Body
WriteSpace();
WriteSymbol("{", true);
WriteOutParameterInitializations(method);
if (_forCompilationThrowPlatformNotSupported)
{
Write("throw new ");
if (_forCompilationIncludeGlobalprefix)
Write("global::");
Write("System.PlatformNotSupportedException(); ");
}
else if (method.ContainingTypeDefinition.IsValueType && method.IsConstructor)
{
// Structs cannot have empty constructors so we need to output this dummy body
Write("throw new ");
if (_forCompilationIncludeGlobalprefix)
Write("global::");
Write("System.NotImplementedException(); ");
}
else if (!TypeHelper.TypesAreEquivalent(method.Type, method.ContainingTypeDefinition.PlatformType.SystemVoid))
{
WriteKeyword("return");
WriteDefaultOf(method.Type);
WriteSymbol(";", true);
}
WriteSymbol("}");
}
private void WritePrivateConstructor(ITypeDefinition type)
{
if (!_forCompilation ||
type.IsInterface ||
type.IsEnum ||
type.IsDelegate ||
type.IsValueType ||
type.IsStatic)
return;
WriteVisibility(TypeMemberVisibility.Assembly);
WriteIdentifier(((INamedEntity)type).Name);
WriteSymbol("(");
WriteSymbol(")");
WriteBaseConstructorCall(type);
WriteEmptyBody();
}
private void WriteOutParameterInitializations(IMethodDefinition method)
{
if (!_forCompilation)
return;
var outParams = method.Parameters.Where(p => p.IsOut);
foreach (var param in outParams)
{
WriteIdentifier(param.Name);
WriteSpace();
WriteSymbol("=", true);
WriteDefaultOf(param.Type);
WriteSymbol(";", true);
}
}
private void WriteBaseConstructorCall(ITypeDefinition type)
{
if (!_forCompilation)
return;
ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull();
if (baseType == null)
return;
var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m));
var defaultCtor = ctors.Where(c => c.ParameterCount == 0);
// Don't need a base call if we have a default constructor
if (defaultCtor.Any())
return;
var ctor = ctors.FirstOrDefault();
if (ctor == null)
return;
WriteSpace();
WriteSymbol(":", true);
WriteKeyword("base");
WriteSymbol("(");
_writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type));
WriteSymbol(")");
}
private void WriteEmptyBody()
{
if (!_forCompilation)
{
WriteSymbol(";");
}
else
{
WriteSpace();
WriteSymbol("{", true);
WriteSymbol("}");
}
}
private void WriteDefaultOf(ITypeReference type)
{
WriteKeyword("default", true);
WriteSymbol("(");
WriteTypeName(type, true);
WriteSymbol(")");
}
public static IDefinition GetDummyConstructor(ITypeDefinition type)
{
return new DummyInternalConstructor() { ContainingType = type };
}
private class DummyInternalConstructor : IDefinition
{
public ITypeDefinition ContainingType { get; set; }
public IEnumerable<ICustomAttribute> Attributes
{
get { throw new System.NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
public IEnumerable<ILocation> Locations
{
get { throw new System.NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
}
}
}
| |
/*
* 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 OpenMetaverse;
using System;
namespace OpenSim.Framework
{
/// <summary>
/// Represents an item in a task inventory
/// </summary>
public class TaskInventoryItem : ICloneable
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// XXX This should really be factored out into some constants class.
/// </summary>
private const uint FULL_MASK_PERMISSIONS_GENERAL = 2147483647;
private UUID _assetID = UUID.Zero;
private uint _baseMask = FULL_MASK_PERMISSIONS_GENERAL;
private uint _creationDate = 0;
private string _creatorData = String.Empty;
private UUID _creatorID = UUID.Zero;
private string _description = String.Empty;
private uint _everyoneMask = FULL_MASK_PERMISSIONS_GENERAL;
private uint _flags = 0;
private UUID _groupID = UUID.Zero;
private uint _groupMask = FULL_MASK_PERMISSIONS_GENERAL;
private int _invType = 0;
private UUID _itemID = UUID.Zero;
private UUID _lastOwnerID = UUID.Zero;
private UUID _loadedID = UUID.Zero;
private string _name = String.Empty;
private uint _nextOwnerMask = FULL_MASK_PERMISSIONS_GENERAL;
private UUID _oldID;
private bool _ownerChanged = false;
private UUID _ownerID = UUID.Zero;
private uint _ownerMask = FULL_MASK_PERMISSIONS_GENERAL;
private UUID _parentID = UUID.Zero; //parent folder id
private UUID _parentPartID = UUID.Zero; // SceneObjectPart this is inside
private UUID _permsGranter;
private int _permsMask;
private int _type = 0;
public TaskInventoryItem()
{
ScriptRunning = true;
CreationDate = (uint)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
}
public UUID AssetID
{
get
{
return _assetID;
}
set
{
_assetID = value;
}
}
public uint BasePermissions
{
get
{
return _baseMask;
}
set
{
_baseMask = value;
}
}
public uint CreationDate
{
get
{
return _creationDate;
}
set
{
_creationDate = value;
}
}
public string CreatorData // = <profile url>;<name>
{
get { return _creatorData; }
set { _creatorData = value; }
}
public UUID CreatorID
{
get
{
return _creatorID;
}
set
{
_creatorID = value;
}
}
/// <summary>
/// Used by the DB layer to retrieve / store the entire user identification.
/// The identification can either be a simple UUID or a string of the form
/// uuid[;profile_url[;name]]
/// </summary>
public string CreatorIdentification
{
get
{
if (!string.IsNullOrEmpty(_creatorData))
return _creatorID.ToString() + ';' + _creatorData;
else
return _creatorID.ToString();
}
set
{
if ((value == null) || (value != null && value == string.Empty))
{
_creatorData = string.Empty;
return;
}
if (!value.Contains(";")) // plain UUID
{
UUID uuid = UUID.Zero;
UUID.TryParse(value, out uuid);
_creatorID = uuid;
}
else // <uuid>[;<endpoint>[;name]]
{
string name = "Unknown User";
string[] parts = value.Split(';');
if (parts.Length >= 1)
{
UUID uuid = UUID.Zero;
UUID.TryParse(parts[0], out uuid);
_creatorID = uuid;
}
if (parts.Length >= 2)
_creatorData = parts[1];
if (parts.Length >= 3)
name = parts[2];
_creatorData += ';' + name;
}
}
}
public uint CurrentPermissions
{
get
{
return _ownerMask;
}
set
{
_ownerMask = value;
}
}
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
public uint EveryonePermissions
{
get
{
return _everyoneMask;
}
set
{
_everyoneMask = value;
}
}
public uint Flags
{
get
{
return _flags;
}
set
{
_flags = value;
}
}
public UUID GroupID
{
get
{
return _groupID;
}
set
{
_groupID = value;
}
}
public uint GroupPermissions
{
get
{
return _groupMask;
}
set
{
_groupMask = value;
}
}
public int InvType
{
get
{
return _invType;
}
set
{
_invType = value;
}
}
public UUID ItemID
{
get
{
return _itemID;
}
set
{
_itemID = value;
}
}
public UUID LastOwnerID
{
get
{
return _lastOwnerID;
}
set
{
_lastOwnerID = value;
}
}
public UUID LoadedItemID
{
get
{
return _loadedID;
}
set
{
_loadedID = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public uint NextPermissions
{
get
{
return _nextOwnerMask;
}
set
{
_nextOwnerMask = value;
}
}
public UUID OldItemID
{
get
{
return _oldID;
}
set
{
_oldID = value;
}
}
public bool OwnerChanged
{
get
{
return _ownerChanged;
}
set
{
_ownerChanged = value;
// m_log.DebugFormat(
// "[TASK INVENTORY ITEM]: Owner changed set {0} for {1} {2} owned by {3}",
// _ownerChanged, Name, ItemID, OwnerID);
}
}
public UUID OwnerID
{
get
{
return _ownerID;
}
set
{
_ownerID = value;
}
}
public UUID ParentID
{
get
{
return _parentID;
}
set
{
_parentID = value;
}
}
public UUID ParentPartID
{
get
{
return _parentPartID;
}
set
{
_parentPartID = value;
}
}
public UUID PermsGranter
{
get
{
return _permsGranter;
}
set
{
_permsGranter = value;
}
}
public int PermsMask
{
get
{
return _permsMask;
}
set
{
_permsMask = value;
}
}
/// <summary>
/// This used ONLY during copy. It can't be relied on at other times!
/// </summary>
/// <remarks>
/// For true script running status, use IEntityInventory.TryGetScriptInstanceRunning() for now.
/// </remarks>
public bool ScriptRunning { get; set; }
public int Type
{
get
{
return _type;
}
set
{
_type = value;
}
}
// See ICloneable
#region ICloneable Members
public Object Clone()
{
return MemberwiseClone();
}
#endregion ICloneable Members
/// <summary>
/// Reset the UUIDs for this item.
/// </summary>
/// <param name="partID">The new part ID to which this item belongs</param>
public void ResetIDs(UUID partID)
{
LoadedItemID = OldItemID;
OldItemID = ItemID;
ItemID = UUID.Random();
ParentPartID = partID;
ParentID = partID;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Test
{
public partial class ZipTest
{
[Fact]
public async Task CreateFromDirectoryNormal()
{
await TestCreateDirectory(zfolder("normal"), true);
if (Interop.IsWindows) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
await TestCreateDirectory(zfolder("unicode"), true);
}
}
private async Task TestCreateDirectory(string folderName, Boolean testWithBaseDir)
{
string noBaseDir = GetTmpFilePath();
ZipFile.CreateFromDirectory(folderName, noBaseDir);
await IsZipSameAsDirAsync(noBaseDir, folderName, ZipArchiveMode.Read, true, true);
if (testWithBaseDir)
{
string withBaseDir = GetTmpFilePath();
ZipFile.CreateFromDirectory(folderName, withBaseDir, CompressionLevel.Optimal, true);
SameExceptForBaseDir(noBaseDir, withBaseDir, folderName);
}
}
private static void SameExceptForBaseDir(string zipNoBaseDir, string zipBaseDir, string baseDir)
{
//b has the base dir
using (ZipArchive a = ZipFile.Open(zipNoBaseDir, ZipArchiveMode.Read),
b = ZipFile.Open(zipBaseDir, ZipArchiveMode.Read))
{
var aCount = a.Entries.Count;
var bCount = b.Entries.Count;
Assert.Equal(aCount, bCount);
int bIdx = 0;
foreach (ZipArchiveEntry aEntry in a.Entries)
{
ZipArchiveEntry bEntry = b.Entries[bIdx++];
Assert.Equal(Path.Combine(Path.GetFileName(baseDir), aEntry.FullName), bEntry.FullName);
Assert.Equal(aEntry.Name, bEntry.Name);
Assert.Equal(aEntry.Length, bEntry.Length);
Assert.Equal(aEntry.CompressedLength, bEntry.CompressedLength);
using (Stream aStream = aEntry.Open(), bStream = bEntry.Open())
{
StreamsEqual(aStream, bStream);
}
}
}
}
[Fact]
public void ExtractToDirectoryNormal()
{
TestExtract(zfile("normal.zip"), zfolder("normal"));
if (Interop.IsWindows) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
TestExtract(zfile("unicode.zip"), zfolder("unicode"));
}
TestExtract(zfile("empty.zip"), zfolder("empty"));
TestExtract(zfile("explicitdir1.zip"), zfolder("explicitdir"));
TestExtract(zfile("explicitdir2.zip"), zfolder("explicitdir"));
TestExtract(zfile("appended.zip"), zfolder("small"));
TestExtract(zfile("prepended.zip"), zfolder("small"));
TestExtract(zfile("noexplicitdir.zip"), zfolder("explicitdir"));
}
private void TestExtract(string zipFileName, string folderName)
{
string tempFolder = GetTmpDirPath(true);
ZipFile.ExtractToDirectory(zipFileName, tempFolder);
DirsEqual(tempFolder, folderName);
Assert.Throws<ArgumentNullException>(() => ZipFile.ExtractToDirectory(null, tempFolder));
}
#region "Extension Methods"
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CreateEntryFromFileTest(bool withCompressionLevel)
{
//add file
string testArchive = CreateTempCopyFile(zfile("normal.zip"));
using (ZipArchive archive = ZipFile.Open(testArchive, ZipArchiveMode.Update))
{
string entryName = "added.txt";
string sourceFilePath = zmodified(Path.Combine("addFile", entryName));
Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).CreateEntryFromFile(sourceFilePath, entryName));
Assert.Throws<ArgumentNullException>(() => archive.CreateEntryFromFile(null, entryName));
Assert.Throws<ArgumentNullException>(() => archive.CreateEntryFromFile(sourceFilePath, null));
ZipArchiveEntry e = withCompressionLevel ?
archive.CreateEntryFromFile(sourceFilePath, entryName) :
archive.CreateEntryFromFile(sourceFilePath, entryName, CompressionLevel.Fastest);
Assert.NotNull(e);
}
await IsZipSameAsDirAsync(testArchive, zmodified("addFile"), ZipArchiveMode.Read, true, true);
}
[Fact]
public void ExtractToFileTest()
{
using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read))
{
string file = GetTmpFilePath();
ZipArchiveEntry e = archive.GetEntry("first.txt");
Assert.Throws<ArgumentNullException>(() => ((ZipArchiveEntry)null).ExtractToFile(file));
Assert.Throws<ArgumentNullException>(() => e.ExtractToFile(null));
//extract when there is nothing there
e.ExtractToFile(file);
using (Stream fs = File.Open(file, FileMode.Open), es = e.Open())
{
StreamsEqual(fs, es);
}
Assert.Throws<IOException>(() => e.ExtractToFile(file, false));
//truncate file
using (Stream fs = File.Open(file, FileMode.Truncate)) { }
//now use overwrite mode
e.ExtractToFile(file, true);
using (Stream fs = File.Open(file, FileMode.Open), es = e.Open())
{
StreamsEqual(fs, es);
}
}
}
[Fact]
public void ExtractToDirectoryTest()
{
using (ZipArchive archive = ZipFile.Open(zfile("normal.zip"), ZipArchiveMode.Read))
{
string tempFolder = GetTmpDirPath(false);
Assert.Throws<ArgumentNullException>(() => ((ZipArchive)null).ExtractToDirectory(tempFolder));
Assert.Throws<ArgumentNullException>(() => archive.ExtractToDirectory(null));
archive.ExtractToDirectory(tempFolder);
DirsEqual(tempFolder, zfolder("normal"));
}
if (Interop.IsWindows) // [ActiveIssue(846, PlatformID.AnyUnix)]
{
using (ZipArchive archive = ZipFile.OpenRead(zfile("unicode.zip")))
{
string tempFolder = GetTmpDirPath(false);
archive.ExtractToDirectory(tempFolder);
DirsEqual(tempFolder, zfolder("unicode"));
}
}
}
[Fact]
public void CreatedEmptyDirectoriesRoundtrip()
{
DirectoryInfo rootDir = new DirectoryInfo(GetTmpDirPath(create: true));
rootDir.CreateSubdirectory("empty1");
string archivePath = GetTmpFilePath();
ZipFile.CreateFromDirectory(
rootDir.FullName, archivePath,
CompressionLevel.Optimal, false, Encoding.UTF8);
using (ZipArchive archive = ZipFile.OpenRead(archivePath))
{
Assert.Equal(1, archive.Entries.Count);
Assert.True(archive.Entries[0].FullName.StartsWith("empty1"));
}
}
[Fact]
public void CreatedEmptyRootDirectoryRoundtrips()
{
DirectoryInfo emptyRoot = new DirectoryInfo(GetTmpDirPath(create: true));
string archivePath = GetTmpFilePath();
ZipFile.CreateFromDirectory(
emptyRoot.FullName, archivePath,
CompressionLevel.Optimal, true);
using (ZipArchive archive = ZipFile.OpenRead(archivePath))
{
Assert.Equal(1, archive.Entries.Count);
}
}
#endregion
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. All Rights Reserved.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
using System;
using System.Collections.Generic;
using Alachisoft.NosDB.Common.DataStructures;
using Alachisoft.NosDB.Common.Serialization;
using Alachisoft.NosDB.Common.Util;
using Newtonsoft.Json;
namespace Alachisoft.NosDB.Common.Configuration.Services
{
public class ClusterInfo : ICloneable, ICompactSerializable,IObjectId
{
private Dictionary<string, ShardInfo> _shards = new Dictionary<string, ShardInfo>(StringComparer.InvariantCultureIgnoreCase);
private Dictionary<string, DatabaseInfo> _databases = new Dictionary<string, DatabaseInfo>(StringComparer.InvariantCultureIgnoreCase);
/// <summary>
/// Gets/Sets the cluster name
/// </summary>
///
string _name = "";
[JsonProperty(PropertyName = "Name")]
public string Name { get { return _name!=null? _name.ToLower():null; } set { _name = value; } }
[JsonProperty(PropertyName = "_key")]
public string JsonDocumetId
{
get { return Name; }
set { Name = value; }
}
[JsonProperty(PropertyName = "UID")]
public string UID
{
get;
set;
}
/// <summary>
/// Gets/Sets detail shard information
/// </summary>
[JsonProperty(PropertyName = "ShardInfo")]
public Dictionary<string, ShardInfo> ShardInfo
{
get { return _shards; }
set { _shards = value; }
}
/// <summary>
/// Gets the meta-data info about configured databases
/// </summary>
[JsonProperty(PropertyName = "Databases")]
public Dictionary<string, DatabaseInfo> Databases
{
get { return _databases; }
set { _databases = value; }
}
public void AddShard(ShardInfo shard)
{
lock (ShardInfo)
{
ShardInfo.Add(shard.Name, shard);
}
}
public void AddShard(string name, ShardInfo server)
{
lock (ShardInfo)
{
ShardInfo.Add(name, server);
}
}
public void RemoveShard(string name)
{
lock (ShardInfo)
{
ShardInfo.Remove(name);
}
}
public bool ContainsShard(string name)
{
return ShardInfo.ContainsKey(name);
}
public ShardInfo GetShard(string name)
{
lock (ShardInfo)
{
if (ShardInfo.ContainsKey(name))
return ShardInfo[name];
return null;
}
}
public void AddDatabase(DatabaseInfo database)
{
lock (Databases)
{
Databases.Add(database.Name, database);
}
}
public void AddDatabase(string name, DatabaseInfo database)
{
lock (Databases)
{
Databases.Add(name, database);
}
}
/// <summary>
/// Replaces current DatabaseInfo with the one provided if database exists else adds a new database
/// </summary>
/// <param name="database"></param>
public void UpdateDatabase(DatabaseInfo database)
{
lock (Databases)
{
if (ContainsDatabase(database.Name))
{
Databases[database.Name]= database;
}
else
{
AddDatabase(database);
}
}
}
public void RemoveDatabase(string name)
{
lock (Databases)
{
Databases.Remove(name);
}
}
public bool ContainsDatabase(string name)
{
return Databases.ContainsKey(name);
}
public DatabaseInfo GetDatabase(string name)
{
lock (Databases)
{
if (Databases.ContainsKey(name))
return Databases[name];
return null;
}
}
public bool IsShardUnderRemoval(string shard)
{
ShardInfo shardInfo = GetShard(shard);
if (shardInfo != null)
return shardInfo.GracefullRemovalInProcess;
return false;
}
public void MarkShardForGracefullRemoval(string shard)
{
ShardInfo shardInfo = GetShard(shard);
if (shardInfo != null)
shardInfo.GracefullRemovalInProcess = true;
}
internal IDictionary<string, long> GetAmountOfDataOnEachShard()
{
IDictionary<string, long> amountOfDataOnEachShard = new Dictionary<string, long>();
foreach (DatabaseInfo databaseInfo in Databases.Values)
{
foreach (CollectionInfo collection in databaseInfo.Collections.Values)
{
IDictionary<string, long> sizeOfCollectionOnShards = collection.DistributionStrategy.GetAmountOfCollectionDataOnEachShard();
foreach (var sizeOfCollectionOnShard in sizeOfCollectionOnShards)
{
if (amountOfDataOnEachShard.ContainsKey(sizeOfCollectionOnShard.Key))
amountOfDataOnEachShard[sizeOfCollectionOnShard.Key] += sizeOfCollectionOnShard.Value;
else
amountOfDataOnEachShard.Add(sizeOfCollectionOnShard.Key, sizeOfCollectionOnShard.Value);
}
}
}
return amountOfDataOnEachShard;
}
public string GetShardWithLowestAmountOfData()
{
KeyValuePair<string, long> minimumShardSize = new KeyValuePair<string, long>("", long.MaxValue);
foreach (var shardSize in GetAmountOfDataOnEachShard())
{
if (shardSize.Value < minimumShardSize.Value)
minimumShardSize = new KeyValuePair<string, long>(shardSize.Key, shardSize.Value);
}
if (string.IsNullOrEmpty(minimumShardSize.Key)) throw new Exception("Cannot tell the shard with minimum amount of data");
return minimumShardSize.Key;
}
public PartitionKey GetPartitonKey(string databaseName, string collectionName)
{
// Can I receive null or empty string as collectionName or databaseName?
foreach (DatabaseInfo databaseInfo in Databases.Values)
{
if (databaseInfo.Name.Equals(databaseName))
return databaseInfo.GetPartitionKey(collectionName);
}
return null; // To be decided later if to throw exception here or return null
}
public ShardInfo GetShardInfo(string shardName)
{
foreach (ShardInfo shard in ShardInfo.Values)
{
if (shard.Name.Equals(shardName))
{
if (shard.IsReadOnly)
{
throw new Exception("Primary Shard is unavailable or under selection at the moment. ReadOnly Mode is activated currently");
}
return shard;
}
}
return null;
}
#region ICompactSerializable Members
public void Deserialize(Common.Serialization.IO.CompactReader reader)
{
Name = reader.ReadObject() as string;
_shards = SerializationUtility.DeserializeDictionary<string, ShardInfo>(reader);
_databases = SerializationUtility.DeserializeDictionary<string, DatabaseInfo>(reader);
UID = reader.ReadObject() as string;
}
public void Serialize(Common.Serialization.IO.CompactWriter writer)
{
writer.WriteObject(Name);
SerializationUtility.SerializeDictionary<string, ShardInfo>(ShardInfo, writer);
SerializationUtility.SerializeDictionary<string, DatabaseInfo>(Databases, writer);
writer.WriteObject(UID);
}
#endregion
#region ICloneable Member
public object Clone()
{
ClusterInfo clusterInfo = new ClusterInfo();
clusterInfo.Name = Name;
clusterInfo._shards = ShardInfo != null ? ShardInfo.Clone<string,ShardInfo>(): null;
clusterInfo._databases = Databases != null ? Databases.Clone<string,DatabaseInfo>(): null;
clusterInfo.UID = UID;
return clusterInfo;
}
#endregion
public IList<string> GetShardsUnderGracefullRemoval()
{
List<string> removeableShards = new List<string>();
if(ShardInfo !=null)
{
foreach(string shard in ShardInfo.Keys)
{
if (IsShardUnderRemoval(shard))
removeableShards.Add(shard);
}
}
return removeableShards;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Messaging;
namespace Orleans.Runtime
{
internal class SocketManager
{
private readonly LRU<IPEndPoint, Socket> cache;
private readonly TimeSpan connectionTimeout;
private readonly ILogger logger;
private const int MAX_SOCKETS = 200;
internal SocketManager(IOptions<NetworkingOptions> options, ILoggerFactory loggerFactory)
{
var networkingOptions = options.Value;
connectionTimeout = networkingOptions.OpenConnectionTimeout;
cache = new LRU<IPEndPoint, Socket>(MAX_SOCKETS, networkingOptions.MaxSocketAge, SendingSocketCreator);
this.logger = loggerFactory.CreateLogger<SocketManager>();
cache.RaiseFlushEvent += FlushHandler;
}
/// <summary>
/// Creates a socket bound to an address for use accepting connections.
/// This is for use by client gateways and other acceptors.
/// </summary>
/// <param name="address">The address to bind to.</param>
/// <returns>The new socket, appropriately bound.</returns>
internal Socket GetAcceptingSocketForEndpoint(IPEndPoint address)
{
var s = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
// Prep the socket so it will reset on close
s.LingerState = new LingerOption(true, 0);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
s.EnableFastpath();
// The following timeout is only effective when calling the synchronous
// Socket.Receive method. We should only use this method when we are reading
// the connection preamble
s.ReceiveTimeout = (int) this.connectionTimeout.TotalMilliseconds;
// And bind it to the address
s.Bind(address);
}
catch (Exception)
{
CloseSocket(s);
throw;
}
return s;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal bool CheckSendingSocket(IPEndPoint target)
{
return cache.ContainsKey(target);
}
internal Socket GetSendingSocket(IPEndPoint target)
{
return cache.Get(target);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Socket SendingSocketCreator(IPEndPoint target)
{
var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
s.EnableFastpath();
Connect(s, target, connectionTimeout);
// Prep the socket so it will reset on close and won't Nagle
s.LingerState = new LingerOption(true, 0);
s.NoDelay = true;
WriteConnectionPreamble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket
// Start an asynch receive off of the socket to detect closure
var receiveAsyncEventArgs = new SocketAsyncEventArgs
{
BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[4]) },
UserToken = new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this)
};
receiveAsyncEventArgs.Completed += ReceiveCallback;
bool receiveCompleted = s.ReceiveAsync(receiveAsyncEventArgs);
NetworkingStatisticsGroup.OnOpenedSendingSocket();
if (!receiveCompleted)
{
ReceiveCallback(this, receiveAsyncEventArgs);
}
}
catch (Exception)
{
try
{
s.Dispose();
}
catch (Exception)
{
// ignore
}
throw;
}
return s;
}
internal static void WriteConnectionPreamble(Socket socket, GrainId grainId)
{
int size = 0;
byte[] grainIdByteArray = null;
if (grainId != null)
{
grainIdByteArray = grainId.ToByteArray();
size += grainIdByteArray.Length;
}
ByteArrayBuilder sizeArray = new ByteArrayBuilder();
sizeArray.Append(size);
socket.Send(sizeArray.ToBytes()); // The size of the data that is coming next.
//socket.Send(guid.ToByteArray()); // The guid of client/silo id
if (grainId != null)
{
// No need to send in a loop.
// From MSDN: If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent,
// unless a time-out was set by using Socket.SendTimeout.
// If the time-out value was exceeded, the Send call will throw a SocketException.
socket.Send(grainIdByteArray); // The grainId of the client
}
}
// We start an asynch receive, with this callback, off of every send socket.
// Since we should never see data coming in on these sockets, having the receive complete means that
// the socket is in an unknown state and we should close it and try again.
private static void ReceiveCallback(object sender, SocketAsyncEventArgs socketAsyncEventArgs)
{
var t = socketAsyncEventArgs.UserToken as Tuple<Socket, IPEndPoint, SocketManager>;
try
{
t?.Item3.InvalidateEntry(t.Item2);
}
catch (Exception ex)
{
t?.Item3.logger.Error(ErrorCode.Messaging_Socket_ReceiveError, $"ReceiveCallback: {t?.Item2}", ex);
}
finally
{
socketAsyncEventArgs.Dispose();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s")]
internal void ReturnSendingSocket(Socket s)
{
// Do nothing -- the socket will get cleaned up when it gets flushed from the cache
}
private static void FlushHandler(Object sender, LRU<IPEndPoint, Socket>.FlushEventArgs args)
{
if (args.Value == null) return;
CloseSocket(args.Value);
NetworkingStatisticsGroup.OnClosedSendingSocket();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void InvalidateEntry(IPEndPoint target)
{
Socket socket;
if (!cache.RemoveKey(target, out socket)) return;
CloseSocket(socket);
NetworkingStatisticsGroup.OnClosedSendingSocket();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
// Note that this method assumes that there are no other threads accessing this object while this method runs.
// Since this is true for the MessageCenter's use of this object, we don't lock around all calls to avoid the overhead.
internal void Stop()
{
// Clear() on an LRU<> calls the flush handler on every item, so no need to manually close the sockets.
cache.Clear();
}
/// <summary>
/// Connect the socket to the target endpoint
/// </summary>
/// <param name="s">The socket</param>
/// <param name="endPoint">The target endpoint</param>
/// <param name="connectionTimeout">The timeout value to use when opening the connection</param>
/// <exception cref="TimeoutException">When the connection could not be established in time</exception>
internal static void Connect(Socket s, IPEndPoint endPoint, TimeSpan connectionTimeout)
{
var signal = new AutoResetEvent(false);
var e = new SocketAsyncEventArgs();
e.RemoteEndPoint = endPoint;
e.Completed += (sender, eventArgs) => signal.Set();
s.ConnectAsync(e);
if (!signal.WaitOne(connectionTimeout))
throw new TimeoutException($"Connection to {endPoint} could not be established in {connectionTimeout}");
if (e.SocketError != SocketError.Success || !s.Connected)
throw new OrleansException($"Could not connect to {endPoint}: {e.SocketError}");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void CloseSocket(Socket s)
{
if (s == null)
{
return;
}
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (ObjectDisposedException)
{
// Socket is already closed -- we're done here
return;
}
catch (Exception)
{
// Ignore
}
try
{
if (s.Connected)
s.Disconnect(false);
else
s.Close();
}
catch (Exception)
{
// Ignore
}
try
{
s.Dispose();
}
catch (Exception)
{
// Ignore
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// SkipUrlEncodingOperations operations.
/// </summary>
internal partial class SkipUrlEncodingOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISkipUrlEncodingOperations
{
/// <summary>
/// Initializes a new instance of the SkipUrlEncodingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SkipUrlEncodingOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodPathValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/path/valid/{unencodedPathParam}").ToString();
_url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathPathValidWithHttpMessagesAsync(string unencodedPathParam, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (unencodedPathParam == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "unencodedPathParam");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPathPathValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/path/path/valid/{unencodedPathParam}").ToString();
_url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerPathValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string unencodedPathParam = "path1/path2/path3";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("unencodedPathParam", unencodedPathParam);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerPathValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/path/valid/{unencodedPathParam}").ToString();
_url = _url.Replace("{unencodedPathParam}", unencodedPathParam);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodQueryValidWithHttpMessagesAsync(string q1, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (q1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "q1");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodQueryValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/query/valid").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetMethodQueryNullWithHttpMessagesAsync(string q1 = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetMethodQueryNull", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/method/query/null").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetPathQueryValidWithHttpMessagesAsync(string q1, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (q1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "q1");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPathQueryValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/path/query/valid").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetSwaggerQueryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string q1 = "value1&q2=value2&q3=value3";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("q1", q1);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetSwaggerQueryValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/skipUrlEncoding/swagger/query/valid").ToString();
List<string> _queryParameters = new List<string>();
if (q1 != null)
{
_queryParameters.Add(string.Format("q1={0}", q1));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Xunit;
namespace System.Numerics.Matrices.Tests
{
/// <summary>
/// Tests for the Matrix1x3 structure.
/// </summary>
public class Test1x3
{
const int Epsilon = 10;
[Fact]
public void ConstructorValuesAreAccessibleByIndexer()
{
Matrix1x3 matrix1x3;
matrix1x3 = new Matrix1x3();
for (int x = 0; x < matrix1x3.Columns; x++)
{
for (int y = 0; y < matrix1x3.Rows; y++)
{
Assert.Equal(0, matrix1x3[x, y], Epsilon);
}
}
double value = 33.33;
matrix1x3 = new Matrix1x3(value);
for (int x = 0; x < matrix1x3.Columns; x++)
{
for (int y = 0; y < matrix1x3.Rows; y++)
{
Assert.Equal(value, matrix1x3[x, y], Epsilon);
}
}
GenerateFilledMatrixWithValues(out matrix1x3);
for (int y = 0; y < matrix1x3.Rows; y++)
{
for (int x = 0; x < matrix1x3.Columns; x++)
{
Assert.Equal(y * matrix1x3.Columns + x, matrix1x3[x, y], Epsilon);
}
}
}
[Fact]
public void IndexerGetAndSetValuesCorrectly()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
for (int x = 0; x < matrix1x3.Columns; x++)
{
for (int y = 0; y < matrix1x3.Rows; y++)
{
matrix1x3[x, y] = y * matrix1x3.Columns + x;
}
}
for (int y = 0; y < matrix1x3.Rows; y++)
{
for (int x = 0; x < matrix1x3.Columns; x++)
{
Assert.Equal(y * matrix1x3.Columns + x, matrix1x3[x, y], Epsilon);
}
}
}
[Fact]
public void ConstantValuesAreCorrect()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
Assert.Equal(1, matrix1x3.Columns);
Assert.Equal(3, matrix1x3.Rows);
Assert.Equal(Matrix1x3.ColumnCount, matrix1x3.Columns);
Assert.Equal(Matrix1x3.RowCount, matrix1x3.Rows);
}
[Fact]
public void ScalarMultiplicationIsCorrect()
{
Matrix1x3 matrix1x3;
GenerateFilledMatrixWithValues(out matrix1x3);
for (double c = -10; c <= 10; c += 0.5)
{
Matrix1x3 result = matrix1x3 * c;
for (int y = 0; y < matrix1x3.Rows; y++)
{
for (int x = 0; x < matrix1x3.Columns; x++)
{
Assert.Equal(matrix1x3[x, y] * c, result[x, y], Epsilon);
}
}
}
}
[Fact]
public void MemberGetAndSetValuesCorrectly()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
matrix1x3.M11 = 0;
matrix1x3.M12 = 1;
matrix1x3.M13 = 2;
Assert.Equal(0, matrix1x3.M11, Epsilon);
Assert.Equal(1, matrix1x3.M12, Epsilon);
Assert.Equal(2, matrix1x3.M13, Epsilon);
Assert.Equal(matrix1x3[0, 0], matrix1x3.M11, Epsilon);
Assert.Equal(matrix1x3[0, 1], matrix1x3.M12, Epsilon);
Assert.Equal(matrix1x3[0, 2], matrix1x3.M13, Epsilon);
}
[Fact]
public void HashCodeGenerationWorksCorrectly()
{
HashSet<int> hashCodes = new HashSet<int>();
Matrix1x3 value = new Matrix1x3(1);
for (int i = 2; i <= 100; i++)
{
Assert.True(hashCodes.Add(value.GetHashCode()), "Unique hash code generation failure.");
value *= i;
}
}
[Fact]
public void SimpleAdditionGeneratesCorrectValues()
{
Matrix1x3 value1 = new Matrix1x3(1);
Matrix1x3 value2 = new Matrix1x3(99);
Matrix1x3 result = value1 + value2;
for (int y = 0; y < Matrix1x3.RowCount; y++)
{
for (int x = 0; x < Matrix1x3.ColumnCount; x++)
{
Assert.Equal(1 + 99, result[x, y], Epsilon);
}
}
}
[Fact]
public void SimpleSubtractionGeneratesCorrectValues()
{
Matrix1x3 value1 = new Matrix1x3(100);
Matrix1x3 value2 = new Matrix1x3(1);
Matrix1x3 result = value1 - value2;
for (int y = 0; y < Matrix1x3.RowCount; y++)
{
for (int x = 0; x < Matrix1x3.ColumnCount; x++)
{
Assert.Equal(100 - 1, result[x, y], Epsilon);
}
}
}
[Fact]
public void EqualityOperatorWorksCorrectly()
{
Matrix1x3 value1 = new Matrix1x3(100);
Matrix1x3 value2 = new Matrix1x3(50) * 2;
Assert.Equal(value1, value2);
Assert.True(value1 == value2, "Equality operator failed.");
}
[Fact]
public void AccessorThrowsWhenOutOfBounds()
{
Matrix1x3 matrix1x3 = new Matrix1x3();
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[-1, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[0, -1] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[1, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix1x3[0, 3] = 0; });
}
[Fact]
public void MuliplyByMatrix2x1ProducesMatrix2x3()
{
Matrix1x3 matrix1 = new Matrix1x3(3);
Matrix2x1 matrix2 = new Matrix2x1(2);
Matrix2x3 result = matrix1 * matrix2;
Matrix2x3 expected = new Matrix2x3(6, 6,
6, 6,
6, 6);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix3x1ProducesMatrix3x3()
{
Matrix1x3 matrix1 = new Matrix1x3(3);
Matrix3x1 matrix2 = new Matrix3x1(2);
Matrix3x3 result = matrix1 * matrix2;
Matrix3x3 expected = new Matrix3x3(6, 6, 6,
6, 6, 6,
6, 6, 6);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix4x1ProducesMatrix4x3()
{
Matrix1x3 matrix1 = new Matrix1x3(3);
Matrix4x1 matrix2 = new Matrix4x1(2);
Matrix4x3 result = matrix1 * matrix2;
Matrix4x3 expected = new Matrix4x3(6, 6, 6, 6,
6, 6, 6, 6,
6, 6, 6, 6);
Assert.Equal(expected, result);
}
private void GenerateFilledMatrixWithValues(out Matrix1x3 matrix)
{
matrix = new Matrix1x3(0,
1,
2);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Token = Lucene.Net.Analysis.Token;
using TokenStream = Lucene.Net.Analysis.TokenStream;
using ArrayUtil = Lucene.Net.Util.ArrayUtil;
namespace Lucene.Net.Index
{
/// <summary> A Payload is metadata that can be stored together with each occurrence
/// of a term. This metadata is stored inline in the posting list of the
/// specific term.
/// <p>
/// To store payloads in the index a {@link TokenStream} has to be used that
/// produces {@link Token}s containing payload data.
/// <p>
/// Use {@link TermPositions#GetPayloadLength()} and {@link TermPositions#GetPayload(byte[], int)}
/// to retrieve the payloads from the index.<br>
///
/// </summary>
[Serializable]
public class Payload : System.ICloneable
{
/// <summary>the byte array containing the payload data </summary>
protected internal byte[] data;
/// <summary>the offset within the byte array </summary>
protected internal int offset;
/// <summary>the length of the payload data </summary>
protected internal int length;
/// <summary>Creates an empty payload and does not allocate a byte array. </summary>
public Payload()
{
// nothing to do
}
/// <summary> Creates a new payload with the the given array as data.
/// A reference to the passed-in array is held, i. e. no
/// copy is made.
///
/// </summary>
/// <param name="data">the data of this payload
/// </param>
public Payload(byte[] data):this(data, 0, data.Length)
{
}
/// <summary> Creates a new payload with the the given array as data.
/// A reference to the passed-in array is held, i. e. no
/// copy is made.
///
/// </summary>
/// <param name="data">the data of this payload
/// </param>
/// <param name="offset">the offset in the data byte array
/// </param>
/// <param name="length">the length of the data
/// </param>
public Payload(byte[] data, int offset, int length)
{
if (offset < 0 || offset + length > data.Length)
{
throw new System.ArgumentException();
}
this.data = data;
this.offset = offset;
this.length = length;
}
/// <summary> Sets this payloads data.
/// A reference to the passed-in array is held, i. e. no
/// copy is made.
/// </summary>
public virtual void SetData(byte[] data)
{
SetData(data, 0, data.Length);
}
/// <summary> Sets this payloads data.
/// A reference to the passed-in array is held, i. e. no
/// copy is made.
/// </summary>
public virtual void SetData(byte[] data, int offset, int length)
{
this.data = data;
this.offset = offset;
this.length = length;
}
/// <summary> Returns a reference to the underlying byte array
/// that holds this payloads data.
/// </summary>
public virtual byte[] GetData()
{
return this.data;
}
/// <summary> Returns the offset in the underlying byte array </summary>
public virtual int GetOffset()
{
return this.offset;
}
/// <summary> Returns the length of the payload data. </summary>
public virtual int Length()
{
return this.length;
}
/// <summary> Returns the byte at the given index.</summary>
public virtual byte ByteAt(int index)
{
if (0 <= index && index < this.length)
{
return this.data[this.offset + index];
}
throw new System. IndexOutOfRangeException("Index of bound " + index);
}
/// <summary> Allocates a new byte array, copies the payload data into it and returns it. </summary>
public virtual byte[] ToByteArray()
{
byte[] retArray = new byte[this.length];
Array.Copy(this.data, this.offset, retArray, 0, this.length);
return retArray;
}
/// <summary> Copies the payload data to a byte array.
///
/// </summary>
/// <param name="target">the target byte array
/// </param>
/// <param name="targetOffset">the offset in the target byte array
/// </param>
public virtual void CopyTo(byte[] target, int targetOffset)
{
if (this.length > target.Length + targetOffset)
{
throw new System.IndexOutOfRangeException();
}
Array.Copy(this.data, this.offset, target, targetOffset, this.length);
}
/// <summary> Clones this payload by creating a copy of the underlying
/// byte array.
/// </summary>
public virtual object Clone()
{
// start with a shallow copy of data
Payload clone = (Payload) base.MemberwiseClone();
// only copy the part of data that belongs to this payload
if (offset == 0 && length == data.Length)
// it is the whole thing so just clone it
clone.data = (byte[])data.Clone();
else
{
// just get the part
clone.data = this.ToByteArray();
clone.offset = 0;
}
return clone;
}
public override bool Equals(object obj)
{
if (obj == this)
return true;
if (obj is Payload)
{
Payload other = (Payload)obj;
if (length == other.length)
{
for (int i = 0; i < length; i++)
if (data[offset + 1] != other.data[other.offset + i])
return false;
return true;
}
else
return false;
}
else
return false;
}
public override int GetHashCode()
{
return ArrayUtil.HashCode(data, offset, offset + length);
}
}
}
| |
// Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using GameKit.Coder;
using GameKit.Coder.LZMA;
using GameKit.Coder.XOR;
using GameKit.Log;
using GameKit.Packing;
using GameKit.Publish;
using Medusa.CoreProto;
using ProtoBuf;
namespace GameKit.Resource
{
public class FileListGenerator
{
private readonly Dictionary<FileListFile, FileList.FileItem> mItemDict = new Dictionary<FileListFile, FileList.FileItem>();
private readonly HashSet<string> mDirSet = new HashSet<string>();
private FileList mFileList = new FileList();
private uint mFileId;
private readonly List<ICoder> mCoders = new List<ICoder>();
private readonly List<FileList.FileCoder> mProtoCoders = new List<FileList.FileCoder>();
public FileListGenerator()
{
Clear();
}
public void Clear()
{
mItemDict.Clear();
mDirSet.Clear();
mFileList = new FileList
{
CurVersion = PublishTarget.Current.ClientVersion.ToProtoVersion()
};
mFileId = 0;
mCoders.Clear();
mProtoCoders.Clear();
if (PublishTarget.Current.IsCompress)
{
mCoders.Add(new LZMAEncoder(null));
LZMADecoder decoder=new LZMADecoder(null);
mProtoCoders.Add(decoder.CoderInfo);
}
if (PublishTarget.Current.IsEncrypt)
{
const string key = "{803CE8F2-8C0E-4159-96CB-921D89C08E13}{2519C077-1247-4AF5-8C71-C7367A481C2D}{975C6505-5494-4A36-9AD6-B4890B0E2F79}{B0DC6B72-83CC-4E81-8566-AD3AC306FE3A}{4B75FE65-1ADC-47AC-890A-293AD2A1968D}";
var bytes = Encoding.UTF8.GetBytes(key);
var keyBytes=BaseCoder.ByteArrayToString(bytes);
mCoders.Add(new XOREncoder(bytes));
XORDecoder decoder = new XORDecoder(null);
mProtoCoders.Add(decoder.CoderInfo);
}
mProtoCoders.Reverse();
}
public uint AddFile(FileListFile file)
{
if (mItemDict.ContainsKey(file))
{
Logger.LogErrorLine("\tDuplicate File name: {0}\tVS\t{1}", file.FileInfo.Name,
mItemDict[file]);
return uint.MaxValue;
}
if (string.IsNullOrEmpty(file.FileInfo.Name))
{
Logger.LogErrorLine("Empty file item path:{0}", file);
return uint.MaxValue;
}
string dirName = file.FileInfo.DirectoryName + Path.AltDirectorySeparatorChar;
dirName = dirName.Replace(PathManager.InputPath.FullName, string.Empty);
//dirName = dirName.Replace(PathManager.OutputResPath.FullName, string.Empty);
dirName = dirName.Replace(PathManager.OutputPath.FullName, string.Empty);
dirName = dirName.TrimStart(new[] { '\\', '/' });
dirName = dirName.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
int dirIndex = -1;
if (!string.IsNullOrEmpty(dirName))
{
if (!mDirSet.Contains(dirName))
{
mDirSet.Add(dirName);
mFileList.Dirs.Add(dirName);
dirIndex = mFileList.Dirs.Count - 1;
}
else
{
dirIndex = mDirSet.TakeWhile(dir => dir != dirName).Count();
}
}
//if (file.IsCoded)
//{
// file.IsCoded = file.FileInfo.Length > 1024 * 50; //50K
//}
if (file.IsCoded)
{
CodeFile(file.FileInfo,file.Md5);
file.UpdateFileInfo(file.FileInfo);
}
if (PublishTarget.Current.IsGuidName)
{
file.MakeGuidName();
}
var item = new FileList.FileItem
{
FileId = mFileId++,
DirIndex = dirIndex,
Name = file.FileInfo.Name,
MD5 = file.Md5
};
if (file.IsCoded)
{
item.Coders.AddRange(mProtoCoders);
}
if (file.OriginalFileInfo!=null)
{
item.OriginalName = file.OriginalFileInfo.Name;
}
mFileList.Files.Add(item);
return item.FileId;
}
public string GetFileName(uint fileId)
{
var fileItem= mFileList.Files.FirstOrDefault(file => file.FileId == fileId);
if (fileItem!=null)
{
return mFileList.Dirs[fileItem.DirIndex] + fileItem.Name;
}
return string.Empty;
}
public void PrintDirectory(string prefix)
{
Logger.LogInfoLine("{0}{1}", prefix, "FileList Dirs:");
string newPrefix = prefix + "\t";
int index = 0;
foreach (var dir in mFileList.Dirs)
{
Logger.LogInfoLine("{0}[{1}]\t{2}", newPrefix, index++, dir);
}
Logger.LogInfoLine("{0}{1}", prefix, "FileList Files:");
foreach (var fileItem in mFileList.Files)
{
Logger.LogInfoLine("{0}[{1}]\t{2}\t({3})\t{4}", newPrefix, fileItem.DirIndex, fileItem.Name, fileItem.FileId, fileItem.MD5);
}
}
public List<string> GetDirectories(string path)
{
var result = new Stack<string>();
path = path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
return path.Split(new[] { Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
public MemoryStream Code(Stream ms)
{
var buffer = new byte[ms.Length];
ms.Read(buffer, 0, (int)ms.Length);
if (mCoders.Count != 0)
{
buffer = mCoders.Aggregate(buffer, (current, coder) => coder.Code(current));
}
return new MemoryStream(buffer);
}
public void CodeFile(FileInfo info,string md5)
{
if (PublishTarget.Current.IsCacheEnabled && !string.IsNullOrEmpty(md5) && FileCacheCenter.IsInCache(info,md5, FileCacheOperation.Encoded))
{
var cacheInfo = FileCacheCenter.GetCacheFileInfo(info,md5, FileCacheOperation.Encoded);
cacheInfo.CopyTo(info.FullName, true);
}
else
{
MemoryStream ms;
using (var tempFile = info.OpenRead())
{
ms = Code(tempFile);
}
StreamWriter sw = new StreamWriter(info.FullName);
ms.CopyTo(sw.BaseStream);
sw.Close();
if (PublishTarget.Current.IsCacheEnabled)
{
FileCacheCenter.AddToCache(md5, info,FileCacheOperation.Encoded);
}
}
}
public void Save()
{
//add resource map to file system also
using (var file = File.Open(PathManager.OutputFileListPath.FullName, FileMode.Create, FileAccess.ReadWrite))
{
Serializer.Serialize(file, mFileList);
}
CodeFile(PathManager.OutputFileListPath,string.Empty);
Logger.LogAllLine("Generate:\t{0}", PathManager.OutputFileListPath.FullName);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkWatchersOperations operations.
/// </summary>
public partial interface INetworkWatchersOperations
{
/// <summary>
/// Creates or updates a network watcher in the specified resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the network watcher resource.
/// </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<NetworkWatcher>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NetworkWatcher parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified network watcher by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </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<NetworkWatcher>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </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 networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network watchers by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </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<IEnumerable<NetworkWatcher>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network watchers by subscription.
/// </summary>
/// <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<IEnumerable<NetworkWatcher>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the current network topology by resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the representation of topology.
/// </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<Topology>> GetTopologyWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TopologyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify IP flow from the specified VM to a location given the
/// currently configured NSG rules.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </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<VerificationIPFlowResult>> VerifyIPFlowWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </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<NextHopResult>> GetNextHopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the configured and effective security group rules on the
/// specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityGroupViewResult>> GetVMSecurityRulesWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </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<TroubleshootingResult>> GetTroubleshootingWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the last completed troubleshooting result on a specified
/// resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting
/// result.
/// </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<TroubleshootingResult>> GetTroubleshootingResultWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </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<FlowLogInformation>> SetFlowLogConfigurationWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </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<FlowLogInformation>> GetFlowLogStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verifies the possibility of establishing a direct TCP connection
/// from a virtual machine to a given endpoint including another VM or
/// an arbitrary remote server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that determine how the connectivity check will be
/// performed.
/// </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<ConnectivityInformation>> CheckConnectivityWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </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 networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify IP flow from the specified VM to a location given the
/// currently configured NSG rules.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </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<VerificationIPFlowResult>> BeginVerifyIPFlowWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </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<NextHopResult>> BeginGetNextHopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, NextHopParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the configured and effective security group rules on the
/// specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SecurityGroupViewResult>> BeginGetVMSecurityRulesWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </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<TroubleshootingResult>> BeginGetTroubleshootingWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the last completed troubleshooting result on a specified
/// resource
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting
/// result.
/// </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<TroubleshootingResult>> BeginGetTroubleshootingResultWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </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<FlowLogInformation>> BeginSetFlowLogConfigurationWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </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<FlowLogInformation>> BeginGetFlowLogStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verifies the possibility of establishing a direct TCP connection
/// from a virtual machine to a given endpoint including another VM or
/// an arbitrary remote server.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that determine how the connectivity check will be
/// performed.
/// </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<ConnectivityInformation>> BeginCheckConnectivityWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, ConnectivityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Marten.Storage;
using Marten.Util;
using Npgsql;
namespace Marten.Schema
{
public sealed class DatabaseGenerator: IDatabaseCreationExpressions, IDatabaseGenerator
{
private string _maintenanceDbConnectionString;
private readonly Dictionary<string, TenantDatabaseCreationExpressions> _configurationPerTenant = new Dictionary<string, TenantDatabaseCreationExpressions>();
public IDatabaseCreationExpressions MaintenanceDatabase(string maintenanceDbConnectionString)
{
_maintenanceDbConnectionString = maintenanceDbConnectionString ?? throw new ArgumentNullException(nameof(maintenanceDbConnectionString));
return this;
}
public ITenantDatabaseCreationExpressions ForTenant(string tenantId = Tenancy.DefaultTenantId)
{
var configurator = new TenantDatabaseCreationExpressions();
_configurationPerTenant.Add(tenantId, configurator);
return configurator;
}
private sealed class TenantDatabaseCreationExpressions: ITenantDatabaseCreationExpressions
{
private readonly StringBuilder _createOptions = new StringBuilder();
public bool DropExistingDatabase { get; private set; }
public bool CheckAgainstCatalog { get; private set; }
public bool KillConnections { get; private set; }
public Action<NpgsqlConnection> OnDbCreated { get; private set; }
public bool CreatePLV8Extension { get; private set; }
public ITenantDatabaseCreationExpressions DropExisting(bool killConnections = false)
{
DropExistingDatabase = true;
KillConnections = killConnections;
return this;
}
public ITenantDatabaseCreationExpressions WithEncoding(string encoding)
{
_createOptions.Append($" ENCODING = '{encoding}'");
return this;
}
public ITenantDatabaseCreationExpressions WithOwner(string owner)
{
_createOptions.Append($" OWNER = '{owner}'");
return this;
}
public ITenantDatabaseCreationExpressions ConnectionLimit(int limit)
{
_createOptions.Append($" CONNECTION LIMIT = {limit}");
return this;
}
public ITenantDatabaseCreationExpressions LcCollate(string lcCollate)
{
_createOptions.Append($" LC_COLLATE = '{lcCollate}'");
return this;
}
public ITenantDatabaseCreationExpressions LcType(string lcType)
{
_createOptions.Append($" LC_CTYPE = '{lcType}'");
return this;
}
public ITenantDatabaseCreationExpressions TableSpace(string tableSpace)
{
_createOptions.Append($" TABLESPACE = {tableSpace}");
return this;
}
public ITenantDatabaseCreationExpressions CheckAgainstPgDatabase()
{
CheckAgainstCatalog = true;
return this;
}
public ITenantDatabaseCreationExpressions OnDatabaseCreated(Action<NpgsqlConnection> onDbCreated)
{
OnDbCreated = onDbCreated;
return this;
}
public ITenantDatabaseCreationExpressions CreatePLV8()
{
CreatePLV8Extension = true;
return this;
}
public override string ToString()
{
return _createOptions.ToString();
}
}
public void CreateDatabases(ITenancy tenancy, Action<IDatabaseCreationExpressions> configure)
{
configure(this);
foreach (var tenantConfig in _configurationPerTenant)
{
var tenant = tenancy[tenantConfig.Key];
var config = tenantConfig.Value;
CreateDb(tenant, config);
if (config.CreatePLV8Extension)
{
CreatePlv8Extension(tenant);
}
}
}
private void CreateDb(ITenant tenant, TenantDatabaseCreationExpressions config)
{
string catalog;
var maintenanceDb = _maintenanceDbConnectionString;
using (var t = tenant.CreateConnection())
{
catalog = t.Database;
if (maintenanceDb == null)
{
var cstringBuilder = new NpgsqlConnectionStringBuilder(t.ConnectionString);
cstringBuilder.Database = "postgres";
maintenanceDb = cstringBuilder.ToString();
}
var noExistingDb = config.CheckAgainstCatalog
? new Func<bool>(() => IsNotInPgDatabase(catalog, maintenanceDb))
: (() => CannotConnectDueToInvalidCatalog(t));
if (noExistingDb())
{
CreateDb(catalog, config, false, maintenanceDb);
return;
}
}
if (config.DropExistingDatabase)
{
CreateDb(catalog, config, true, maintenanceDb);
}
}
private bool IsNotInPgDatabase(string catalog, string maintenanceDb)
{
using (var connection = new NpgsqlConnection(maintenanceDb))
using (var cmd = connection.CreateCommand("SELECT datname FROM pg_database where datname = @catalog"))
{
cmd.AddNamedParameter("catalog", catalog);
connection.Open();
try
{
var m = cmd.ExecuteScalar();
return m == null;
}
finally
{
connection.Close();
connection.Dispose();
}
}
}
private bool CannotConnectDueToInvalidCatalog(NpgsqlConnection t)
{
try
{
t.Open();
t.Close();
}
// INVALID CATALOG NAME (https://www.postgresql.org/docs/current/static/errcodes-appendix.html)
catch (PostgresException e) when (e.SqlState == "3D000")
{
return true;
}
return false;
}
private void CreateDb(string catalog, TenantDatabaseCreationExpressions config, bool dropExisting, string maintenanceDb)
{
var cmdText = string.Empty;
if (dropExisting)
{
if (config.KillConnections)
{
cmdText =
$"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '{catalog}' AND pid <> pg_backend_pid();";
}
cmdText += $"DROP DATABASE IF EXISTS \"{catalog}\";";
}
using (var connection = new NpgsqlConnection(maintenanceDb))
using (var cmd = connection.CreateCommand(cmdText))
{
cmd.CommandText += $"CREATE DATABASE \"{catalog}\" WITH" + config;
connection.Open();
try
{
cmd.ExecuteNonQuery();
config.OnDbCreated?.Invoke(connection);
}
finally
{
connection.Close();
connection.Dispose();
}
}
}
private static void CreatePlv8Extension(ITenant tenant)
{
using (var connection = tenant.CreateConnection())
using (var cmd = connection.CreateCommand("CREATE EXTENSION IF NOT EXISTS plv8"))
{
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Recepies.Services.Areas.HelpPage.Models;
namespace Recepies.Services.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Drawing.Text;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace System.Drawing
{
public class FontConverter : TypeConverter
{
private const string StylePrefix = "style=";
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) ? true : base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return (destinationType == typeof(string)) || (destinationType == typeof(InstanceDescriptor));
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is Font font)
{
if (destinationType == typeof(string))
{
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
ValueStringBuilder sb = new ValueStringBuilder();
sb.Append(font.Name);
sb.Append(culture.TextInfo.ListSeparator[0] + " ");
sb.Append(font.Size.ToString(culture.NumberFormat));
switch (font.Unit)
{
// MS throws ArgumentException, if unit is set
// to GraphicsUnit.Display
// Don't know what to append for GraphicsUnit.Display
case GraphicsUnit.Display:
sb.Append("display");
break;
case GraphicsUnit.Document:
sb.Append("doc");
break;
case GraphicsUnit.Point:
sb.Append("pt");
break;
case GraphicsUnit.Inch:
sb.Append("in");
break;
case GraphicsUnit.Millimeter:
sb.Append("mm");
break;
case GraphicsUnit.Pixel:
sb.Append("px");
break;
case GraphicsUnit.World:
sb.Append("world");
break;
}
if (font.Style != FontStyle.Regular)
{
sb.Append(culture.TextInfo.ListSeparator[0] + " style=");
sb.Append(font.Style.ToString());
}
return sb.ToString();
}
if (destinationType == typeof(InstanceDescriptor))
{
ConstructorInfo met = typeof(Font).GetTypeInfo().GetConstructor(new Type[] { typeof(string), typeof(float), typeof(FontStyle), typeof(GraphicsUnit) });
object[] args = new object[4];
args[0] = font.Name;
args[1] = font.Size;
args[2] = font.Style;
args[3] = font.Unit;
return new InstanceDescriptor(met, args);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (!(value is string font))
{
return base.ConvertFrom(context, culture, value);
}
font = font.Trim();
// Expected string format: "name[, size[, units[, style=style1[, style2[...]]]]]"
// Example using 'vi-VN' culture: "Microsoft Sans Serif, 8,25pt, style=Italic, Bold"
if (font.Length == 0)
{
return null;
}
if (culture == null)
{
culture = CultureInfo.CurrentCulture;
}
char separator = culture.TextInfo.ListSeparator[0]; // For vi-VN: ','
string fontName = font; // start with the assumption that only the font name was provided.
string style = null;
string sizeStr = null;
float fontSize = 8.25f;
FontStyle fontStyle = FontStyle.Regular;
GraphicsUnit units = GraphicsUnit.Point;
// Get the index of the first separator (would indicate the end of the name in the string).
int nameIndex = font.IndexOf(separator);
if (nameIndex < 0)
{
return new Font(fontName, fontSize, fontStyle, units);
}
// Some parameters are provided in addition to name.
fontName = font.Substring(0, nameIndex);
if (nameIndex < font.Length - 1)
{
// Get the style index (if any). The size is a bit problematic because it can be formatted differently
// depending on the culture, we'll parse it last.
int styleIndex = culture.CompareInfo.IndexOf(font, StylePrefix, CompareOptions.IgnoreCase);
if (styleIndex != -1)
{
// style found.
style = font.Substring(styleIndex, font.Length - styleIndex);
// Get the mid-substring containing the size information.
sizeStr = font.Substring(nameIndex + 1, styleIndex - nameIndex - 1);
}
else
{
// no style.
sizeStr = font.Substring(nameIndex + 1);
}
// Parse size.
(string size, string unit) unitTokens = ParseSizeTokens(sizeStr, separator);
if (unitTokens.size != null)
{
try
{
fontSize = (float)TypeDescriptor.GetConverter(typeof(float)).ConvertFromString(context, culture, unitTokens.size);
}
catch
{
// Exception from converter is too generic.
throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, font, $"name{separator} size[units[{separator} style=style1[{separator} style2{separator} ...]]]"), nameof(sizeStr));
}
}
if (unitTokens.unit != null)
{
// ParseGraphicsUnits throws an ArgumentException if format is invalid.
units = ParseGraphicsUnits(unitTokens.unit);
}
if (style != null)
{
// Parse FontStyle
style = style.Substring(6); // style string always starts with style=
string[] styleTokens = style.Split(separator);
for (int tokenCount = 0; tokenCount < styleTokens.Length; tokenCount++)
{
string styleText = styleTokens[tokenCount];
styleText = styleText.Trim();
fontStyle |= (FontStyle)Enum.Parse(typeof(FontStyle), styleText, true);
// Enum.IsDefined doesn't do what we want on flags enums...
FontStyle validBits = FontStyle.Regular | FontStyle.Bold | FontStyle.Italic | FontStyle.Underline | FontStyle.Strikeout;
if ((fontStyle | validBits) != validBits)
{
throw new InvalidEnumArgumentException(nameof(style), (int)fontStyle, typeof(FontStyle));
}
}
}
}
return new Font(fontName, fontSize, fontStyle, units);
}
private (string, string) ParseSizeTokens(string text, char separator)
{
string size = null;
string units = null;
text = text.Trim();
int length = text.Length;
int splitPoint;
if (length > 0)
{
// text is expected to have a format like " 8,25pt, ". Leading and trailing spaces (trimmed above),
// last comma, unit and decimal value may not appear. We need to make it ####.##CC
for (splitPoint = 0; splitPoint < length; splitPoint++)
{
if (char.IsLetter(text[splitPoint]))
{
break;
}
}
char[] trimChars = new char[] { separator, ' ' };
if (splitPoint > 0)
{
size = text.Substring(0, splitPoint);
// Trimming spaces between size and units.
size = size.Trim(trimChars);
}
if (splitPoint < length)
{
units = text.Substring(splitPoint);
units = units.TrimEnd(trimChars);
}
}
return (size, units);
}
private GraphicsUnit ParseGraphicsUnits(string units) =>
units switch
{
"display" => GraphicsUnit.Display,
"doc" => GraphicsUnit.Document,
"pt" => GraphicsUnit.Point,
"in" => GraphicsUnit.Inch,
"mm" => GraphicsUnit.Millimeter,
"px" => GraphicsUnit.Pixel,
"world" => GraphicsUnit.World,
_ => throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, units), nameof(units)),
};
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
object value;
byte charSet = 1;
float size = 8;
string name = null;
bool vertical = false;
FontStyle style = FontStyle.Regular;
FontFamily fontFamily = null;
GraphicsUnit unit = GraphicsUnit.Point;
if ((value = propertyValues["GdiCharSet"]) != null)
charSet = (byte)value;
if ((value = propertyValues["Size"]) != null)
size = (float)value;
if ((value = propertyValues["Unit"]) != null)
unit = (GraphicsUnit)value;
if ((value = propertyValues["Name"]) != null)
name = (string)value;
if ((value = propertyValues["GdiVerticalFont"]) != null)
vertical = (bool)value;
if ((value = propertyValues["Bold"]) != null)
{
if ((bool)value == true)
style |= FontStyle.Bold;
}
if ((value = propertyValues["Italic"]) != null)
{
if ((bool)value == true)
style |= FontStyle.Italic;
}
if ((value = propertyValues["Strikeout"]) != null)
{
if ((bool)value == true)
style |= FontStyle.Strikeout;
}
if ((value = propertyValues["Underline"]) != null)
{
if ((bool)value == true)
style |= FontStyle.Underline;
}
if (name == null)
{
fontFamily = new FontFamily("Tahoma");
}
else
{
FontCollection collection = new InstalledFontCollection();
FontFamily[] installedFontList = collection.Families;
foreach (FontFamily font in installedFontList)
{
if (name.Equals(font.Name, StringComparison.OrdinalIgnoreCase))
{
fontFamily = font;
break;
}
}
// font family not found in installed fonts
if (fontFamily == null)
{
collection = new PrivateFontCollection();
FontFamily[] privateFontList = collection.Families;
foreach (FontFamily font in privateFontList)
{
if (name.Equals(font.Name, StringComparison.OrdinalIgnoreCase))
{
fontFamily = font;
break;
}
}
}
// font family not found in private fonts also
if (fontFamily == null)
fontFamily = FontFamily.GenericSansSerif;
}
return new Font(fontFamily, size, style, unit, charSet, vertical);
}
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) => true;
public override PropertyDescriptorCollection GetProperties(
ITypeDescriptorContext context,
object value,
Attribute[] attributes)
{
return value is Font ? TypeDescriptor.GetProperties(value, attributes) : base.GetProperties(context, value, attributes);
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context) => true;
public sealed class FontNameConverter : TypeConverter, IDisposable
{
private readonly FontFamily[] _fonts;
public FontNameConverter()
{
_fonts = FontFamily.Families;
}
void IDisposable.Dispose()
{
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) ? true : base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value is string strValue ? MatchFontName(strValue, context) : base.ConvertFrom(context, culture, value);
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
string[] values = new string[_fonts.Length];
for (int i = 0; i < _fonts.Length; i++)
{
values[i] = _fonts[i].Name;
}
Array.Sort(values, Comparer.Default);
return new TypeConverter.StandardValuesCollection(values);
}
// We allow other values other than those in the font list.
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => false;
// Yes, we support picking an element from the list.
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
private string MatchFontName(string name, ITypeDescriptorContext context)
{
// Try a partial match
string bestMatch = null;
foreach (string fontName in GetStandardValues(context))
{
if (fontName.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
// For an exact match, return immediately
return fontName;
}
if (fontName.StartsWith(name, StringComparison.InvariantCultureIgnoreCase))
{
if (bestMatch == null || fontName.Length <= bestMatch.Length)
{
bestMatch = fontName;
}
}
}
// No match... fall back on whatever was provided
return bestMatch ?? name;
}
}
public class FontUnitConverter : EnumConverter
{
public FontUnitConverter() : base(typeof(GraphicsUnit)) { }
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
// display graphic unit is not supported.
if (Values == null)
{
base.GetStandardValues(context); // sets "values"
ArrayList filteredValues = new ArrayList(Values);
filteredValues.Remove(GraphicsUnit.Display);
Values = new StandardValuesCollection(filteredValues);
}
return Values;
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A high school.
/// </summary>
public class HighSchool_Core : TypeCore, IEducationalOrganization
{
public HighSchool_Core()
{
this._TypeId = 125;
this._Id = "HighSchool";
this._Schema_Org_Url = "http://schema.org/HighSchool";
string label = "";
GetLabel(out label, "HighSchool", typeof(HighSchool_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,88};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{88};
this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196,13};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// Alumni of educational organization.
/// </summary>
private Alumni_Core alumni;
public Alumni_Core Alumni
{
get
{
return alumni;
}
set
{
alumni = value;
SetPropertyInstance(alumni);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.QTKit;
using System.IO;
using MonoMac.CoreImage;
using System.Text;
namespace QTRecorder
{
public partial class QTRDocument : MonoMac.AppKit.NSDocument
{
QTCaptureSession session;
QTCaptureDeviceInput videoDeviceInput, audioDeviceInput;
QTCaptureMovieFileOutput movieFileOutput;
QTCaptureAudioPreviewOutput audioPreviewOutput;
public QTRDocument ()
{
}
[Export("initWithCoder:")]
public QTRDocument (NSCoder coder) : base(coder)
{
}
public override void WindowControllerDidLoadNib (NSWindowController windowController)
{
NSError error;
base.WindowControllerDidLoadNib (windowController);
// Create session
session = new QTCaptureSession ();
// Attach preview to session
captureView.CaptureSession = session;
captureView.WillDisplayImage = (view, image) => {
if (videoPreviewFilterDescription == null)
return image;
var selectedFilter = (NSString) videoPreviewFilterDescription [filterNameKey];
var filter = CIFilter.FromName (selectedFilter);
filter.SetDefaults ();
filter.SetValueForKey (image, CIFilterInputKey.Image);
return (CIImage) filter.ValueForKey (CIFilterOutputKey.Image);
};
// Attach outputs to session
movieFileOutput = new QTCaptureMovieFileOutput ();
movieFileOutput.WillStartRecording += delegate {
Console.WriteLine ("Will start recording");
};
movieFileOutput.DidStartRecording += delegate {
Console.WriteLine ("Started Recording");
};
movieFileOutput.ShouldChangeOutputFile = (output, url, connections, reason) => {
// Should change the file on error
Console.WriteLine (reason.LocalizedDescription);
return false;
};
movieFileOutput.MustChangeOutputFile += delegate(object sender, QTCaptureFileErrorEventArgs e) {
Console.WriteLine ("Must change file due to error");
};
// These ones we care about, some notifications
movieFileOutput.WillFinishRecording += delegate(object sender, QTCaptureFileErrorEventArgs e) {
Console.WriteLine ("Will finish recording");
InvokeOnMainThread (delegate {
WillChangeValue ("Recording");
});
};
movieFileOutput.DidFinishRecording += delegate(object sender, QTCaptureFileErrorEventArgs e) {
Console.WriteLine ("Recorded {0} bytes duration {1}", movieFileOutput.RecordedFileSize, movieFileOutput.RecordedDuration);
DidChangeValue ("Recording");
if (e.Reason != null){
NSAlert.WithError (e.Reason).BeginSheet (Window, delegate {});
return;
}
var save = NSSavePanel.SavePanel;
save.AllowedFileTypes = new string[] {"mov"};
save.CanSelectHiddenExtension = true;
save.Begin (code => {
NSError err2;
if (code == (int)NSPanelButtonType.Ok){
NSFileManager.DefaultManager.Move (e.OutputFileURL, save.Url, out err2);
} else {
NSFileManager.DefaultManager.Remove (e.OutputFileURL.Path, out err2);
}
});
};
session.AddOutput (movieFileOutput, out error);
audioPreviewOutput = new QTCaptureAudioPreviewOutput ();
session.AddOutput (audioPreviewOutput, out error);
if (VideoDevices.Length > 0)
SelectedVideoDevice = VideoDevices [0];
if (AudioDevices.Length > 0)
SelectedAudioDevice = AudioDevices [0];
session.StartRunning ();
// events: devices added/removed
AddObserver (QTCaptureDevice.WasConnectedNotification, DevicesDidChange);
AddObserver (QTCaptureDevice.WasDisconnectedNotification, DevicesDidChange);
// events: connection format changes
AddObserver (QTCaptureConnection.FormatDescriptionDidChangeNotification, FormatDidChange);
AddObserver (QTCaptureConnection.FormatDescriptionWillChangeNotification, FormatWillChange);
AddObserver (QTCaptureDevice.AttributeDidChangeNotification, AttributeDidChange);
AddObserver (QTCaptureDevice.AttributeWillChangeNotification, AttributeWillChange);
}
List<NSObject> notifications = new List<NSObject> ();
void AddObserver (NSString key, Action<NSNotification> notification)
{
notifications.Add (NSNotificationCenter.DefaultCenter.AddObserver (key, notification));
}
NSWindow Window {
get {
return WindowControllers [0].Window;
}
}
protected override void Dispose (bool disposing)
{
if (disposing){
NSNotificationCenter.DefaultCenter.RemoveObservers (notifications);
notifications = null;
}
base.Dispose (disposing);
}
//
// Save support:
// Override one of GetAsData, GetAsFileWrapper, or WriteToUrl.
//
// This method should store the contents of the document using the given typeName
// on the return NSData value.
public override NSData GetAsData (string documentType, out NSError outError)
{
outError = NSError.FromDomain (NSError.OsStatusErrorDomain, -4);
return null;
}
//
// Load support:
// Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl
//
public override bool ReadFromData (NSData data, string typeName, out NSError outError)
{
outError = NSError.FromDomain (NSError.OsStatusErrorDomain, -4);
return false;
}
// Not available until we bind CIFilter
string [] filterNames = new string [] {
"CIKaleidoscope", "CIGaussianBlur", "CIZoomBlur",
"CIColorInvert", "CISepiaTone", "CIBumpDistortion",
"CICircularWrap", "CIHoleDistortion", "CITorusLensDistortion",
"CITwirlDistortion", "CIVortexDistortion", "CICMYKHalftone",
"CIColorPosterize", "CIDotScreen", "CIHatchedScreen",
"CIBloom", "CICrystallize", "CIEdges",
"CIEdgeWork", "CIGloom", "CIPixellate",
};
static NSString filterNameKey = new NSString ("filterName");
static NSString localizedFilterKey = new NSString ("localizedName");
// Creates descriptions that can be accessed with Key/Values
[Export]
NSDictionary [] VideoPreviewFilterDescriptions {
get {
return (from name in filterNames
select NSDictionary.FromObjectsAndKeys (
new NSObject [] { new NSString (name), new NSString (CIFilter.FilterLocalizedName (name)) },
new NSObject [] { filterNameKey, localizedFilterKey })).ToArray ();
}
}
NSDictionary videoPreviewFilterDescription;
[Export]
NSDictionary VideoPreviewFilterDescription {
get {
return videoPreviewFilterDescription;
}
set {
if (value == videoPreviewFilterDescription)
return;
videoPreviewFilterDescription = value;
captureView.NeedsDisplay = true;
}
}
QTCaptureDevice [] videoDevices, audioDevices;
void RefreshDevices ()
{
WillChangeValue ("VideoDevices");
videoDevices = QTCaptureDevice.GetInputDevices (QTMediaType.Video).Concat (QTCaptureDevice.GetInputDevices (QTMediaType.Muxed)).ToArray ();
DidChangeValue ("VideoDevices");
WillChangeValue ("AudioDevices");
audioDevices = QTCaptureDevice.GetInputDevices (QTMediaType.Sound);
DidChangeValue ("AudioDevices");
if (!videoDevices.Contains (SelectedVideoDevice))
SelectedVideoDevice = null;
if (!audioDevices.Contains (SelectedAudioDevice))
SelectedAudioDevice = null;
}
void DevicesDidChange (NSNotification notification)
{
RefreshDevices ();
}
//
// Binding support
//
[Export]
public QTCaptureAudioPreviewOutput AudioPreviewOutput {
get {
return audioPreviewOutput;
}
}
[Export]
public QTCaptureDevice [] VideoDevices {
get {
if (videoDevices == null)
RefreshDevices ();
return videoDevices;
}
set {
videoDevices = value;
}
}
[Export]
public QTCaptureDevice SelectedVideoDevice {
get {
return videoDeviceInput == null ? null : videoDeviceInput.Device;
}
set {
if (videoDeviceInput != null){
session.RemoveInput (videoDeviceInput);
videoDeviceInput.Device.Close ();
videoDeviceInput.Dispose ();
videoDeviceInput = null;
}
if (value != null){
NSError err;
if (!value.Open (out err)){
NSAlert.WithError (err).BeginSheet (Window, delegate {});
return;
}
videoDeviceInput = new QTCaptureDeviceInput (value);
if (!session.AddInput (videoDeviceInput, out err)){
NSAlert.WithError (err).BeginSheet (Window, delegate {});
videoDeviceInput.Dispose ();
videoDeviceInput = null;
value.Close ();
return;
}
}
// If the video device provides audio, do not use a new audio device
if (SelectedVideoDeviceProvidesAudio)
SelectedAudioDevice = null;
}
}
[Export]
public QTCaptureDevice [] AudioDevices {
get {
if (audioDevices == null)
RefreshDevices ();
return audioDevices;
}
}
[Export]
public QTCaptureDevice SelectedAudioDevice {
get {
if (audioDeviceInput == null)
return null;
return audioDeviceInput.Device;
}
set {
if (audioDeviceInput != null){
session.RemoveInput (audioDeviceInput);
audioDeviceInput.Device.Close ();
audioDeviceInput.Dispose ();
audioDeviceInput = null;
}
if (value == null || SelectedVideoDeviceProvidesAudio)
return;
NSError err;
// try to open
if (!value.Open (out err)){
NSAlert.WithError (err).BeginSheet (Window, delegate {});
return;
}
audioDeviceInput = new QTCaptureDeviceInput (value);
if (session.AddInput (audioDeviceInput, out err))
return;
NSAlert.WithError (err).BeginSheet (Window, delegate {});
audioDeviceInput.Dispose ();
audioDeviceInput = null;
value.Close ();
}
}
[Export]
public string MediaFormatSummary {
get {
var sb = new StringBuilder ();
if (videoDeviceInput != null)
foreach (var c in videoDeviceInput.Connections)
sb.AppendFormat ("{0}\n", c.FormatDescription.LocalizedFormatSummary);
if (audioDeviceInput != null)
foreach (var c in videoDeviceInput.Connections)
sb.AppendFormat ("{0}\n", c.FormatDescription.LocalizedFormatSummary);
return sb.ToString ();
}
}
bool SelectedVideoDeviceProvidesAudio {
get {
var x = SelectedVideoDevice;
if (x == null)
return false;
return x.HasMediaType (QTMediaType.Muxed) || x.HasMediaType (QTMediaType.Sound);
}
}
[Export]
public bool HasRecordingDevice {
get {
return videoDeviceInput != null || audioDeviceInput != null;
}
}
[Export]
public bool Recording {
get {
if (movieFileOutput == null) return false;
return movieFileOutput.OutputFileUrl != null;
}
set {
if (value == Recording)
return;
if (value){
movieFileOutput.RecordToOutputFile (NSUrl.FromFilename (Path.GetTempFileName () + ".mov"));
Path.GetTempPath ();
} else {
movieFileOutput.RecordToOutputFile (null);
}
}
}
// UI controls
[Export]
public QTCaptureDevice ControllableDevice {
get {
if (SelectedVideoDevice == null)
return null;
if (SelectedVideoDevice.AvcTransportControl == null)
return null;
if (SelectedVideoDevice.IsAvcTransportControlReadOnly)
return null;
return SelectedVideoDevice;
}
}
[Export]
public bool DevicePlaying {
get {
var device = ControllableDevice;
if (device == null)
return false;
var controls = device.AvcTransportControl;
if (controls == null)
return false;
return controls.Speed == QTCaptureDeviceControlsSpeed.NormalForward && controls.PlaybackMode == QTCaptureDevicePlaybackMode.Playing;
}
set {
var device = ControllableDevice;
if (device == null)
return;
device.AvcTransportControl = new QTCaptureDeviceTransportControl () {
Speed = value ? QTCaptureDeviceControlsSpeed.NormalForward : QTCaptureDeviceControlsSpeed.Stopped,
PlaybackMode = QTCaptureDevicePlaybackMode.Playing
};
}
}
partial void StopDevice (NSObject sender)
{
var device = ControllableDevice;
if (device == null)
return;
device.AvcTransportControl = new QTCaptureDeviceTransportControl () {
Speed = QTCaptureDeviceControlsSpeed.Stopped,
PlaybackMode = QTCaptureDevicePlaybackMode.NotPlaying
};
}
bool GetDeviceSpeed (Func<QTCaptureDeviceControlsSpeed?,bool> g)
{
var device = ControllableDevice;
if (device == null)
return false;
var control = device.AvcTransportControl;
if (control == null)
return false;
return g (control.Speed);
}
void SetDeviceSpeed (bool value, QTCaptureDeviceControlsSpeed speed)
{
var device = ControllableDevice;
if (device == null)
return;
var control = device.AvcTransportControl;
if (control == null)
return;
control.Speed = value ? speed : QTCaptureDeviceControlsSpeed.Stopped;
device.AvcTransportControl = control;
}
[Export]
public bool DeviceRewinding {
get {
return GetDeviceSpeed (x => x < QTCaptureDeviceControlsSpeed.Stopped);
}
set {
SetDeviceSpeed (value, QTCaptureDeviceControlsSpeed.FastReverse);
}
}
[Export]
public bool DeviceFastForwarding {
get {
return GetDeviceSpeed (x => x > QTCaptureDeviceControlsSpeed.Stopped);
}
set {
SetDeviceSpeed (value, QTCaptureDeviceControlsSpeed.FastForward);
}
}
// Link any co-dependent keys
[Export]
public static NSSet keyPathsForValuesAffectingHasRecordingDevice ()
{
// With MonoMac 0.4:
return new NSSet (new string [] {"SelectedVideoDevice", "SelectedAudioDevice" });
// With the new MonoMac:
//return new NSSet ("SelectedVideoDevice", "SelectedAudioDevice");
}
[Export]
public static NSSet keyPathsForValuesAffectingControllableDevice ()
{
// With MonoMac 0.4:
return new NSSet (new string [] { "SelectedVideoDevice" });
// With the new MonoMac:
//return new NSSet ("SelectedVideoDevice");
}
[Export]
public static NSSet keyPathsForValuesAffectingSelectedVideoDeviceProvidesAudio ()
{
// With MonoMac 0.4:
return new NSSet (new string [] { "SelectedVideoDevice" });
// With the new MonoMac:
//return new NSSet ("SelectedVideoDevice");
}
//
// Notifications
//
void AttributeWillChange (NSNotification n)
{
}
void AttributeDidChange (NSNotification n)
{
}
void FormatWillChange (NSNotification n)
{
var owner = ((QTCaptureConnection)n.Object).Owner;
Console.WriteLine (owner);
if (owner == videoDeviceInput || owner == audioDeviceInput)
WillChangeValue ("mediaFormatSummary");
}
void FormatDidChange (NSNotification n)
{
var owner = ((QTCaptureConnection)n.Object).Owner;
Console.WriteLine (owner);
if (owner == videoDeviceInput || owner == audioDeviceInput)
DidChangeValue ("mediaFormatSummary");
}
public override string WindowNibName {
get {
return "QTRDocument";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Xml.XPath;
namespace System.Xml.Xsl.XsltOld
{
internal enum VariableType
{
GlobalVariable,
GlobalParameter,
LocalVariable,
LocalParameter,
WithParameter,
}
internal class VariableAction : ContainerAction, IXsltContextVariable
{
public static object BeingComputedMark = new object();
private const int ValueCalculated = 2;
protected XmlQualifiedName name;
protected string nameStr;
protected string baseUri;
protected int selectKey = Compiler.InvalidQueryKey;
protected int stylesheetid;
protected VariableType varType;
private int _varKey;
internal int Stylesheetid
{
get { return this.stylesheetid; }
}
internal XmlQualifiedName Name
{
get { return this.name; }
}
internal string NameStr
{
get { return this.nameStr; }
}
internal VariableType VarType
{
get { return this.varType; }
}
internal int VarKey
{
get { return _varKey; }
}
internal bool IsGlobal
{
get { return this.varType == VariableType.GlobalVariable || this.varType == VariableType.GlobalParameter; }
}
internal VariableAction(VariableType type)
{
this.varType = type;
}
internal override void Compile(Compiler compiler)
{
this.stylesheetid = compiler.Stylesheetid;
this.baseUri = compiler.Input.BaseURI;
CompileAttributes(compiler);
CheckRequiredAttribute(compiler, this.name, "name");
if (compiler.Recurse())
{
CompileTemplate(compiler);
compiler.ToParent();
if (this.selectKey != Compiler.InvalidQueryKey && this.containedActions != null)
{
throw XsltException.Create(SR.Xslt_VariableCntSel2, this.nameStr);
}
}
if (this.containedActions != null)
{
baseUri = baseUri + '#' + compiler.GetUnicRtfId();
}
else
{
baseUri = null;
}
_varKey = compiler.InsertVariable(this);
}
internal override bool CompileAttribute(Compiler compiler)
{
string name = compiler.Input.LocalName;
string value = compiler.Input.Value;
if (Ref.Equal(name, compiler.Atoms.Name))
{
Debug.Assert(this.name == null && this.nameStr == null);
this.nameStr = value;
this.name = compiler.CreateXPathQName(this.nameStr);
}
else if (Ref.Equal(name, compiler.Atoms.Select))
{
this.selectKey = compiler.AddQuery(value);
}
else
{
return false;
}
return true;
}
internal override void Execute(Processor processor, ActionFrame frame)
{
Debug.Assert(processor != null && frame != null && frame.State != ValueCalculated);
object value = null;
switch (frame.State)
{
case Initialized:
if (IsGlobal)
{
if (frame.GetVariable(_varKey) != null)
{ // This var was calculated already
frame.Finished();
break;
}
// Mark that the variable is being computed to check for circular references
frame.SetVariable(_varKey, BeingComputedMark);
}
// If this is a parameter, check whether the caller has passed the value
if (this.varType == VariableType.GlobalParameter)
{
value = processor.GetGlobalParameter(this.name);
}
else if (this.varType == VariableType.LocalParameter)
{
value = processor.GetParameter(this.name);
}
if (value != null)
{
goto case ValueCalculated;
}
// If value was not passed, check the 'select' attribute
if (this.selectKey != Compiler.InvalidQueryKey)
{
value = processor.RunQuery(frame, this.selectKey);
goto case ValueCalculated;
}
// If there is no 'select' attribute and the content is empty, use the empty string
if (this.containedActions == null)
{
value = string.Empty;
goto case ValueCalculated;
}
// RTF case
NavigatorOutput output = new NavigatorOutput(this.baseUri);
processor.PushOutput(output);
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
break;
case ProcessingChildren:
RecordOutput recOutput = processor.PopOutput();
Debug.Assert(recOutput is NavigatorOutput);
value = ((NavigatorOutput)recOutput).Navigator;
goto case ValueCalculated;
case ValueCalculated:
Debug.Assert(value != null);
frame.SetVariable(_varKey, value);
frame.Finished();
break;
default:
Debug.Fail("Invalid execution state inside VariableAction.Execute");
break;
}
}
// ---------------------- IXsltContextVariable --------------------
XPathResultType IXsltContextVariable.VariableType
{
get { return XPathResultType.Any; }
}
object IXsltContextVariable.Evaluate(XsltContext xsltContext)
{
return ((XsltCompileContext)xsltContext).EvaluateVariable(this);
}
bool IXsltContextVariable.IsLocal
{
get { return this.varType == VariableType.LocalVariable || this.varType == VariableType.LocalParameter; }
}
bool IXsltContextVariable.IsParam
{
get { return this.varType == VariableType.LocalParameter || this.varType == VariableType.GlobalParameter; }
}
}
}
| |
namespace Epi.Windows.MakeView.Dialogs
{
partial class CodesDialog : LegalValuesDialog
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CodesDialog));
this.txtTable = new System.Windows.Forms.TextBox();
this.lblTable = new System.Windows.Forms.Label();
this.lblVariable = new System.Windows.Forms.Label();
this.lblCodes = new System.Windows.Forms.Label();
this.lbxFields = new System.Windows.Forms.ListBox();
this.lblFields = new System.Windows.Forms.Label();
this.groupBoxLinkFields = new System.Windows.Forms.GroupBox();
this.btnMatchFields = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBoxLinkFields.SuspendLayout();
this.SuspendLayout();
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
//
// btnCancel
//
resources.ApplyResources(this.btnCancel, "btnCancel");
//
// btnUseExisting
//
resources.ApplyResources(this.btnUseExisting, "btnUseExisting");
//
// btnCreate
//
resources.ApplyResources(this.btnCreate, "btnCreate");
//
// btnDelete
//
resources.ApplyResources(this.btnDelete, "btnDelete");
//
// cbxSort
//
resources.ApplyResources(this.cbxSort, "cbxSort");
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
//
// btnFromExisting
//
resources.ApplyResources(this.btnFromExisting, "btnFromExisting");
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
//
// txtTable
//
resources.ApplyResources(this.txtTable, "txtTable");
this.txtTable.Name = "txtTable";
this.txtTable.ReadOnly = true;
//
// lblTable
//
this.lblTable.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblTable, "lblTable");
this.lblTable.Name = "lblTable";
//
// lblVariable
//
this.lblVariable.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblVariable, "lblVariable");
this.lblVariable.Name = "lblVariable";
//
// lblCodes
//
this.lblCodes.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblCodes, "lblCodes");
this.lblCodes.Name = "lblCodes";
//
// lbxFields
//
resources.ApplyResources(this.lbxFields, "lbxFields");
this.lbxFields.Name = "lbxFields";
this.lbxFields.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
//
// lblFields
//
this.lblFields.FlatStyle = System.Windows.Forms.FlatStyle.System;
resources.ApplyResources(this.lblFields, "lblFields");
this.lblFields.Name = "lblFields";
//
// groupBoxLinkFields
//
resources.ApplyResources(this.groupBoxLinkFields, "groupBoxLinkFields");
this.groupBoxLinkFields.Controls.Add(this.btnMatchFields);
this.groupBoxLinkFields.Name = "groupBoxLinkFields";
this.groupBoxLinkFields.TabStop = false;
//
// btnMatchFields
//
resources.ApplyResources(this.btnMatchFields, "btnMatchFields");
this.btnMatchFields.Name = "btnMatchFields";
this.btnMatchFields.UseVisualStyleBackColor = true;
this.btnMatchFields.Click += new System.EventHandler(this.btnMatchFields_Click);
//
// CodesDialog
//
resources.ApplyResources(this, "$this");
this.Controls.Add(this.groupBoxLinkFields);
this.Controls.Add(this.lblFields);
this.Controls.Add(this.lbxFields);
this.Controls.Add(this.txtTable);
this.Controls.Add(this.lblTable);
this.Controls.Add(this.lblVariable);
this.Controls.Add(this.lblCodes);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Name = "CodesDialog";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.Controls.SetChildIndex(this.lblCodes, 0);
this.Controls.SetChildIndex(this.lblVariable, 0);
this.Controls.SetChildIndex(this.lblTable, 0);
this.Controls.SetChildIndex(this.txtTable, 0);
this.Controls.SetChildIndex(this.lbxFields, 0);
this.Controls.SetChildIndex(this.btnOK, 0);
this.Controls.SetChildIndex(this.btnCancel, 0);
this.Controls.SetChildIndex(this.lblFields, 0);
this.Controls.SetChildIndex(this.groupBoxLinkFields, 0);
this.Controls.SetChildIndex(this.groupBox1, 0);
this.groupBox1.ResumeLayout(false);
this.groupBoxLinkFields.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtTable;
private System.Windows.Forms.Label lblTable;
private System.Windows.Forms.Label lblCodes;
private System.Windows.Forms.Label lblVariable;
private System.Windows.Forms.ListBox lbxFields;
private System.Windows.Forms.Label lblFields;
private System.Windows.Forms.GroupBox groupBoxLinkFields;
private System.Windows.Forms.Button btnMatchFields;
}
}
| |
/*
* Copyright 2009 ZXing 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;
namespace ZXing
{
/// <summary>
/// This object extends LuminanceSource around an array of YUV data returned from the camera driver,
/// with the option to crop to a rectangle within the full data. This can be used to exclude
/// superfluous pixels around the perimeter and speed up decoding.
/// It works for any pixel format where the Y channel is planar and appears first, including
/// YCbCr_420_SP and YCbCr_422_SP.
/// @author dswitkin@google.com (Daniel Switkin)
/// </summary>
public sealed class PlanarYUVLuminanceSource : BaseLuminanceSource
{
private const int THUMBNAIL_SCALE_FACTOR = 2;
private readonly byte[] yuvData;
private readonly int dataWidth;
private readonly int dataHeight;
private readonly int left;
private readonly int top;
/// <summary>
/// Initializes a new instance of the <see cref="PlanarYUVLuminanceSource"/> class.
/// </summary>
/// <param name="yuvData">The yuv data.</param>
/// <param name="dataWidth">Width of the data.</param>
/// <param name="dataHeight">Height of the data.</param>
/// <param name="left">The left.</param>
/// <param name="top">The top.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="reverseHoriz">if set to <c>true</c> [reverse horiz].</param>
public PlanarYUVLuminanceSource(byte[] yuvData,
int dataWidth,
int dataHeight,
int left,
int top,
int width,
int height,
bool reverseHoriz)
: base(width, height)
{
if (left + width > dataWidth || top + height > dataHeight)
{
throw new ArgumentException("Crop rectangle does not fit within image data.");
}
this.yuvData = yuvData;
this.dataWidth = dataWidth;
this.dataHeight = dataHeight;
this.left = left;
this.top = top;
if (reverseHoriz)
{
reverseHorizontal(width, height);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="PlanarYUVLuminanceSource"/> class.
/// </summary>
/// <param name="luminances">The luminances.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
private PlanarYUVLuminanceSource(byte[] luminances, int width, int height)
: base(width, height)
{
yuvData = luminances;
this.luminances = luminances;
dataWidth = width;
dataHeight = height;
left = 0;
top = 0;
}
/// <summary>
/// Fetches one row of luminance data from the underlying platform's bitmap. Values range from
/// 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have
/// to bitwise and with 0xff for each value. It is preferable for implementations of this method
/// to only fetch this row rather than the whole image, since no 2D Readers may be installed and
/// getMatrix() may never be called.
/// </summary>
/// <param name="y">The row to fetch, 0 <= y < Height.</param>
/// <param name="row">An optional preallocated array. If null or too small, it will be ignored.
/// Always use the returned object, and ignore the .length of the array.</param>
/// <returns>
/// An array containing the luminance data.
/// </returns>
override public byte[] getRow(int y, byte[] row)
{
if (y < 0 || y >= Height)
{
throw new ArgumentException("Requested row is outside the image: " + y);
}
int width = Width;
if (row == null || row.Length < width)
{
row = new byte[width];
}
int offset = (y + top) * dataWidth + left;
Array.Copy(yuvData, offset, row, 0, width);
return row;
}
/// <summary>
///
/// </summary>
override public byte[] Matrix
{
get
{
int width = Width;
int height = Height;
// If the caller asks for the entire underlying image, save the copy and give them the
// original data. The docs specifically warn that result.length must be ignored.
if (width == dataWidth && height == dataHeight)
{
return yuvData;
}
int area = width * height;
byte[] matrix = new byte[area];
int inputOffset = top * dataWidth + left;
// If the width matches the full width of the underlying data, perform a single copy.
if (width == dataWidth)
{
Array.Copy(yuvData, inputOffset, matrix, 0, area);
return matrix;
}
// Otherwise copy one cropped row at a time.
byte[] yuv = yuvData;
for (int y = 0; y < height; y++)
{
int outputOffset = y * width;
Array.Copy(yuvData, inputOffset, matrix, outputOffset, width);
inputOffset += dataWidth;
}
return matrix;
}
}
/// <summary>
/// </summary>
/// <returns> Whether this subclass supports cropping.</returns>
override public bool CropSupported
{
get { return true; }
}
/// <summary>
/// Returns a new object with cropped image data. Implementations may keep a reference to the
/// original data rather than a copy. Only callable if CropSupported is true.
/// </summary>
/// <param name="left">The left coordinate, 0 <= left < Width.</param>
/// <param name="top">The top coordinate, 0 <= top <= Height.</param>
/// <param name="width">The width of the rectangle to crop.</param>
/// <param name="height">The height of the rectangle to crop.</param>
/// <returns>
/// A cropped version of this object.
/// </returns>
override public LuminanceSource crop(int left, int top, int width, int height)
{
return new PlanarYUVLuminanceSource(yuvData,
dataWidth,
dataHeight,
this.left + left,
this.top + top,
width,
height,
false);
}
/// <summary>
/// Renders the cropped greyscale bitmap.
/// </summary>
/// <returns></returns>
public int[] renderThumbnail()
{
int width = Width / THUMBNAIL_SCALE_FACTOR;
int height = Height / THUMBNAIL_SCALE_FACTOR;
int[] pixels = new int[width * height];
byte[] yuv = yuvData;
int inputOffset = top * dataWidth + left;
for (int y = 0; y < height; y++)
{
int outputOffset = y * width;
for (int x = 0; x < width; x++)
{
int grey = yuv[inputOffset + x * THUMBNAIL_SCALE_FACTOR] & 0xff;
pixels[outputOffset + x] = ((0x00FF0000 << 8) | (grey * 0x00010101));
}
inputOffset += dataWidth * THUMBNAIL_SCALE_FACTOR;
}
return pixels;
}
/// <summary>
/// width of image from {@link #renderThumbnail()}
/// </summary>
public int ThumbnailWidth
{
get
{
return Width / THUMBNAIL_SCALE_FACTOR;
}
}
/// <summary>
/// height of image from {@link #renderThumbnail()}
/// </summary>
public int ThumbnailHeight
{
get
{
return Height / THUMBNAIL_SCALE_FACTOR;
}
}
private void reverseHorizontal(int width, int height)
{
byte[] yuvData = this.yuvData;
for (int y = 0, rowStart = top * dataWidth + left; y < height; y++, rowStart += dataWidth)
{
int middle = rowStart + width / 2;
for (int x1 = rowStart, x2 = rowStart + width - 1; x1 < middle; x1++, x2--)
{
byte temp = yuvData[x1];
yuvData[x1] = yuvData[x2];
yuvData[x2] = temp;
}
}
}
/// <summary>
/// creates a new instance
/// </summary>
/// <param name="newLuminances"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
protected override LuminanceSource CreateLuminanceSource(byte[] newLuminances, int width, int height)
{
return new PlanarYUVLuminanceSource(newLuminances, width, height);
}
}
}
| |
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RedditSharp.Things
{
public class RedditUser : Thing
{
private const string OverviewUrl = "/user/{0}.json";
private const string CommentsUrl = "/user/{0}/comments.json";
private const string LinksUrl = "/user/{0}/submitted.json";
private const string SubscribedSubredditsUrl = "/subreddits/mine.json";
private const string LikedUrl = "/user/{0}/liked.json";
private const string DislikedUrl = "/user/{0}/disliked.json";
private const string SavedUrl = "/user/{0}/saved.json";
private const int MAX_LIMIT = 100;
public async Task<RedditUser> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent)
{
CommonInit(reddit, json, webAgent);
await JsonConvert.PopulateObjectAsync(json["name"] == null ? json["data"].ToString() : json.ToString(), this,
reddit.JsonSerializerSettings);
return this;
}
public RedditUser Init(Reddit reddit, JToken json, IWebAgent webAgent)
{
CommonInit(reddit, json, webAgent);
JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this,
reddit.JsonSerializerSettings);
return this;
}
private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent)
{
base.Init(json);
Reddit = reddit;
WebAgent = webAgent;
}
[JsonIgnore]
protected Reddit Reddit { get; set; }
[JsonIgnore]
protected IWebAgent WebAgent { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("is_gold")]
public bool HasGold { get; set; }
[JsonProperty("is_mod")]
public bool IsModerator { get; set; }
[JsonProperty("link_karma")]
public int LinkKarma { get; set; }
[JsonProperty("comment_karma")]
public int CommentKarma { get; set; }
[JsonProperty("created")]
[JsonConverter(typeof(UnixTimestampConverter))]
public DateTime Created { get; set; }
public Listing<VotableThing> Overview
{
get
{
return new Listing<VotableThing>(Reddit, string.Format(OverviewUrl, Name), WebAgent);
}
}
public Listing<Post> LikedPosts
{
get
{
return new Listing<Post>(Reddit, string.Format(LikedUrl, Name), WebAgent);
}
}
public Listing<Post> DislikedPosts
{
get
{
return new Listing<Post>(Reddit, string.Format(DislikedUrl, Name), WebAgent);
}
}
public Listing<Comment> Comments
{
get
{
return new Listing<Comment>(Reddit, string.Format(CommentsUrl, Name), WebAgent);
}
}
public Listing<Post> Posts
{
get
{
return new Listing<Post>(Reddit, string.Format(LinksUrl, Name), WebAgent);
}
}
public Listing<Subreddit> SubscribedSubreddits
{
get
{
return new Listing<Subreddit>(Reddit, SubscribedSubredditsUrl, WebAgent);
}
}
/// <summary>
/// Get a listing of comments and posts from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/>
/// and limited to <paramref name="limit"/>.
/// </summary>
/// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param>
/// <param name="limit">How many comments to fetch per request. Max is 100.</param>
/// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param>
/// <returns>The listing of comments requested.</returns>
public Listing<VotableThing> GetOverview(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All)
{
if ((limit < 1) || (limit > MAX_LIMIT))
throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]");
string overviewUrl = string.Format(OverviewUrl, Name);
overviewUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime));
return new Listing<VotableThing>(Reddit, overviewUrl, WebAgent);
}
/// <summary>
/// Get a listing of comments from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/>
/// and limited to <paramref name="limit"/>.
/// </summary>
/// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param>
/// <param name="limit">How many comments to fetch per request. Max is 100.</param>
/// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param>
/// <returns>The listing of comments requested.</returns>
public Listing<Comment> GetComments(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All)
{
if ((limit < 1) || (limit > MAX_LIMIT))
throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]");
string commentsUrl = string.Format(CommentsUrl, Name);
commentsUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime));
return new Listing<Comment>(Reddit, commentsUrl, WebAgent);
}
/// <summary>
/// Get a listing of posts from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/>
/// and limited to <paramref name="limit"/>.
/// </summary>
/// <param name="sorting">How to sort the posts (hot, new, top, controversial).</param>
/// <param name="limit">How many posts to fetch per request. Max is 100.</param>
/// <param name="fromTime">What time frame of posts to show (hour, day, week, month, year, all).</param>
/// <returns>The listing of posts requested.</returns>
public Listing<Post> GetPosts(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All)
{
if ((limit < 1) || (limit > 100))
throw new ArgumentOutOfRangeException("limit", "Valid range: [1,100]");
string linksUrl = string.Format(LinksUrl, Name);
linksUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime));
return new Listing<Post>(Reddit, linksUrl, WebAgent);
}
/// <summary>
/// Get a listing of comments and posts saved by the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/>
/// and limited to <paramref name="limit"/>.
/// </summary>
/// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param>
/// <param name="limit">How many comments to fetch per request. Max is 100.</param>
/// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param>
/// <returns>The listing of posts and/or comments requested that the user saved.</returns>
public Listing<VotableThing> GetSaved(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All)
{
if ((limit < 1) || (limit > MAX_LIMIT))
throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]");
string savedUrl = string.Format(SavedUrl, Name);
savedUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime));
return new Listing<VotableThing>(Reddit, savedUrl, WebAgent);
}
public override string ToString()
{
return Name;
}
#region Obsolete Getter Methods
[Obsolete("Use Overview property instead")]
public Listing<VotableThing> GetOverview()
{
return Overview;
}
[Obsolete("Use Comments property instead")]
public Listing<Comment> GetComments()
{
return Comments;
}
[Obsolete("Use Posts property instead")]
public Listing<Post> GetPosts()
{
return Posts;
}
[Obsolete("Use SubscribedSubreddits property instead")]
public Listing<Subreddit> GetSubscribedSubreddits()
{
return SubscribedSubreddits;
}
#endregion Obsolete Getter Methods
}
public enum Sort
{
New,
Hot,
Top,
Controversial
}
public enum FromTime
{
All,
Year,
Month,
Week,
Day,
Hour
}
}
| |
//
// Mono.System.Xml.XmlNodeReaderImpl.cs - implements the core part of XmlNodeReader
//
// Author:
// Atsushi Enomoto (atsushi@ximian.com)
//
// (C) 2004 Novell Inc.
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// This serves the implementation part of XmlNodeReader except for
// ResolveEntity().
//
using System;
#if NET_2_0
using System.Collections.Generic;
#endif
using Mono.System.Xml;
using System.Text;
using Mono.Xml;
#if NET_2_0
using Mono.System.Xml.Schema;
#endif
namespace Mono.System.Xml
{
#if NET_2_0
internal class XmlNodeReaderImpl : XmlReader, IHasXmlParserContext, IXmlNamespaceResolver
#else
internal class XmlNodeReaderImpl : XmlReader, IHasXmlParserContext
#endif
{
XmlDocument document;
XmlNode startNode;
XmlNode current;
XmlNode ownerLinkedNode;
ReadState state = ReadState.Initial;
int depth;
bool isEndElement;
bool ignoreStartNode;
#region Constructor
internal XmlNodeReaderImpl (XmlNodeReaderImpl entityContainer)
: this (entityContainer.current)
{
}
public XmlNodeReaderImpl (XmlNode node)
{
startNode = node;
depth = 0;
document = startNode.NodeType == XmlNodeType.Document ?
startNode as XmlDocument : startNode.OwnerDocument;
switch (node.NodeType) {
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
case XmlNodeType.EntityReference:
ignoreStartNode = true;
break;
}
}
#endregion
#region Properties
public override int AttributeCount {
get {
if (state != ReadState.Interactive)
return 0;
if (isEndElement || current == null)
return 0;
XmlNode n = ownerLinkedNode;
return n.Attributes != null ? n.Attributes.Count : 0;
}
}
public override string BaseURI {
get {
if (current == null)
return startNode.BaseURI;
return current.BaseURI;
}
}
#if NET_2_0
public override bool CanReadBinaryContent {
get { return true; }
}
public override bool CanReadValueChunk {
get { return true; }
}
#else
internal override bool CanReadBinaryContent {
get { return true; }
}
internal override bool CanReadValueChunk {
get { return true; }
}
#endif
public override bool CanResolveEntity {
get { return false; }
}
public override int Depth {
get {
return current == null ? 0 :
current == ownerLinkedNode ? depth :
current.NodeType == XmlNodeType.Attribute ? depth + 1 :
depth + 2;
}
}
public override bool EOF {
get { return state == ReadState.EndOfFile || state == ReadState.Error; }
}
public override bool HasAttributes {
get {
if (isEndElement || current == null)
return false;
// MS BUG: inconsistent return value between XmlTextReader and XmlNodeReader.
// As for attribute and its descendants, XmlReader returns element's HasAttributes.
XmlNode n = ownerLinkedNode;
if (n.Attributes == null ||
n.Attributes.Count == 0)
return false;
else
return true;
}
}
public override bool HasValue {
get {
if (current == null)
return false;
switch (current.NodeType) {
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
case XmlNodeType.Notation:
case XmlNodeType.EndElement:
case XmlNodeType.EndEntity:
return false;
default:
return true;
}
}
}
public override bool IsDefault {
get {
if (current == null)
return false;
if (current.NodeType != XmlNodeType.Attribute)
return false;
else
{
return !((XmlAttribute) current).Specified;
}
}
}
public override bool IsEmptyElement {
get {
if (current == null)
return false;
if(current.NodeType == XmlNodeType.Element)
return ((XmlElement) current).IsEmpty;
else
return false;
}
}
#if NET_2_0
#else
public override string this [int i] {
get { return GetAttribute (i); }
}
public override string this [string name] {
get { return GetAttribute (name); }
}
public override string this [string name, string namespaceURI] {
get { return GetAttribute (name, namespaceURI); }
}
#endif
public override string LocalName {
get {
if (current == null)
return String.Empty;
switch (current.NodeType) {
case XmlNodeType.Attribute:
case XmlNodeType.DocumentType:
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.XmlDeclaration:
return current.LocalName;
}
return String.Empty;
}
}
public override string Name {
get {
if (current == null)
return String.Empty;
switch (current.NodeType) {
case XmlNodeType.Attribute:
case XmlNodeType.DocumentType:
case XmlNodeType.Element:
case XmlNodeType.EntityReference:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.XmlDeclaration:
return current.Name;
}
return String.Empty;
}
}
public override string NamespaceURI {
get {
if (current == null)
return String.Empty;
return current.NamespaceURI;
}
}
public override XmlNameTable NameTable {
get { return document.NameTable; }
}
public override XmlNodeType NodeType {
get {
if (current == null)
return XmlNodeType.None;
return isEndElement ? XmlNodeType.EndElement : current.NodeType;
}
}
public override string Prefix {
get {
if (current == null)
return String.Empty;
return current.Prefix;
}
}
#if NET_2_0
#else
public override char QuoteChar {
get {
return '"';
}
}
#endif
public override ReadState ReadState {
get { return state; }
}
#if NET_2_0
public override IXmlSchemaInfo SchemaInfo {
get { return current != null ? current.SchemaInfo : null; }
}
#endif
public override string Value {
get {
if (NodeType == XmlNodeType.DocumentType)
return ((XmlDocumentType) current).InternalSubset;
else
return HasValue ? current.Value : String.Empty;
}
}
public override string XmlLang {
get {
if (current == null)
return startNode.XmlLang;
return current.XmlLang;
}
}
public override XmlSpace XmlSpace {
get {
if (current == null)
return startNode.XmlSpace;
return current.XmlSpace;
}
}
#endregion
#region Methods
public override void Close ()
{
current = null;
state = ReadState.Closed;
}
public override string GetAttribute (int attributeIndex)
{
if (NodeType == XmlNodeType.XmlDeclaration) {
XmlDeclaration decl = current as XmlDeclaration;
if (attributeIndex == 0)
return decl.Version;
else if (attributeIndex == 1) {
if (decl.Encoding != String.Empty)
return decl.Encoding;
else if (decl.Standalone != String.Empty)
return decl.Standalone;
}
else if (attributeIndex == 2 &&
decl.Encoding != String.Empty && decl.Standalone != null)
return decl.Standalone;
throw new ArgumentOutOfRangeException ("Index out of range.");
} else if (NodeType == XmlNodeType.DocumentType) {
XmlDocumentType doctype = current as XmlDocumentType;
if (attributeIndex == 0) {
if (doctype.PublicId != "")
return doctype.PublicId;
else if (doctype.SystemId != "")
return doctype.SystemId;
} else if (attributeIndex == 1)
if (doctype.PublicId == "" && doctype.SystemId != "")
return doctype.SystemId;
throw new ArgumentOutOfRangeException ("Index out of range.");
}
// This is MS.NET bug which returns attributes in spite of EndElement.
if (isEndElement || current == null)
return null;
if (attributeIndex < 0 || attributeIndex > AttributeCount)
throw new ArgumentOutOfRangeException ("Index out of range.");
return ownerLinkedNode.Attributes [attributeIndex].Value;
}
public override string GetAttribute (string name)
{
// This is MS.NET bug which returns attributes in spite of EndElement.
if (isEndElement || current == null)
return null;
if (NodeType == XmlNodeType.XmlDeclaration)
return GetXmlDeclarationAttribute (name);
else if (NodeType == XmlNodeType.DocumentType)
return GetDocumentTypeAttribute (name);
if (ownerLinkedNode.Attributes == null)
return null;
XmlAttribute attr = ownerLinkedNode.Attributes [name];
if (attr == null)
return null;
else
return attr.Value;
}
public override string GetAttribute (string name, string namespaceURI)
{
// This is MS.NET bug which returns attributes in spite of EndElement.
if (isEndElement || current == null)
return null;
if (NodeType == XmlNodeType.XmlDeclaration)
return GetXmlDeclarationAttribute (name);
else if (NodeType == XmlNodeType.DocumentType)
return GetDocumentTypeAttribute (name);
if (ownerLinkedNode.Attributes == null)
return null;
XmlAttribute attr = ownerLinkedNode.Attributes [name, namespaceURI];
if (attr == null)
return null; // In fact MS.NET returns null instead of String.Empty.
else
return attr.Value;
}
private string GetXmlDeclarationAttribute (string name)
{
XmlDeclaration decl = current as XmlDeclaration;
switch (name) {
case "version":
return decl.Version;
case "encoding":
// This is MS.NET bug that XmlNodeReturns in case of string.empty.
return decl.Encoding != String.Empty ? decl.Encoding : null;
case "standalone":
return decl.Standalone;
}
return null;
}
private string GetDocumentTypeAttribute (string name)
{
XmlDocumentType doctype = current as XmlDocumentType;
switch (name) {
case "PUBLIC":
return doctype.PublicId;
case "SYSTEM":
return doctype.SystemId;
}
return null;
}
XmlParserContext IHasXmlParserContext.ParserContext {
get {
return new XmlParserContext (document.NameTable,
current == null ?
new XmlNamespaceManager (document.NameTable) :
current.ConstructNamespaceManager (),
document.DocumentType != null ? document.DocumentType.DTD : null,
current == null ? document.BaseURI : current.BaseURI,
XmlLang, XmlSpace, Encoding.Unicode);
}
}
#if NET_2_0
public IDictionary<string, string> GetNamespacesInScope (XmlNamespaceScope scope)
{
IDictionary<string, string> table = new Dictionary<string, string> ();
XmlNode n = current ?? startNode;
do {
if (n.NodeType == XmlNodeType.Document)
break;
for (int i = 0; i < n.Attributes.Count; i++) {
XmlAttribute a = n.Attributes [i];
if (a.NamespaceURI == XmlNamespaceManager.XmlnsXmlns) {
string key = a.Prefix == XmlNamespaceManager.PrefixXmlns ? a.LocalName : String.Empty;
if (!table.ContainsKey (key))
table.Add (key, a.Value);
}
}
if (scope == XmlNamespaceScope.Local)
return table;
n = n.ParentNode;
} while (n != null);
if (scope == XmlNamespaceScope.All)
table.Add (XmlNamespaceManager.PrefixXml, XmlNamespaceManager.XmlnsXml);
return table;
}
#endif
private XmlElement GetCurrentElement ()
{
XmlElement el = null;
switch (current.NodeType) {
case XmlNodeType.Attribute:
el = ((XmlAttribute) current).OwnerElement;
break;
case XmlNodeType.Element:
el = (XmlElement) current;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.EntityReference:
case XmlNodeType.Comment:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
case XmlNodeType.ProcessingInstruction:
el = current.ParentNode as XmlElement;
break;
}
return el;
}
public override string LookupNamespace (string prefix)
{
if (current == null)
return null;
XmlElement el = GetCurrentElement ();
for (; el != null; el = el.ParentNode as XmlElement) {
for (int i = 0; i < el.Attributes.Count; i++) {
XmlAttribute attr = el.Attributes [i];
if (attr.NamespaceURI != XmlNamespaceManager.XmlnsXmlns)
continue;
if (prefix == "") {
if (attr.Prefix == "")
return attr.Value;
}
else if (attr.LocalName == prefix)
return attr.Value;
continue;
}
}
switch (prefix) {
case XmlNamespaceManager.PrefixXml:
return XmlNamespaceManager.XmlnsXml;
case XmlNamespaceManager.PrefixXmlns:
return XmlNamespaceManager.XmlnsXmlns;
}
return null;
}
#if NET_2_0
public string LookupPrefix (string ns)
{
return LookupPrefix (ns, false);
}
public string LookupPrefix (string ns, bool atomizedNames)
{
if (current == null)
return null;
XmlElement el = GetCurrentElement ();
for (; el != null; el = el.ParentNode as XmlElement) {
for (int i = 0; i < el.Attributes.Count; i++) {
XmlAttribute attr = el.Attributes [i];
if (atomizedNames) {
if (!Object.ReferenceEquals (attr.NamespaceURI, XmlNamespaceManager.XmlnsXmlns))
continue;
if (Object.ReferenceEquals (attr.Value, ns))
// xmlns:blah="..." -> LocalName, xmlns="..." -> String.Empty
return attr.Prefix != String.Empty ? attr.LocalName : String.Empty;
} else {
if (attr.NamespaceURI != XmlNamespaceManager.XmlnsXmlns)
continue;
if (attr.Value == ns)
// xmlns:blah="..." -> LocalName, xmlns="..." -> String.Empty
return attr.Prefix != String.Empty ? attr.LocalName : String.Empty;
}
}
}
switch (ns) {
case XmlNamespaceManager.XmlnsXml:
return XmlNamespaceManager.PrefixXml;
case XmlNamespaceManager.XmlnsXmlns:
return XmlNamespaceManager.PrefixXmlns;
}
return null;
}
#endif
public override void MoveToAttribute (int attributeIndex)
{
if (isEndElement || attributeIndex < 0 || attributeIndex > AttributeCount)
throw new ArgumentOutOfRangeException ();
state = ReadState.Interactive;
current = ownerLinkedNode.Attributes [attributeIndex];
}
public override bool MoveToAttribute (string name)
{
if (isEndElement || current == null)
return false;
XmlNode tmpCurrent = current;
if (current.ParentNode.NodeType == XmlNodeType.Attribute)
current = current.ParentNode;
if (ownerLinkedNode.Attributes == null)
return false;
XmlAttribute attr = ownerLinkedNode.Attributes [name];
if (attr == null) {
current = tmpCurrent;
return false;
}
else {
current = attr;
return true;
}
}
public override bool MoveToAttribute (string name, string namespaceURI)
{
if (isEndElement || current == null)
return false;
if (ownerLinkedNode.Attributes == null)
return false;
XmlAttribute attr = ownerLinkedNode.Attributes [name, namespaceURI];
if (attr == null)
return false;
else {
current = attr;
return true;
}
}
public override bool MoveToElement ()
{
if (current == null)
return false;
XmlNode n = ownerLinkedNode;
if (current != n) {
current = n;
return true;
} else
return false;
}
public override bool MoveToFirstAttribute ()
{
if (current == null)
return false;
if (ownerLinkedNode.Attributes == null)
return false;
if(ownerLinkedNode.Attributes.Count > 0)
{
current = ownerLinkedNode.Attributes [0];
return true;
}
else
return false;
}
public override bool MoveToNextAttribute ()
{
if (current == null)
return false;
XmlNode anode = current;
if (current.NodeType != XmlNodeType.Attribute) {
// then it's either an attribute child or anything on the tree.
if (current.ParentNode == null || // document, or non-tree node
current.ParentNode.NodeType != XmlNodeType.Attribute) // not an attr value
return MoveToFirstAttribute ();
anode = current.ParentNode;
}
{
XmlAttributeCollection ac = ((XmlAttribute) anode).OwnerElement.Attributes;
for (int i=0; i<ac.Count-1; i++)
{
XmlAttribute attr = ac [i];
if (attr == anode)
{
i++;
if (i == ac.Count)
return false;
current = ac [i];
return true;
}
}
return false;
}
}
public override bool Read ()
{
// FIXME: at some stage inlining might work effectively.
// if (EOF)
switch (state) {
case ReadState.EndOfFile:
case ReadState.Error:
case ReadState.Closed:
return false;
}
#if NET_2_0
if (Binary != null)
Binary.Reset ();
#endif
bool ret = ReadContent ();
ownerLinkedNode = current;
return ret;
}
bool ReadContent ()
{
if (ReadState == ReadState.Initial) {
current = startNode;
state = ReadState.Interactive;
// when startNode is document or fragment
if (ignoreStartNode)
current = startNode.FirstChild;
if (current == null) {
state = ReadState.Error;
return false;
} else
return true;
}
MoveToElement ();
// don't step into EntityReference's children. Also
// avoid re-entering children of already-consumed
// element (i.e. when it is regarded as EndElement).
XmlNode firstChild =
!isEndElement && current.NodeType != XmlNodeType.EntityReference ?
current.FirstChild : null;
if (firstChild != null) {
isEndElement = false;
current = firstChild;
depth++;
return true;
}
if (current == startNode) { // Currently it is on the start node.
if (IsEmptyElement || isEndElement) {
// The start node is already consumed.
isEndElement = false;
current = null;
state = ReadState.EndOfFile;
return false;
} else {
// The start node is the only element
// which should be processed. Now it
// is set as EndElement.
isEndElement = true;
return true;
}
}
if (!isEndElement && !IsEmptyElement &&
current.NodeType == XmlNodeType.Element) {
// element, currently not EndElement, and has
// no child. (such as <foo></foo>, which
// should become EndElement).
isEndElement = true;
return true;
}
// If NextSibling is available, move to there.
XmlNode next = current.NextSibling;
if (next != null) {
isEndElement = false;
current = next;
return true;
}
// Otherwise, parent.
XmlNode parent = current.ParentNode;
if (parent == null || parent == startNode && ignoreStartNode) {
// Parent is not available, or reached to
// the start node. This reader never sets
// startNode as current if it was originally
// ignored (e.g. startNode is XmlDocument).
isEndElement = false;
current = null;
state = ReadState.EndOfFile;
return false;
} else {
// Parent was available, so return it as
// EndElement.
current = parent;
depth--;
isEndElement = true;
return true;
}
}
public override bool ReadAttributeValue ()
{
if (current.NodeType == XmlNodeType.Attribute) {
if (current.FirstChild == null)
return false;
current = current.FirstChild;
return true;
} else if (current.ParentNode.NodeType == XmlNodeType.Attribute) {
if (current.NextSibling == null)
return false;
current = current.NextSibling;
return true;
} else
return false;
}
public override string ReadString ()
{
return base.ReadString ();
}
public override void ResolveEntity ()
{
throw new NotSupportedException ("Should not happen.");
}
public override void Skip ()
{
// Why is this overriden? Such skipping might raise
// (or ignore) unexpected validation error.
base.Skip ();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Platform;
namespace Avalonia.Threading
{
/// <summary>
/// A main loop in a <see cref="Dispatcher"/>.
/// </summary>
internal class JobRunner
{
private IPlatformThreadingInterface? _platform;
private readonly Queue<IJob>[] _queues = Enumerable.Range(0, (int) DispatcherPriority.MaxValue + 1)
.Select(_ => new Queue<IJob>()).ToArray();
public JobRunner(IPlatformThreadingInterface? platform)
{
_platform = platform;
}
/// <summary>
/// Runs continuations pushed on the loop.
/// </summary>
/// <param name="priority">Priority to execute jobs for. Pass null if platform doesn't have internal priority system</param>
public void RunJobs(DispatcherPriority? priority)
{
var minimumPriority = priority ?? DispatcherPriority.MinValue;
while (true)
{
var job = GetNextJob(minimumPriority);
if (job == null)
return;
job.Run();
}
}
/// <summary>
/// Invokes a method on the main loop.
/// </summary>
/// <param name="action">The method.</param>
/// <param name="priority">The priority with which to invoke the method.</param>
/// <returns>A task that can be used to track the method's execution.</returns>
public Task InvokeAsync(Action action, DispatcherPriority priority)
{
var job = new Job(action, priority, false);
AddJob(job);
return job.Task!;
}
/// <summary>
/// Invokes a method on the main loop.
/// </summary>
/// <param name="function">The method.</param>
/// <param name="priority">The priority with which to invoke the method.</param>
/// <returns>A task that can be used to track the method's execution.</returns>
public Task<TResult> InvokeAsync<TResult>(Func<TResult> function, DispatcherPriority priority)
{
var job = new Job<TResult>(function, priority);
AddJob(job);
return job.Task;
}
/// <summary>
/// Post action that will be invoked on main thread
/// </summary>
/// <param name="action">The method.</param>
///
/// <param name="priority">The priority with which to invoke the method.</param>
internal void Post(Action action, DispatcherPriority priority)
{
AddJob(new Job(action, priority, true));
}
/// <summary>
/// Allows unit tests to change the platform threading interface.
/// </summary>
internal void UpdateServices()
{
_platform = AvaloniaLocator.Current.GetService<IPlatformThreadingInterface>();
}
private void AddJob(IJob job)
{
bool needWake;
var queue = _queues[(int) job.Priority];
lock (queue)
{
needWake = queue.Count == 0;
queue.Enqueue(job);
}
if (needWake)
_platform?.Signal(job.Priority);
}
private IJob? GetNextJob(DispatcherPriority minimumPriority)
{
for (int c = (int) DispatcherPriority.MaxValue; c >= (int) minimumPriority; c--)
{
var q = _queues[c];
lock (q)
{
if (q.Count > 0)
return q.Dequeue();
}
}
return null;
}
private interface IJob
{
/// <summary>
/// Gets the job priority.
/// </summary>
DispatcherPriority Priority { get; }
/// <summary>
/// Runs the job.
/// </summary>
void Run();
}
/// <summary>
/// A job to run.
/// </summary>
private sealed class Job : IJob
{
/// <summary>
/// The method to call.
/// </summary>
private readonly Action _action;
/// <summary>
/// The task completion source.
/// </summary>
private readonly TaskCompletionSource<object?>? _taskCompletionSource;
/// <summary>
/// Initializes a new instance of the <see cref="Job"/> class.
/// </summary>
/// <param name="action">The method to call.</param>
/// <param name="priority">The job priority.</param>
/// <param name="throwOnUiThread">Do not wrap exception in TaskCompletionSource</param>
public Job(Action action, DispatcherPriority priority, bool throwOnUiThread)
{
_action = action;
Priority = priority;
_taskCompletionSource = throwOnUiThread ? null : new TaskCompletionSource<object?>();
}
/// <inheritdoc/>
public DispatcherPriority Priority { get; }
/// <summary>
/// The task.
/// </summary>
public Task? Task => _taskCompletionSource?.Task;
/// <inheritdoc/>
void IJob.Run()
{
if (_taskCompletionSource == null)
{
_action();
return;
}
try
{
_action();
_taskCompletionSource.SetResult(null);
}
catch (Exception e)
{
_taskCompletionSource.SetException(e);
}
}
}
/// <summary>
/// A job to run.
/// </summary>
private sealed class Job<TResult> : IJob
{
private readonly Func<TResult> _function;
private readonly TaskCompletionSource<TResult> _taskCompletionSource;
/// <summary>
/// Initializes a new instance of the <see cref="Job"/> class.
/// </summary>
/// <param name="function">The method to call.</param>
/// <param name="priority">The job priority.</param>
public Job(Func<TResult> function, DispatcherPriority priority)
{
_function = function;
Priority = priority;
_taskCompletionSource = new TaskCompletionSource<TResult>();
}
/// <inheritdoc/>
public DispatcherPriority Priority { get; }
/// <summary>
/// The task.
/// </summary>
public Task<TResult> Task => _taskCompletionSource.Task;
/// <inheritdoc/>
void IJob.Run()
{
try
{
var result = _function();
_taskCompletionSource.SetResult(result);
}
catch (Exception e)
{
_taskCompletionSource.SetException(e);
}
}
}
}
}
| |
// 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.
// File System.Windows.Interop.HwndSourceParameters.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Interop
{
public partial struct HwndSourceParameters
{
#region Methods and constructors
public static bool operator != (System.Windows.Interop.HwndSourceParameters a, System.Windows.Interop.HwndSourceParameters b)
{
return default(bool);
}
public static bool operator == (System.Windows.Interop.HwndSourceParameters a, System.Windows.Interop.HwndSourceParameters b)
{
return default(bool);
}
public bool Equals(System.Windows.Interop.HwndSourceParameters obj)
{
return default(bool);
}
public override bool Equals(Object obj)
{
return default(bool);
}
public override int GetHashCode()
{
return default(int);
}
public HwndSourceParameters(string name)
{
}
public HwndSourceParameters(string name, int width, int height)
{
}
public void SetPosition(int x, int y)
{
}
public void SetSize(int width, int height)
{
}
#endregion
#region Properties and indexers
public bool AcquireHwndFocusInMenuMode
{
get
{
return default(bool);
}
set
{
}
}
public bool AdjustSizingForNonClientArea
{
get
{
return default(bool);
}
set
{
}
}
public int ExtendedWindowStyle
{
get
{
return default(int);
}
set
{
}
}
public bool HasAssignedSize
{
get
{
return default(bool);
}
}
public int Height
{
get
{
return default(int);
}
set
{
}
}
public HwndSourceHook HwndSourceHook
{
get
{
return default(HwndSourceHook);
}
set
{
}
}
public IntPtr ParentWindow
{
get
{
return default(IntPtr);
}
set
{
}
}
public int PositionX
{
get
{
return default(int);
}
set
{
}
}
public int PositionY
{
get
{
return default(int);
}
set
{
}
}
public System.Windows.Input.RestoreFocusMode RestoreFocusMode
{
get
{
return default(System.Windows.Input.RestoreFocusMode);
}
set
{
}
}
public bool UsesPerPixelOpacity
{
get
{
return default(bool);
}
set
{
}
}
public int Width
{
get
{
return default(int);
}
set
{
}
}
public int WindowClassStyle
{
get
{
return default(int);
}
set
{
}
}
public string WindowName
{
get
{
return default(string);
}
set
{
}
}
public int WindowStyle
{
get
{
return default(int);
}
set
{
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using Avalonia.Platform;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.Mathematics.Interop;
using DWrite = SharpDX.DirectWrite;
namespace Avalonia.Direct2D1
{
public static class PrimitiveExtensions
{
/// <summary>
/// The value for which all absolute numbers smaller than are considered equal to zero.
/// </summary>
public const float ZeroTolerance = 1e-6f; // Value a 8x higher than 1.19209290E-07F
public static readonly RawRectangleF RectangleInfinite;
/// <summary>
/// Gets the identity matrix.
/// </summary>
/// <value>The identity matrix.</value>
public readonly static RawMatrix3x2 Matrix3x2Identity = new RawMatrix3x2 { M11 = 1, M12 = 0, M21 = 0, M22 = 1, M31 = 0, M32 = 0 };
static PrimitiveExtensions()
{
RectangleInfinite = new RawRectangleF
{
Left = float.NegativeInfinity,
Top = float.NegativeInfinity,
Right = float.PositiveInfinity,
Bottom = float.PositiveInfinity
};
}
public static Rect ToAvalonia(this RawRectangleF r)
{
return new Rect(new Point(r.Left, r.Top), new Point(r.Right, r.Bottom));
}
public static PixelSize ToAvalonia(this Size2 p) => new PixelSize(p.Width, p.Height);
public static Vector ToAvaloniaVector(this Size2F p) => new Vector(p.Width, p.Height);
public static RawRectangleF ToSharpDX(this Rect r)
{
return new RawRectangleF((float)r.X, (float)r.Y, (float)r.Right, (float)r.Bottom);
}
public static RawVector2 ToSharpDX(this Point p)
{
return new RawVector2 { X = (float)p.X, Y = (float)p.Y };
}
public static Size2F ToSharpDX(this Size p)
{
return new Size2F((float)p.Width, (float)p.Height);
}
public static ExtendMode ToDirect2D(this Avalonia.Media.GradientSpreadMethod spreadMethod)
{
if (spreadMethod == Avalonia.Media.GradientSpreadMethod.Pad)
return ExtendMode.Clamp;
else if (spreadMethod == Avalonia.Media.GradientSpreadMethod.Reflect)
return ExtendMode.Mirror;
else
return ExtendMode.Wrap;
}
public static SharpDX.Direct2D1.LineJoin ToDirect2D(this Avalonia.Media.PenLineJoin lineJoin)
{
if (lineJoin == Avalonia.Media.PenLineJoin.Round)
return LineJoin.Round;
else if (lineJoin == Avalonia.Media.PenLineJoin.Miter)
return LineJoin.Miter;
else
return LineJoin.Bevel;
}
public static SharpDX.Direct2D1.CapStyle ToDirect2D(this Avalonia.Media.PenLineCap lineCap)
{
if (lineCap == Avalonia.Media.PenLineCap.Flat)
return CapStyle.Flat;
else if (lineCap == Avalonia.Media.PenLineCap.Round)
return CapStyle.Round;
else if (lineCap == Avalonia.Media.PenLineCap.Square)
return CapStyle.Square;
else
return CapStyle.Triangle;
}
public static Guid ToWic(this Platform.PixelFormat format, Platform.AlphaFormat alphaFormat)
{
bool isPremul = alphaFormat == AlphaFormat.Premul;
if (format == Platform.PixelFormat.Rgb565)
return SharpDX.WIC.PixelFormat.Format16bppBGR565;
if (format == Platform.PixelFormat.Bgra8888)
return isPremul ? SharpDX.WIC.PixelFormat.Format32bppPBGRA : SharpDX.WIC.PixelFormat.Format32bppBGRA;
if (format == Platform.PixelFormat.Rgba8888)
return isPremul ? SharpDX.WIC.PixelFormat.Format32bppPRGBA : SharpDX.WIC.PixelFormat.Format32bppRGBA;
throw new ArgumentException("Unknown pixel format");
}
/// <summary>
/// Converts a pen to a Direct2D stroke style.
/// </summary>
/// <param name="pen">The pen to convert.</param>
/// <param name="renderTarget">The render target.</param>
/// <returns>The Direct2D brush.</returns>
public static StrokeStyle ToDirect2DStrokeStyle(this Avalonia.Media.IPen pen, SharpDX.Direct2D1.RenderTarget renderTarget)
{
return pen.ToDirect2DStrokeStyle(Direct2D1Platform.Direct2D1Factory);
}
/// <summary>
/// Converts a pen to a Direct2D stroke style.
/// </summary>
/// <param name="pen">The pen to convert.</param>
/// <param name="factory">The factory associated with this resource.</param>
/// <returns>The Direct2D brush.</returns>
public static StrokeStyle ToDirect2DStrokeStyle(this Avalonia.Media.IPen pen, Factory factory)
{
var d2dLineCap = pen.LineCap.ToDirect2D();
var properties = new StrokeStyleProperties
{
DashStyle = DashStyle.Solid,
MiterLimit = (float)pen.MiterLimit,
LineJoin = pen.LineJoin.ToDirect2D(),
StartCap = d2dLineCap,
EndCap = d2dLineCap,
DashCap = d2dLineCap
};
float[] dashes = null;
if (pen.DashStyle?.Dashes != null && pen.DashStyle.Dashes.Count > 0)
{
properties.DashStyle = DashStyle.Custom;
properties.DashOffset = (float)pen.DashStyle.Offset;
dashes = pen.DashStyle.Dashes.Select(x => (float)x).ToArray();
}
dashes = dashes ?? Array.Empty<float>();
return new StrokeStyle(factory, properties, dashes);
}
/// <summary>
/// Converts a Avalonia <see cref="Avalonia.Media.Color"/> to Direct2D.
/// </summary>
/// <param name="color">The color to convert.</param>
/// <returns>The Direct2D color.</returns>
public static RawColor4 ToDirect2D(this Avalonia.Media.Color color)
{
return new RawColor4(
(float)(color.R / 255.0),
(float)(color.G / 255.0),
(float)(color.B / 255.0),
(float)(color.A / 255.0));
}
/// <summary>
/// Converts a Avalonia <see cref="Avalonia.Matrix"/> to a Direct2D <see cref="RawMatrix3x2"/>
/// </summary>
/// <param name="matrix">The <see cref="Matrix"/>.</param>
/// <returns>The <see cref="RawMatrix3x2"/>.</returns>
public static RawMatrix3x2 ToDirect2D(this Matrix matrix)
{
return new RawMatrix3x2
{
M11 = (float)matrix.M11,
M12 = (float)matrix.M12,
M21 = (float)matrix.M21,
M22 = (float)matrix.M22,
M31 = (float)matrix.M31,
M32 = (float)matrix.M32
};
}
/// <summary>
/// Converts a Direct2D <see cref="RawMatrix3x2"/> to a Avalonia <see cref="Avalonia.Matrix"/>.
/// </summary>
/// <param name="matrix">The matrix</param>
/// <returns>a <see cref="Avalonia.Matrix"/>.</returns>
public static Matrix ToAvalonia(this RawMatrix3x2 matrix)
{
return new Matrix(
matrix.M11,
matrix.M12,
matrix.M21,
matrix.M22,
matrix.M31,
matrix.M32);
}
/// <summary>
/// Converts a Avalonia <see cref="Rect"/> to a Direct2D <see cref="RawRectangleF"/>
/// </summary>
/// <param name="rect">The <see cref="Rect"/>.</param>
/// <returns>The <see cref="RawRectangleF"/>.</returns>
public static RawRectangleF ToDirect2D(this Rect rect)
{
return new RawRectangleF(
(float)rect.X,
(float)rect.Y,
(float)rect.Right,
(float)rect.Bottom);
}
public static DWrite.TextAlignment ToDirect2D(this Avalonia.Media.TextAlignment alignment)
{
switch (alignment)
{
case Avalonia.Media.TextAlignment.Left:
return DWrite.TextAlignment.Leading;
case Avalonia.Media.TextAlignment.Center:
return DWrite.TextAlignment.Center;
case Avalonia.Media.TextAlignment.Right:
return DWrite.TextAlignment.Trailing;
default:
throw new InvalidOperationException("Invalid TextAlignment");
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Framework.Lists;
namespace osu.Game.Beatmaps.ControlPoints
{
[Serializable]
public class ControlPointInfo
{
/// <summary>
/// All control points grouped by time.
/// </summary>
[JsonProperty]
public IBindableList<ControlPointGroup> Groups => groups;
private readonly BindableList<ControlPointGroup> groups = new BindableList<ControlPointGroup>();
/// <summary>
/// All timing points.
/// </summary>
[JsonProperty]
public IReadOnlyList<TimingControlPoint> TimingPoints => timingPoints;
private readonly SortedList<TimingControlPoint> timingPoints = new SortedList<TimingControlPoint>(Comparer<TimingControlPoint>.Default);
/// <summary>
/// All difficulty points.
/// </summary>
[JsonProperty]
public IReadOnlyList<DifficultyControlPoint> DifficultyPoints => difficultyPoints;
private readonly SortedList<DifficultyControlPoint> difficultyPoints = new SortedList<DifficultyControlPoint>(Comparer<DifficultyControlPoint>.Default);
/// <summary>
/// All sound points.
/// </summary>
[JsonProperty]
public IReadOnlyList<SampleControlPoint> SamplePoints => samplePoints;
private readonly SortedList<SampleControlPoint> samplePoints = new SortedList<SampleControlPoint>(Comparer<SampleControlPoint>.Default);
/// <summary>
/// All effect points.
/// </summary>
[JsonProperty]
public IReadOnlyList<EffectControlPoint> EffectPoints => effectPoints;
private readonly SortedList<EffectControlPoint> effectPoints = new SortedList<EffectControlPoint>(Comparer<EffectControlPoint>.Default);
/// <summary>
/// All control points, of all types.
/// </summary>
public IEnumerable<ControlPoint> AllControlPoints => Groups.SelectMany(g => g.ControlPoints).ToArray();
/// <summary>
/// Finds the difficulty control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the difficulty control point at.</param>
/// <returns>The difficulty control point.</returns>
public DifficultyControlPoint DifficultyPointAt(double time) => binarySearchWithFallback(DifficultyPoints, time);
/// <summary>
/// Finds the effect control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the effect control point at.</param>
/// <returns>The effect control point.</returns>
public EffectControlPoint EffectPointAt(double time) => binarySearchWithFallback(EffectPoints, time);
/// <summary>
/// Finds the sound control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the sound control point at.</param>
/// <returns>The sound control point.</returns>
public SampleControlPoint SamplePointAt(double time) => binarySearchWithFallback(SamplePoints, time, SamplePoints.Count > 0 ? SamplePoints[0] : null);
/// <summary>
/// Finds the timing control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the timing control point at.</param>
/// <returns>The timing control point.</returns>
public TimingControlPoint TimingPointAt(double time) => binarySearchWithFallback(TimingPoints, time, TimingPoints.Count > 0 ? TimingPoints[0] : null);
/// <summary>
/// Finds the maximum BPM represented by any timing control point.
/// </summary>
[JsonIgnore]
public double BPMMaximum =>
60000 / (TimingPoints.OrderBy(c => c.BeatLength).FirstOrDefault() ?? new TimingControlPoint()).BeatLength;
/// <summary>
/// Finds the minimum BPM represented by any timing control point.
/// </summary>
[JsonIgnore]
public double BPMMinimum =>
60000 / (TimingPoints.OrderByDescending(c => c.BeatLength).FirstOrDefault() ?? new TimingControlPoint()).BeatLength;
/// <summary>
/// Finds the mode BPM (most common BPM) represented by the control points.
/// </summary>
[JsonIgnore]
public double BPMMode =>
60000 / (TimingPoints.GroupBy(c => c.BeatLength).OrderByDescending(grp => grp.Count()).FirstOrDefault()?.FirstOrDefault() ?? new TimingControlPoint()).BeatLength;
/// <summary>
/// Remove all <see cref="ControlPointGroup"/>s and return to a pristine state.
/// </summary>
public void Clear()
{
groups.Clear();
timingPoints.Clear();
difficultyPoints.Clear();
samplePoints.Clear();
effectPoints.Clear();
}
/// <summary>
/// Add a new <see cref="ControlPoint"/>. Note that the provided control point may not be added if the correct state is already present at the provided time.
/// </summary>
/// <param name="time">The time at which the control point should be added.</param>
/// <param name="controlPoint">The control point to add.</param>
/// <returns>Whether the control point was added.</returns>
public bool Add(double time, ControlPoint controlPoint)
{
if (checkAlreadyExisting(time, controlPoint))
return false;
GroupAt(time, true).Add(controlPoint);
return true;
}
public ControlPointGroup GroupAt(double time, bool addIfNotExisting = false)
{
var newGroup = new ControlPointGroup(time);
int i = groups.BinarySearch(newGroup);
if (i >= 0)
return groups[i];
if (addIfNotExisting)
{
newGroup.ItemAdded += groupItemAdded;
newGroup.ItemRemoved += groupItemRemoved;
groups.Insert(~i, newGroup);
return newGroup;
}
return null;
}
public void RemoveGroup(ControlPointGroup group)
{
group.ItemAdded -= groupItemAdded;
group.ItemRemoved -= groupItemRemoved;
groups.Remove(group);
}
/// <summary>
/// Binary searches one of the control point lists to find the active control point at <paramref name="time"/>.
/// Includes logic for returning a specific point when no matching point is found.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="time">The time to find the control point at.</param>
/// <param name="prePoint">The control point to use when <paramref name="time"/> is before any control points. If null, a new control point will be constructed.</param>
/// <returns>The active control point at <paramref name="time"/>, or a fallback <see cref="ControlPoint"/> if none found.</returns>
private T binarySearchWithFallback<T>(IReadOnlyList<T> list, double time, T prePoint = null)
where T : ControlPoint, new()
{
return binarySearch(list, time) ?? prePoint ?? new T();
}
/// <summary>
/// Binary searches one of the control point lists to find the active control point at <paramref name="time"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="time">The time to find the control point at.</param>
/// <returns>The active control point at <paramref name="time"/>.</returns>
private T binarySearch<T>(IReadOnlyList<T> list, double time)
where T : ControlPoint
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (list.Count == 0)
return null;
if (time < list[0].Time)
return null;
if (time >= list[^1].Time)
return list[^1];
int l = 0;
int r = list.Count - 2;
while (l <= r)
{
int pivot = l + ((r - l) >> 1);
if (list[pivot].Time < time)
l = pivot + 1;
else if (list[pivot].Time > time)
r = pivot - 1;
else
return list[pivot];
}
// l will be the first control point with Time > time, but we want the one before it
return list[l - 1];
}
/// <summary>
/// Check whether <paramref name="newPoint"/> should be added.
/// </summary>
/// <param name="time">The time to find the timing control point at.</param>
/// <param name="newPoint">A point to be added.</param>
/// <returns>Whether the new point should be added.</returns>
private bool checkAlreadyExisting(double time, ControlPoint newPoint)
{
ControlPoint existing = null;
switch (newPoint)
{
case TimingControlPoint _:
// Timing points are a special case and need to be added regardless of fallback availability.
existing = binarySearch(TimingPoints, time);
break;
case EffectControlPoint _:
existing = EffectPointAt(time);
break;
case SampleControlPoint _:
existing = binarySearch(SamplePoints, time);
break;
case DifficultyControlPoint _:
existing = DifficultyPointAt(time);
break;
}
return existing?.EquivalentTo(newPoint) == true;
}
private void groupItemAdded(ControlPoint controlPoint)
{
switch (controlPoint)
{
case TimingControlPoint typed:
timingPoints.Add(typed);
break;
case EffectControlPoint typed:
effectPoints.Add(typed);
break;
case SampleControlPoint typed:
samplePoints.Add(typed);
break;
case DifficultyControlPoint typed:
difficultyPoints.Add(typed);
break;
}
}
private void groupItemRemoved(ControlPoint controlPoint)
{
switch (controlPoint)
{
case TimingControlPoint typed:
timingPoints.Remove(typed);
break;
case EffectControlPoint typed:
effectPoints.Remove(typed);
break;
case SampleControlPoint typed:
samplePoints.Remove(typed);
break;
case DifficultyControlPoint typed:
difficultyPoints.Remove(typed);
break;
}
}
}
}
| |
// 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;
using System.Runtime.InteropServices;
using System.Threading;
using CFStringRef = System.IntPtr;
using FSEventStreamRef = System.IntPtr;
using size_t = System.IntPtr;
using FSEventStreamEventId = System.UInt64;
using CFRunLoopRef = System.IntPtr;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
public partial class FileSystemWatcher
{
/// <summary>Called when FileSystemWatcher is finalized.</summary>
private void FinalizeDispose()
{
// Make sure we cleanup
StopRaisingEvents();
}
private void StartRaisingEvents()
{
// Don't start another instance if one is already runnings
if (_cancellation != null)
{
return;
}
try
{
CancellationTokenSource cancellation = new CancellationTokenSource();
RunningInstance instance = new RunningInstance(this, _directory, _includeSubdirectories, TranslateFlags(_notifyFilters), cancellation.Token);
_enabled = true;
_cancellation = cancellation;
instance.Start();
}
catch
{
_enabled = false;
_cancellation = null;
throw;
}
}
private void StopRaisingEvents()
{
_enabled = false;
CancellationTokenSource token = _cancellation;
if (token != null)
{
_cancellation = null;
token.Cancel();
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private CancellationTokenSource _cancellation;
private static Interop.EventStream.FSEventStreamEventFlags TranslateFlags(NotifyFilters flagsToTranslate)
{
Interop.EventStream.FSEventStreamEventFlags flags = 0;
// Always re-create the filter flags when start is called since they could have changed
if ((flagsToTranslate & (NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size)) != 0)
{
flags = Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner;
}
if ((flagsToTranslate & NotifyFilters.Security) != 0)
{
flags |= Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod;
}
if ((flagsToTranslate & NotifyFilters.DirectoryName) != 0)
{
flags |= Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed;
}
if ((flagsToTranslate & NotifyFilters.FileName) != 0)
{
flags |= Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed;
}
return flags;
}
private sealed class RunningInstance
{
// Flags used to create the event stream
private const Interop.EventStream.FSEventStreamCreateFlags EventStreamFlags = (Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagFileEvents |
Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagNoDefer |
Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagWatchRoot);
// Weak reference to the associated watcher. A weak reference is used so that the FileSystemWatcher may be collected and finalized,
// causing an active operation to be torn down.
private readonly WeakReference<FileSystemWatcher> _weakWatcher;
// The user can input relative paths, which can muck with our path comparisons. Save off the
// actual full path so we can use it for comparing
private string _fullDirectory;
// Boolean if we allow events from nested folders
private bool _includeChildren;
// The bitmask of events that we want to send to the user
private Interop.EventStream.FSEventStreamEventFlags _filterFlags;
// The EventStream to listen for events on
private SafeEventStreamHandle _eventStream;
// A reference to the RunLoop that we can use to start or stop a Watcher
private CFRunLoopRef _watcherRunLoop;
// Callback delegate for the EventStream events
private Interop.EventStream.FSEventStreamCallback _callback;
// Token to monitor for cancellation requests, upon which processing is stopped and all
// state is cleaned up.
private readonly CancellationToken _cancellationToken;
// Calling RunLoopStop multiple times SegFaults so protect the call to it
private bool _stopping;
internal RunningInstance(
FileSystemWatcher watcher,
string directory,
bool includeChildren,
Interop.EventStream.FSEventStreamEventFlags filter,
CancellationToken cancelToken)
{
Debug.Assert(string.IsNullOrEmpty(directory) == false);
Debug.Assert(!cancelToken.IsCancellationRequested);
_weakWatcher = new WeakReference<FileSystemWatcher>(watcher);
_fullDirectory = System.IO.Path.GetFullPath(directory);
_includeChildren = includeChildren;
_filterFlags = filter;
_cancellationToken = cancelToken;
_cancellationToken.Register(obj => ((RunningInstance)obj).CancellationCallback(), this);
_stopping = false;
}
private void CancellationCallback()
{
if (!_stopping)
{
_stopping = true;
// Stop the FS event message pump
Interop.RunLoop.CFRunLoopStop(_watcherRunLoop);
}
}
internal void Start()
{
// Make sure _fullPath doesn't contain a link or alias
// since the OS will give back the actual, non link'd or alias'd paths
_fullDirectory = Interop.Sys.RealPath(_fullDirectory);
if (_fullDirectory == null)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
}
Debug.Assert(string.IsNullOrEmpty(_fullDirectory) == false, "Watch directory is null or empty");
// Normalize the _fullDirectory path to have a trailing slash
if (_fullDirectory[_fullDirectory.Length - 1] != '/')
{
_fullDirectory += "/";
}
// Get the path to watch and verify we created the CFStringRef
SafeCreateHandle path = Interop.CoreFoundation.CFStringCreateWithCString(_fullDirectory);
if (path.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
}
// Take the CFStringRef and put it into an array to pass to the EventStream
SafeCreateHandle arrPaths = Interop.CoreFoundation.CFArrayCreate(new CFStringRef[1] { path.DangerousGetHandle() }, 1);
if (arrPaths.IsInvalid)
{
path.Dispose();
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
}
// Create the callback for the EventStream if it wasn't previously created for this instance.
if (_callback == null)
{
_callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback);
}
// Make sure the OS file buffer(s) are fully flushed so we don't get events from cached I/O
Interop.Sys.Sync();
// Create the event stream for the path and tell the stream to watch for file system events.
_eventStream = Interop.EventStream.FSEventStreamCreate(
_callback,
arrPaths,
Interop.EventStream.kFSEventStreamEventIdSinceNow,
0.0f,
EventStreamFlags);
if (_eventStream.IsInvalid)
{
arrPaths.Dispose();
path.Dispose();
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true);
}
// Create and start our watcher thread then wait for the thread to initialize and start
// the RunLoop. We wait for that to prevent this function from returning before the RunLoop
// has a chance to start so that any callers won't race with the background thread's initialization
// and calling Stop, which would attempt to stop a RunLoop that hasn't started yet.
var runLoopStarted = new ManualResetEventSlim();
new Thread(WatchForFileSystemEventsThreadStart) { IsBackground = true }.Start(runLoopStarted);
runLoopStarted.Wait();
}
private void WatchForFileSystemEventsThreadStart(object arg)
{
var runLoopStarted = (ManualResetEventSlim)arg;
// Get this thread's RunLoop
_watcherRunLoop = Interop.RunLoop.CFRunLoopGetCurrent();
Debug.Assert(_watcherRunLoop != IntPtr.Zero);
// Schedule the EventStream to run on the thread's RunLoop
Interop.EventStream.FSEventStreamScheduleWithRunLoop(_eventStream, _watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode);
try
{
bool started = Interop.EventStream.FSEventStreamStart(_eventStream);
// Notify the StartRaisingEvents call that we are initialized and about to start
// so that it can return and avoid a race-condition around multiple threads calling Stop and Start
runLoopStarted.Set();
if (started)
{
// Start the OS X RunLoop (a blocking call) that will pump file system changes into the callback function
Interop.RunLoop.CFRunLoopRun();
// When we get here, we've requested to stop so cleanup the EventStream and unschedule from the RunLoop
Interop.EventStream.FSEventStreamStop(_eventStream);
}
else
{
// Try to get the Watcher to raise the error event; if we can't do that, just silently exist since the watcher is gone anyway
FileSystemWatcher watcher;
if (_weakWatcher.TryGetTarget(out watcher))
{
// An error occurred while trying to start the run loop so fail out
watcher.OnError(new ErrorEventArgs(new IOException(SR.EventStream_FailedToStart, Marshal.GetLastWin32Error())));
}
}
}
finally
{
// Always unschedule the RunLoop before cleaning up
Interop.EventStream.FSEventStreamUnscheduleFromRunLoop(_eventStream, _watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode);
}
}
private void FileSystemEventCallback(
FSEventStreamRef streamRef,
IntPtr clientCallBackInfo,
size_t numEvents,
String[] eventPaths,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
Interop.EventStream.FSEventStreamEventFlags[] eventFlags,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
FSEventStreamEventId[] eventIds)
{
Debug.Assert((numEvents.ToInt32() == eventPaths.Length) && (numEvents.ToInt32() == eventFlags.Length) && (numEvents.ToInt32() == eventIds.Length));
// Try to get the actual watcher from our weak reference. We maintain a weak reference most of the time
// so as to avoid a rooted cycle that would prevent our processing loop from ever ending
// if the watcher is dropped by the user without being disposed. If we can't get the watcher,
// there's nothing more to do (we can't raise events), so bail.
FileSystemWatcher watcher;
if (!_weakWatcher.TryGetTarget(out watcher))
{
CancellationCallback();
return;
}
// Since renames come in pairs, when we find the first we need to search for the next one. Once we find it, we'll add it to this
// list so when the for-loop comes across it, we'll skip it since it's already been processed as part of the original of the pair.
List<FSEventStreamEventId> handledRenameEvents = null;
for (long i = 0; i < numEvents.ToInt32(); i++)
{
Debug.Assert(eventPaths[i].Length > 0, "Empty events are not supported");
Debug.Assert(eventPaths[i][eventPaths[i].Length - 1] != '/', "Trailing slashes on events is not supported");
// Match Windows and don't notify us about changes to the Root folder
string path = eventPaths[i];
if (string.Compare(path, 0, _fullDirectory, 0, path.Length, StringComparison.OrdinalIgnoreCase) == 0)
{
continue;
}
WatcherChangeTypes eventType = 0;
// First, we should check if this event should kick off a re-scan since we can't really rely on anything after this point if that is true
if (ShouldRescanOccur(eventFlags[i]))
{
watcher.OnError(new ErrorEventArgs(new IOException(SR.FSW_BufferOverflow, (int)eventFlags[i])));
break;
}
else if ((handledRenameEvents != null) && (handledRenameEvents.Contains(eventIds[i])))
{
// If this event is the second in a rename pair then skip it
continue;
}
else if (CheckIfPathIsNested(path) && ((eventType = FilterEvents(eventFlags[i], path)) != 0))
{
// The base FileSystemWatcher does a match check against the relative path before combining with
// the root dir; however, null is special cased to signify the root dir, so check if we should use that.
string relativePath = null;
if (path.Equals(_fullDirectory, StringComparison.OrdinalIgnoreCase) == false)
{
// Remove the root directory to get the relative path
relativePath = path.Remove(0, _fullDirectory.Length);
}
// Raise a notification for the event
if (eventType != WatcherChangeTypes.Renamed)
{
watcher.NotifyFileSystemEventArgs(eventType, relativePath);
}
else
{
// Find the rename that is paired to this rename, which should be the next rename in the list
long pairedId = FindRenameChangePairedChange(i, eventPaths, eventFlags, eventIds);
if (pairedId == long.MinValue)
{
// Getting here means we have a rename without a pair, meaning it should be a create for the
// move from unwatched folder to watcher folder scenario or a move from the watcher folder out.
// Check if the item exists on disk to check which it is
WatcherChangeTypes wct = DoesItemExist(path, IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile)) ?
WatcherChangeTypes.Created :
WatcherChangeTypes.Deleted;
watcher.NotifyFileSystemEventArgs(wct, relativePath);
}
else
{
// Remove the base directory prefix and add the paired event to the list of
// events to skip and notify the user of the rename
string newPathRelativeName = eventPaths[pairedId].Remove(0, _fullDirectory.Length);
watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, newPathRelativeName, relativePath);
// Create a new list, if necessary, and add the event
if (handledRenameEvents == null)
{
handledRenameEvents = new List<FSEventStreamEventId>();
}
handledRenameEvents.Add(eventIds[pairedId]);
}
}
}
}
}
/// <summary>
/// Compares the given event flags to the filter flags and returns which event (if any) corresponds
/// to those flags.
/// </summary>
private WatcherChangeTypes FilterEvents(Interop.EventStream.FSEventStreamEventFlags eventFlags, string fullPath)
{
const Interop.EventStream.FSEventStreamEventFlags changedFlags = Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner |
Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod;
// If any of the Changed flags are set in both Filter and Event then a Changed event has occurred.
if (((_filterFlags & changedFlags) & (eventFlags & changedFlags)) > 0)
{
return WatcherChangeTypes.Changed;
}
// Disallow event coalescing. OSX likes to add a Created event to everything, particularly Changed events.
if ((eventFlags & changedFlags) > 0)
return 0;
// Notify created/deleted/renamed events if they pass through the filters
bool allowDirs = (_filterFlags & Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir) > 0;
bool allowFiles = (_filterFlags & Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile) > 0;
bool isDir = (eventFlags & Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir) > 0;
bool isFile = (eventFlags & Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile) > 0;
bool eventIsCorrectType = (isDir && allowDirs) || (isFile && allowFiles);
bool eventIsLink = (eventFlags & (Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsHardlink | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsLastHardlink)) > 0;
if (eventIsCorrectType || ((allowDirs || allowFiles) && (eventIsLink)))
{
// Notify Renamed events.
if (IsFlagSet(eventFlags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed))
{
return WatcherChangeTypes.Renamed;
}
else
{
// Notify Created/Deleted events.
if ((IsFlagSet(eventFlags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated)) &&
(IsFlagSet(eventFlags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved)))
{
// OS X is wonky where it can give back kFSEventStreamEventFlagItemCreated and kFSEventStreamEventFlagItemRemoved
// for the same item. The only option we have is to stat and see if the item exists; if so send created, otherwise send deleted.
WatcherChangeTypes wct = DoesItemExist(fullPath, IsFlagSet(eventFlags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile)) ?
WatcherChangeTypes.Created :
WatcherChangeTypes.Deleted;
return wct;
}
else if (IsFlagSet(eventFlags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated))
{
return WatcherChangeTypes.Created;
}
else if (IsFlagSet(eventFlags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved))
{
return WatcherChangeTypes.Deleted;
}
}
}
return 0;
}
private bool ShouldRescanOccur(Interop.EventStream.FSEventStreamEventFlags flags)
{
// Check if any bit is set that signals that the caller should rescan
return (IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagMustScanSubDirs) ||
IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagUserDropped) ||
IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagKernelDropped) ||
IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagRootChanged) ||
IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagMount) ||
IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagUnmount));
}
private bool CheckIfPathIsNested(string eventPath)
{
bool doesPathPass = true;
// If we shouldn't include subdirectories, check if this path's parent is the watch directory
if (_includeChildren == false)
{
// Check if the parent is the root. If so, then we'll continue processing based on the name.
// If it isn't, then this will be set to false and we'll skip the name processing since it's irrelevant.
string parent = System.IO.Path.GetDirectoryName(eventPath);
doesPathPass = (string.Compare(parent, 0, _fullDirectory, 0, parent.Length, StringComparison.OrdinalIgnoreCase) == 0);
}
return doesPathPass;
}
private long FindRenameChangePairedChange(
long currentIndex,
String[] eventPaths,
Interop.EventStream.FSEventStreamEventFlags[] eventFlags,
FSEventStreamEventId[] eventIds)
{
// Start at one past the current index and try to find the next Rename item, which should be the old path.
for (long i = currentIndex + 1; i < eventPaths.Length; i++)
{
if (IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed))
{
// We found match, stop looking
return i;
}
}
return long.MinValue;
}
private static bool IsFlagSet(Interop.EventStream.FSEventStreamEventFlags flags, Interop.EventStream.FSEventStreamEventFlags value)
{
return (value & flags) == value;
}
private static bool DoesItemExist(string path, bool isFile)
{
if (isFile)
return File.Exists(path);
else
return Directory.Exists(path);
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;
#endregion
namespace GameStateManagement
{
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
abstract class MenuScreen : GameScreen
{
#region Fields
// the number of pixels to pad above and below menu entries for touch input
const int menuEntryPadding = 10;
List<MenuEntry> menuEntries = new List<MenuEntry>();
int selectedEntry = 0;
string menuTitle;
#endregion
#region Properties
/// <summary>
/// Gets the list of menu entries, so derived classes can add
/// or change the menu contents.
/// </summary>
protected IList<MenuEntry> MenuEntries
{
get { return menuEntries; }
}
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public MenuScreen(string menuTitle)
{
// menus generally only need Tap for menu selection
EnabledGestures = GestureType.Tap;
this.menuTitle = menuTitle;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
}
#endregion
#region Handle Input
/// <summary>
/// Allows the screen to create the hit bounds for a particular menu entry.
/// </summary>
protected virtual Rectangle GetMenuEntryHitBounds(MenuEntry entry)
{
// the hit bounds are the entire width of the screen, and the height of the entry
// with some additional padding above and below.
return new Rectangle(
0,
(int)entry.Position.Y - menuEntryPadding,
ScreenManager.GraphicsDevice.Viewport.Width,
entry.GetHeight(this) + (menuEntryPadding * 2));
}
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(InputState input)
{
// we cancel the current menu screen if the user presses the back button
PlayerIndex player;
if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player))
{
OnCancel(player);
}
// look for any taps that occurred and select any entries that were tapped
foreach (GestureSample gesture in input.Gestures)
{
if (gesture.GestureType == GestureType.Tap)
{
// convert the position to a Point that we can test against a Rectangle
Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
// iterate the entries to see if any were tapped
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
if (GetMenuEntryHitBounds(menuEntry).Contains(tapLocation))
{
// select the entry. since gestures are only available on Windows Phone,
// we can safely pass PlayerIndex.One to all entries since there is only
// one player on Windows Phone.
OnSelectEntry(i, PlayerIndex.One);
}
}
}
}
}
/// <summary>
/// Handler for when the user has chosen a menu entry.
/// </summary>
protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
{
menuEntries[entryIndex].OnSelectEntry(playerIndex);
}
/// <summary>
/// Handler for when the user has cancelled the menu.
/// </summary>
protected virtual void OnCancel(PlayerIndex playerIndex)
{
ExitScreen();
}
/// <summary>
/// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
/// </summary>
protected void OnCancel(object sender, PlayerIndexEventArgs e)
{
OnCancel(e.PlayerIndex);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen the chance to position the menu entries. By default
/// all menu entries are lined up in a vertical list, centered on the screen.
/// </summary>
protected virtual void UpdateMenuEntryLocations()
{
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// start at Y = 175; each X value is generated per entry
Vector2 position = new Vector2(0f, 175f);
// update each menu entry's location in turn
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
// each entry is to be centered horizontally
position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;
if (ScreenState == ScreenState.TransitionOn)
position.X -= transitionOffset * 256;
else
position.X += transitionOffset * 512;
// set the entry's position
menuEntry.Position = position;
// move down for the next entry the size of this entry plus our padding
position.Y += menuEntry.GetHeight(this) + (menuEntryPadding * 2);
}
}
/// <summary>
/// Updates the menu.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// Update each nested MenuEntry object.
for (int i = 0; i < menuEntries.Count; i++)
{
bool isSelected = IsActive && (i == selectedEntry);
menuEntries[i].Update(this, isSelected, gameTime);
}
}
/// <summary>
/// Draws the menu.
/// </summary>
public override void Draw(GameTime gameTime)
{
// make sure our entries are in the right place before we draw them
UpdateMenuEntryLocations();
GraphicsDevice graphics = ScreenManager.GraphicsDevice;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
SpriteFont font = ScreenManager.Font;
spriteBatch.Begin();
// Draw each menu entry in turn.
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
bool isSelected = IsActive && (i == selectedEntry);
menuEntry.Draw(this, isSelected, gameTime);
}
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// Draw the menu title centered on the screen
Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80);
Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
float titleScale = 1.25f;
titlePosition.Y -= transitionOffset * 100;
spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
titleOrigin, titleScale, SpriteEffects.None, 0);
spriteBatch.End();
}
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/language/v1/language_service.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// 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.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Cloud.Language.V1 {
/// <summary>
/// Provides text analysis operations such as sentiment analysis and entity
/// recognition.
/// </summary>
public static class LanguageService
{
static readonly string __ServiceName = "google.cloud.language.v1.LanguageService";
static readonly Marshaller<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest> __Marshaller_AnalyzeSentimentRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSentimentRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> __Marshaller_AnalyzeSentimentResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSentimentResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest> __Marshaller_AnalyzeEntitiesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> __Marshaller_AnalyzeEntitiesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest> __Marshaller_AnalyzeSyntaxRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> __Marshaller_AnalyzeSyntaxResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnnotateTextRequest> __Marshaller_AnnotateTextRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnnotateTextRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Cloud.Language.V1.AnnotateTextResponse> __Marshaller_AnnotateTextResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnnotateTextResponse.Parser.ParseFrom);
static readonly Method<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> __Method_AnalyzeSentiment = new Method<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1.AnalyzeSentimentResponse>(
MethodType.Unary,
__ServiceName,
"AnalyzeSentiment",
__Marshaller_AnalyzeSentimentRequest,
__Marshaller_AnalyzeSentimentResponse);
static readonly Method<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> __Method_AnalyzeEntities = new Method<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse>(
MethodType.Unary,
__ServiceName,
"AnalyzeEntities",
__Marshaller_AnalyzeEntitiesRequest,
__Marshaller_AnalyzeEntitiesResponse);
static readonly Method<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> __Method_AnalyzeSyntax = new Method<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse>(
MethodType.Unary,
__ServiceName,
"AnalyzeSyntax",
__Marshaller_AnalyzeSyntaxRequest,
__Marshaller_AnalyzeSyntaxResponse);
static readonly Method<global::Google.Cloud.Language.V1.AnnotateTextRequest, global::Google.Cloud.Language.V1.AnnotateTextResponse> __Method_AnnotateText = new Method<global::Google.Cloud.Language.V1.AnnotateTextRequest, global::Google.Cloud.Language.V1.AnnotateTextResponse>(
MethodType.Unary,
__ServiceName,
"AnnotateText",
__Marshaller_AnnotateTextRequest,
__Marshaller_AnnotateTextResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.Language.V1.LanguageServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of LanguageService</summary>
public abstract class LanguageServiceBase
{
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for LanguageService</summary>
public class LanguageServiceClient : ClientBase<LanguageServiceClient>
{
/// <summary>Creates a new client for LanguageService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public LanguageServiceClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for LanguageService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public LanguageServiceClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected LanguageServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected LanguageServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSentiment(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSentiment, null, options, request);
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSentimentAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSentiment, null, options, request);
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntities(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeEntities, null, options, request);
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeEntitiesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeEntities, null, options, request);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSyntax(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSyntax, null, options, request);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnalyzeSyntaxAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSyntax, null, options, request);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnnotateText(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual global::Google.Cloud.Language.V1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_AnnotateText, null, options, request);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1.AnnotateTextRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return AnnotateTextAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1.AnnotateTextRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_AnnotateText, null, options, request);
}
protected override LanguageServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new LanguageServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(LanguageServiceBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_AnalyzeSentiment, serviceImpl.AnalyzeSentiment)
.AddMethod(__Method_AnalyzeEntities, serviceImpl.AnalyzeEntities)
.AddMethod(__Method_AnalyzeSyntax, serviceImpl.AnalyzeSyntax)
.AddMethod(__Method_AnnotateText, serviceImpl.AnnotateText).Build();
}
}
}
#endregion
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiAuthSample.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;
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ===========================================================
using System;
using System.Collections.Generic;
using CoroutinesLib.Shared.Logging;
namespace NodeCs.Shared
{
public interface IServiceLocator
{
T Resolve<T>(bool nullIfNotFound = false);
object Resolve(Type t,bool nullIfNotFound = false);
void Release(object ob);
void Register(Type t);
void Register<T>(Func<Type,object> resolver, bool isSingleton = true);
void Register<T>(object instance);
void SetChildLocator(IServiceLocator childLocator);
}
public class ServiceLocator : IServiceLocator
{
private readonly static IServiceLocator _locator = new ServiceLocator();
public static IServiceLocator Locator
{
get { return _locator; }
}
class ServiceInstance
{
public bool IsSingleton;
public object Instance;
public Func<Type,object> Create;
}
private readonly Dictionary<Type, ServiceInstance> _services;
private readonly Dictionary<Type, ServiceInstance> _resolved;
public IServiceLocator ChildLocator { get; private set; }
public void SetChildLocator(IServiceLocator childLocator)
{
if (ChildLocator != null)
{
return;
}
ChildLocator = childLocator;
}
private ServiceLocator()
{
_services = new Dictionary<Type, ServiceInstance>();
_resolved = new Dictionary<Type, ServiceInstance>();
Register<ILogger>(NullLogger.Create());
}
public void Register<T>(Func<Type,object> resolver = null,bool isSingleton=true)
{
if (resolver == null)
{
resolver = Activator.CreateInstance;
}
var instance = resolver(typeof(T));
_services[typeof (T)] = new ServiceInstance
{
Create = resolver,
IsSingleton = isSingleton,
Instance = isSingleton ? instance : null
};
_resolved[instance.GetType()] = _services[typeof (T)];
if (!isSingleton)
{
var disposable = instance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
public void Register(Type t)
{
if (ChildLocator != null)
{
ChildLocator.Register(t);
}
else
{
Func<Type,object> resolver = Activator.CreateInstance;
_services[t] = new ServiceInstance
{
Create = resolver,
IsSingleton = false,
Instance = null
};
_resolved[t] = _services[t];
}
}
public void Register<T>(object instance)
{
if (ChildLocator != null)
{
ChildLocator.Register<T>(instance);
}
else
{
_services[typeof (T)] = new ServiceInstance
{
Create = null,
IsSingleton = true,
Instance = instance
};
_resolved[instance.GetType()] = _services[typeof (T)];
}
}
public T Resolve<T>(bool nullIfNotFound = false)
{
if (_services.ContainsKey(typeof (T)))
{
var desc = _services[typeof (T)];
if (desc.Instance!=null) return (T) desc.Instance;
desc.Instance = desc.Create(typeof(T));
return (T)desc.Instance;
}
if (ChildLocator != null)
{
var result = ChildLocator.Resolve<T>();
if(result != null) return result;
}
if (typeof(T).IsAbstract || typeof(T).IsInterface || nullIfNotFound)
{
return default(T);
}
if (IsSystem(typeof (T))) return default(T);
return Activator.CreateInstance<T>();
}
public object Resolve(Type t,bool nullIfNotFound = false)
{
if (_services.ContainsKey(t))
{
var desc = _services[t];
if (desc.Instance != null) return desc.Instance;
desc.Instance = desc.Create(t);
return desc.Instance;
}
if (ChildLocator != null)
{
var result = ChildLocator.Resolve(t);
if (result != null) return result;
}
if (t.IsAbstract || t.IsInterface || nullIfNotFound)
{
return null;
}
if (IsSystem(t)) return null;
return Activator.CreateInstance(t);
}
private bool IsSystem(Type type)
{
var ns = type.Namespace ?? "";
return type.IsPrimitive ||
ns.StartsWith("System.") ||
ns == "System." ||
type.Module.ScopeName == "CommonLanguageRuntimeLibrary";
}
public void Release(object ob)
{
if (ChildLocator != null)
{
ChildLocator.Release(ob);
}
if (_resolved.ContainsKey(ob.GetType()))
{
var desc = _resolved[ob.GetType()];
if (desc.IsSingleton) return;
var disposable = desc.Instance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
}
}
| |
//====================================================
//| Downloaded From |
//| Visual C# Kicks - http://www.vcskicks.com/ |
//| License - http://www.vcskicks.com/license.html |
//====================================================
using System;
using System.Collections.Generic;
using System.Text;
namespace SyNet.DataHelpers
{
class AVLTreeNode<T> : BinaryTreeNode<T>
where T : IComparable
{
public AVLTreeNode(T value)
: base(value)
{
}
public new AVLTreeNode<T> LeftChild
{
get
{
return (AVLTreeNode<T>)base.LeftChild;
}
set
{
base.LeftChild = value;
}
}
public new AVLTreeNode<T> RightChild
{
get
{
return (AVLTreeNode<T>)base.RightChild;
}
set
{
base.RightChild = value;
}
}
public new AVLTreeNode<T> Parent
{
get
{
return (AVLTreeNode<T>)base.Parent;
}
set
{
base.Parent = value;
}
}
}
/// <summary>
/// AVL Tree data structure
/// </summary>
class AVLTree<T> : BinaryTree<T>
where T : IComparable
{
/// <summary>
/// Returns the AVL Node of the tree
/// </summary>
public new AVLTreeNode<T> Root
{
get { return (AVLTreeNode<T>)base.Root; }
set { base.Root = value; }
}
/// <summary>
/// Returns the AVL Node corresponding to the given value
/// </summary>
public new AVLTreeNode<T> Find(T value)
{
return (AVLTreeNode<T>)base.Find(value);
}
/// <summary>
/// Insert a value in the tree and rebalance the tree if necessary.
/// </summary>
public override void Add(T value)
{
AVLTreeNode<T> node = new AVLTreeNode<T>(value);
base.Add(node); //add normally
//Balance every node going up, starting with the parent
AVLTreeNode<T> parentNode = node.Parent;
while (parentNode != null)
{
int balance = this.getBalance(parentNode);
if (Math.Abs(balance) == 2) //-2 or 2 is unbalanced
{
//Rebalance tree
this.balanceAt(parentNode, balance);
}
parentNode = parentNode.Parent; //keep going up
}
}
/// <summary>
/// Removes a given value from the tree and rebalances the tree if necessary.
/// </summary>
public override bool Remove(T value)
{
AVLTreeNode<T> valueNode = this.Find(value);
return this.Remove(valueNode);
}
/// <summary>
/// Wrapper method for removing a node within the tree
/// </summary>
protected new bool Remove(BinaryTreeNode<T> removeNode)
{
return this.Remove((AVLTreeNode<T>)removeNode);
}
/// <summary>
/// Removes a given node from the tree and rebalances the tree if necessary.
/// </summary>
public bool Remove(AVLTreeNode<T> valueNode)
{
//Save reference to the parent node to be removed
AVLTreeNode<T> parentNode = valueNode.Parent;
//Remove the node as usual
bool removed = base.Remove(valueNode);
if (!removed)
return false; //removing failed, no need to rebalance
else
{
//Balance going up the tree
while (parentNode != null)
{
int balance = this.getBalance(parentNode);
if (Math.Abs(balance) == 1) //1, -1
break; //height hasn't changed, can stop
else if (Math.Abs(balance) == 2) //2, -2
{
//Rebalance tree
this.balanceAt(parentNode, balance);
}
parentNode = parentNode.Parent;
}
return true;
}
}
/// <summary>
/// Balances an AVL Tree node
/// </summary>
protected virtual void balanceAt(AVLTreeNode<T> node, int balance)
{
if (balance == 2) //right outweighs
{
int rightBalance = getBalance(node.RightChild);
if (rightBalance == 1 || rightBalance == 0)
{
//Left rotation needed
rotateLeft(node);
}
else if (rightBalance == -1)
{
//Right rotation needed
rotateRight(node.RightChild);
//Left rotation needed
rotateLeft(node);
}
}
else if (balance == -2) //left outweighs
{
int leftBalance = getBalance(node.LeftChild);
if (leftBalance == 1)
{
//Left rotation needed
rotateLeft(node.LeftChild);
//Right rotation needed
rotateRight(node);
}
else if (leftBalance == -1 || leftBalance == 0)
{
//Right rotation needed
rotateRight(node);
}
}
}
/// <summary>
/// Determines the balance of a given node
/// </summary>
protected virtual int getBalance(AVLTreeNode<T> root)
{
//Balance = right child's height - left child's height
return this.GetHeight(root.RightChild) - this.GetHeight(root.LeftChild);
}
/// <summary>
/// Rotates a node to the left within an AVL Tree
/// </summary>
protected virtual void rotateLeft(AVLTreeNode<T> root)
{
if (root == null)
return;
AVLTreeNode<T> pivot = root.RightChild;
if (pivot == null)
return;
else
{
AVLTreeNode<T> rootParent = root.Parent; //original parent of root node
bool isLeftChild = (rootParent != null) && rootParent.LeftChild == root; //whether the root was the parent's left node
bool makeTreeRoot = root.Tree.Root == root; //whether the root was the root of the entire tree
//Rotate
root.RightChild = pivot.LeftChild;
pivot.LeftChild = root;
//Update parents
root.Parent = pivot;
pivot.Parent = rootParent;
if (root.RightChild != null)
root.RightChild.Parent = root;
//Update the entire tree's Root if necessary
if (makeTreeRoot)
pivot.Tree.Root = pivot;
//Update the original parent's child node
if (isLeftChild)
rootParent.LeftChild = pivot;
else
if (rootParent != null)
rootParent.RightChild = pivot;
}
}
/// <summary>
/// Rotates a node to the right within an AVL Tree
/// </summary>
protected virtual void rotateRight(AVLTreeNode<T> root)
{
if (root == null)
return;
AVLTreeNode<T> pivot = root.LeftChild;
if (pivot == null)
return;
else
{
AVLTreeNode<T> rootParent = root.Parent; //original parent of root node
bool isLeftChild = (rootParent != null) && rootParent.LeftChild == root; //whether the root was the parent's left node
bool makeTreeRoot = root.Tree.Root == root; //whether the root was the root of the entire tree
//Rotate
root.LeftChild = pivot.RightChild;
pivot.RightChild = root;
//Update parents
root.Parent = pivot;
pivot.Parent = rootParent;
if (root.LeftChild != null)
root.LeftChild.Parent = root;
//Update the entire tree's Root if necessary
if (makeTreeRoot)
pivot.Tree.Root = pivot;
//Update the original parent's child node
if (isLeftChild)
rootParent.LeftChild = pivot;
else
if (rootParent != null)
rootParent.RightChild = pivot;
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Alba;
using IssueService;
using IssueService.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
namespace Marten.AspNetCore.Testing
{
public class AppFixture : IDisposable, IAsyncLifetime
{
private IAlbaHost _host;
public AppFixture()
{
}
public void Dispose()
{
_host.Dispose();
}
public IAlbaHost Host => _host;
public async Task InitializeAsync()
{
_host = await Program.CreateHostBuilder(Array.Empty<string>())
.StartAlbaAsync();
}
public async Task DisposeAsync()
{
await _host.DisposeAsync();
}
}
public class web_service_streaming_tests : IClassFixture<AppFixture>
{
private readonly IAlbaHost theHost;
public web_service_streaming_tests(AppFixture fixture)
{
theHost = fixture.Host;
}
[Fact]
public async Task stream_a_single_document_hit()
{
var issue = new Issue {Description = "It's bad", Open = true};
var store = theHost.Services.GetRequiredService<IDocumentStore>();
using (var session = store.LightweightSession())
{
session.Store(issue);
await session.SaveChangesAsync();
}
var result = await theHost.Scenario(s =>
{
s.Get.Url($"/issue/{issue.Id}");
s.StatusCodeShouldBeOk();
s.ContentTypeShouldBe("application/json");
});
var read = result.ReadAsJson<Issue>();
read.Description.ShouldBe(issue.Description);
}
[Fact]
public async Task stream_a_single_document_miss()
{
await theHost.Scenario(s =>
{
s.Get.Url($"/issue/{Guid.NewGuid()}");
s.StatusCodeShouldBe(404);
});
}
[Fact]
public async Task stream_a_single_document_hit_2()
{
var issue = new Issue {Description = "It's bad", Open = true};
var store = theHost.Services.GetRequiredService<IDocumentStore>();
using (var session = store.LightweightSession())
{
session.Store(issue);
await session.SaveChangesAsync();
}
var result = await theHost.Scenario(s =>
{
s.Get.Url($"/issue2/{issue.Id}");
s.StatusCodeShouldBeOk();
s.ContentTypeShouldBe("application/json");
});
var read = result.ReadAsJson<Issue>();
read.Description.ShouldBe(issue.Description);
}
[Fact]
public async Task stream_a_single_document_miss_2()
{
await theHost.Scenario(s =>
{
s.Get.Url($"/issue2/{Guid.NewGuid()}");
s.StatusCodeShouldBe(404);
});
}
[Fact]
public async Task stream_an_array_of_documents()
{
var store = theHost.Services.GetRequiredService<IDocumentStore>();
await store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Issue));
var issues = new Issue[100];
for (int i = 0; i < issues.Length; i++)
{
issues[i] = Issue.Random();
}
await store.BulkInsertDocumentsAsync(issues);
var result = await theHost.Scenario(s =>
{
s.Get.Url("/issue/open");
s.StatusCodeShouldBeOk();
s.ContentTypeShouldBe("application/json");
});
var read = result.ReadAsJson<Issue[]>();
read.Length.ShouldBe(issues.Count(x => x.Open));
}
[Fact]
public async Task stream_a_single_document_hit_with_compiled_query()
{
var issue = new Issue {Description = "It's bad", Open = true};
var store = theHost.Services.GetRequiredService<IDocumentStore>();
using (var session = store.LightweightSession())
{
session.Store(issue);
await session.SaveChangesAsync();
}
var result = await theHost.Scenario(s =>
{
s.Get.Url($"/issue3/{issue.Id}");
s.StatusCodeShouldBeOk();
s.ContentTypeShouldBe("application/json");
});
var read = result.ReadAsJson<Issue>();
read.Description.ShouldBe(issue.Description);
}
[Fact]
public async Task stream_a_single_document_miss_with_compiled_query()
{
await theHost.Scenario(s =>
{
s.Get.Url($"/issue3/{Guid.NewGuid()}");
s.StatusCodeShouldBe(404);
});
}
[Fact]
public async Task stream_an_array_of_documents_with_compiled_query()
{
var store = theHost.Services.GetRequiredService<IDocumentStore>();
await store.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Issue));
var issues = new Issue[100];
for (int i = 0; i < issues.Length; i++)
{
issues[i] = Issue.Random();
}
await store.BulkInsertDocumentsAsync(issues);
var result = await theHost.Scenario(s =>
{
s.Get.Url("/issue2/open");
s.StatusCodeShouldBeOk();
s.ContentTypeShouldBe("application/json");
});
var read = result.ReadAsJson<Issue[]>();
read.Length.ShouldBe(issues.Count(x => x.Open));
}
}
}
| |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Project Oxford: http://ProjectOxford.ai
//
// Project Oxford SDK Github:
// https://github.com/Microsoft/ProjectOxfordSDK-Windows
//
// 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.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ProjectOxford.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.ProjectOxford.Emotion
{
public class EmotionServiceClient : IEmotionServiceClient
{
#region private members
/// <summary>
/// The json header
/// </summary>
private const string JsonHeader = "application/json";
/// <summary>
/// The subscription key name.
/// </summary>
private const string SubscriptionKeyName = "subscription-key";
/// <summary>
/// Path string for REST Emotion recognition method.
/// </summary>
private const string RecognizeQuery = "recognize";
/// <summary>
/// Optional query string for REST Emotion recognition method.
/// </summary>
private const string FaceRectangles = "faceRectangles";
/// <summary>
/// The subscription key.
/// </summary>
private readonly string _subscriptionKey;
/// <summary>
/// The default resolver.
/// </summary>
private static CamelCasePropertyNamesContractResolver s_defaultResolver = new CamelCasePropertyNamesContractResolver();
private static JsonSerializerSettings s_settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = s_defaultResolver
};
private static HttpClient s_httpClient = new HttpClient();
private readonly HttpClient _httpClient;
private static string s_apiRoot = "https://api.projectoxford.ai";
private readonly string _serviceUrl;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="EmotionServiceClient"/> class.
/// </summary>
/// <param name="subscriptionKey">The subscription key.</param>
public EmotionServiceClient(string subscriptionKey) : this(s_httpClient, subscriptionKey, s_apiRoot) { }
/// <summary>
/// Initializes a new instance of the <see cref="EmotionServiceClient"/> class.
/// </summary>
/// <param name="subscriptionKey">The subscription key.</param>
/// <param name="apiRoot">Host name of the service URL, without the trailing slash.</param>
public EmotionServiceClient(string subscriptionKey, string apiRoot) : this(s_httpClient, subscriptionKey, apiRoot) { }
/// <summary>
/// Initializes a new instance of the <see cref="EmotionServiceClient"/> class, with a client-supplied
/// HttpClient object. Intended primarily for testing.
/// </summary>
/// <param name="httpClient"></param>
/// <param name="subscriptionKey"></param>
public EmotionServiceClient(HttpClient httpClient, string subscriptionKey) : this(httpClient, subscriptionKey, s_apiRoot) { }
/// <summary>
/// Initializes a new instance of the <see cref="EmotionServiceClient"/> class, with a client-supplied
/// HttpClient object. Intended primarily for testing.
/// </summary>
/// <param name="httpClient"></param>
/// <param name="subscriptionKey"></param>
/// <param name="subscriptionKey"></param>
public EmotionServiceClient(HttpClient httpClient, string subscriptionKey, string apiRoot)
{
_httpClient = httpClient;
_subscriptionKey = subscriptionKey;
_serviceUrl = apiRoot + "/emotion/v1.0";
}
#region IEmotionServiceClient implementations
/// <summary>
/// Recognize emotions on faces in an image.
/// </summary>
/// <param name="imageUrl">URL of the image.</param>
/// <returns>Async task, which, upon completion, will return rectangle and emotion scores for each recognized face.</returns>
public async Task<Contract.Emotion[]> RecognizeAsync(String imageUrl)
{
return await RecognizeAsync(imageUrl, null);
}
/// <summary>
/// Recognize emotions on faces in an image.
/// </summary>
/// <param name="imageUrl">URL of the image.</param>
/// <param name="faceRectangles">Array of face rectangles.</param>
/// <returns>Async task, which, upon completion, will return rectangle and emotion scores for each recognized face.</returns>
public async Task<Contract.Emotion[]> RecognizeAsync(String imageUrl, Rectangle[] faceRectangles)
{
return await SendRequestAsync<object, Contract.Emotion[]>(faceRectangles, new { url = imageUrl });
}
/// <summary>
/// Recognize emotions on faces in an image.
/// </summary>
/// <param name="imageStream">Stream of the image</param>
/// <returns>Async task, which, upon completion, will return rectangle and emotion scores for each recognized face.</returns>
public async Task<Contract.Emotion[]> RecognizeAsync(Stream imageStream)
{
return await RecognizeAsync(imageStream, null);
}
/// <summary>
/// Recognize emotions on faces in an image.
/// </summary>
/// <param name="imageStream">Stream of the image</param>
/// <returns>Async task, which, upon completion, will return rectangle and emotion scores for each face.</returns>
public async Task<Contract.Emotion[]> RecognizeAsync(Stream imageStream, Rectangle[] faceRectangles)
{
return await SendRequestAsync<Stream, Contract.Emotion[]>(faceRectangles, imageStream);
}
#endregion
#region the JSON client
/// <summary>
/// Helper method executing the REST request.
/// </summary>
/// <typeparam name="TRequest">Type of request.</typeparam>
/// <typeparam name="TResponse">Type of response.</typeparam>
/// <param name="faceRectangles">Optional list of face rectangles.</param>
/// <param name="requestBody">Content of the HTTP request.</param>
/// <returns></returns>
private async Task<TResponse> SendRequestAsync<TRequest, TResponse>(Rectangle[] faceRectangles, TRequest requestBody)
{
var httpMethod = HttpMethod.Post;
var requestUri = new StringBuilder();
requestUri.AppendFormat("{0}/{1}", _serviceUrl, RecognizeQuery);
requestUri.Append('?');
if (faceRectangles != null)
{
requestUri.Append(FaceRectangles);
requestUri.Append('=');
foreach (var rectangle in faceRectangles)
{
requestUri.AppendFormat("{0},{1},{2},{3};",
rectangle.Left,
rectangle.Top,
rectangle.Width,
rectangle.Height);
}
requestUri.Remove(requestUri.Length - 1, 1); // drop last comma
requestUri.Append('&');
}
requestUri.AppendFormat("{0}={1}",
SubscriptionKeyName,
_subscriptionKey);
var request = new HttpRequestMessage(httpMethod, _serviceUrl);
request.RequestUri = new Uri(requestUri.ToString());
if (requestBody != null)
{
if (requestBody is Stream)
{
request.Content = new StreamContent(requestBody as Stream);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
else
{
request.Content = new StringContent(JsonConvert.SerializeObject(requestBody, s_settings), Encoding.UTF8, JsonHeader);
}
}
HttpResponseMessage response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string responseContent = null;
if (response.Content != null)
{
responseContent = await response.Content.ReadAsStringAsync();
}
if (!string.IsNullOrWhiteSpace(responseContent))
{
return JsonConvert.DeserializeObject<TResponse>(responseContent, s_settings);
}
return default(TResponse);
}
else
{
if (response.Content != null && response.Content.Headers.ContentType.MediaType.Contains(JsonHeader))
{
var errorObjectString = await response.Content.ReadAsStringAsync();
ClientError errorCollection = JsonConvert.DeserializeObject<ClientError>(errorObjectString);
if (errorCollection != null)
{
throw new ClientException(errorCollection, response.StatusCode);
}
}
response.EnsureSuccessStatusCode();
}
return default(TResponse);
}
#endregion
}
}
| |
#region (c) 2010-2011 Lokad CQRS - New BSD License
// Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com)
// This code is released as Open Source under the terms of the New BSD Licence
// Homepage: http://lokad.github.com/lokad-cqrs/
#endregion
using System;
namespace Lokad.Cqrs
{
/// <summary>
/// Helper class that indicates nullable value in a good-citizenship code and
/// provides some additional piping syntax
/// </summary>
/// <typeparam name="T">underlying type</typeparam>
[Serializable]
public sealed class Maybe<T> : IEquatable<Maybe<T>>
{
readonly T _value;
readonly bool _hasValue;
Maybe(T item, bool hasValue)
{
_value = item;
_hasValue = hasValue;
}
Maybe(T value)
: this(value, true)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (value == null)
{
throw new ArgumentNullException("value");
}
// ReSharper restore CompareNonConstrainedGenericWithNull
}
/// <summary>
/// Default empty instance.
/// </summary>
public static readonly Maybe<T> Empty = new Maybe<T>(default(T), false);
/// <summary>
/// Gets the underlying value.
/// </summary>
/// <value>The value.</value>
public T Value
{
get
{
if (!_hasValue)
{
throw new InvalidOperationException("Dont access value when maybe is empty");
}
return _value;
}
}
/// <summary>
/// Gets a value indicating whether this instance has value.
/// </summary>
/// <value><c>true</c> if this instance has value; otherwise, <c>false</c>.</value>
public bool HasValue
{
get { return _hasValue; }
}
/// <summary>
/// Retrieves value from this instance, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public T GetValue(T defaultValue)
{
return _hasValue ? _value : defaultValue;
}
/// <summary>
/// Retrieves value from this instance, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public T GetValue(Func<T> defaultValue)
{
return _hasValue ? _value : defaultValue();
}
/// <summary>
/// Retrieves value from this instance, using a <paramref name="defaultValue"/>
/// factory, if it is absent
/// </summary>
/// <param name="defaultValue">The default value to provide.</param>
/// <returns>maybe value</returns>
public Maybe<T> Combine(Func<Maybe<T>> defaultValue)
{
return _hasValue ? this : defaultValue();
}
/// <summary>
/// Converts this instance to <see cref="Maybe{T}"/>,
/// while applying <paramref name="converter"/> if there is a value.
/// </summary>
/// <typeparam name="TTarget">The type of the target.</typeparam>
/// <param name="converter">The converter.</param>
/// <returns></returns>
public Maybe<TTarget> Convert<TTarget>(Func<T, TTarget> converter)
{
return _hasValue ? converter(_value) : Maybe<TTarget>.Empty;
}
/// <summary>
/// Retrieves converted value, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <typeparam name="TTarget">type of the conversion target</typeparam>
/// <param name="converter">The converter.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public TTarget Convert<TTarget>(Func<T, TTarget> converter, Func<TTarget> defaultValue)
{
return _hasValue ? converter(_value) : defaultValue();
}
/// <summary>
/// Retrieves converted value, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <typeparam name="TTarget">type of the conversion target</typeparam>
/// <param name="converter">The converter.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public TTarget Convert<TTarget>(Func<T, TTarget> converter, TTarget defaultValue)
{
return _hasValue ? converter(_value) : defaultValue;
}
/// <summary>
/// Retrieves converted value.
/// </summary>
/// <typeparam name="TTarget">type of the conversion target</typeparam>
/// <param name="converter">The converter.</param>
/// <returns>value</returns>
public Maybe<TTarget> Combine<TTarget>(Func<T, Maybe<TTarget>> converter)
{
return _hasValue ? converter(_value) : Maybe<TTarget>.Empty;
}
/// <summary>
/// Determines whether the specified <see cref="Maybe{T}"/> is equal to the current <see cref="Maybe{T}"/>.
/// </summary>
/// <param name="maybe">The <see cref="Maybe{T}"/> to compare with.</param>
/// <returns>true if the objects are equal</returns>
public bool Equals(Maybe<T> maybe)
{
if (ReferenceEquals(null, maybe)) return false;
if (ReferenceEquals(this, maybe)) return true;
if (_hasValue != maybe._hasValue) return false;
if (!_hasValue) return true;
return _value.Equals(maybe._value);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
var maybe = obj as Maybe<T>;
if (maybe == null) return false;
return Equals(maybe);
}
/// <summary>
/// Serves as a hash function for this instance.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="Maybe{T}"/>.
/// </returns>
public override int GetHashCode()
{
unchecked
{
// ReSharper disable CompareNonConstrainedGenericWithNull
return ((_value != null ? _value.GetHashCode() : 0) * 397) ^ _hasValue.GetHashCode();
// ReSharper restore CompareNonConstrainedGenericWithNull
}
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(Maybe<T> left, Maybe<T> right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(Maybe<T> left, Maybe<T> right)
{
return !Equals(left, right);
}
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Maybe{T}"/>.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Maybe<T>(T item)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (item == null) throw new ArgumentNullException("item");
// ReSharper restore CompareNonConstrainedGenericWithNull
return new Maybe<T>(item);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (_hasValue)
{
return "<" + _value + ">";
}
return "<Empty>";
}
/// <summary>
/// Eagerly applies the <paramref name="applicator"/> function, if the optional has a value.
/// </summary>
/// <param name="applicator">The applicator function.</param>
/// <returns>same instance for further chaining</returns>
public Maybe<T> IfValue(Action<T> applicator)
{
if (_hasValue)
{
applicator(_value);
}
return this;
}
/// <summary>
/// Eagerly executes the <paramref name="applicator"/> functional,
/// if this optional does not have a value.
/// </summary>
/// <param name="applicator">The applicator.</param>
/// <returns>same instance for further chaining</returns>
public Maybe<T> IfEmpty(Action applicator)
{
if (!_hasValue)
{
applicator();
}
return this;
}
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_5_4_15 : EcmaTest
{
[Fact]
[Trait("Category", "15.5.4.15")]
public void TheStringPrototypeSubstringLengthPropertyHasTheAttributeReadonly()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void TheLengthPropertyOfTheSubstringMethodIs2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T12.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd5()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T13.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd6()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T14.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd7()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T15.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd8()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd9()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd10()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd11()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd12()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd13()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEnd14()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A1_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T3.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject5()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject6()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject7()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject8()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject9()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndReturnsAStringValueNotObject10()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A2_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T1.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject2()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T10.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject3()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T11.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject4()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T2.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject5()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T3.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject6()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T4.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject7()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T5.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject8()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject9()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject10()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringStartEndCanBeAppliedToNonStringObjectInstanceAndReturnsAStringValueNotObject11()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A3_T9.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringHasNotPrototypeProperty()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A6.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void StringPrototypeSubstringCanTBeUsedAsConstructor()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A7.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void TheStringPrototypeSubstringLengthPropertyHasTheAttributeDontenum()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A8.js", false);
}
[Fact]
[Trait("Category", "15.5.4.15")]
public void TheStringPrototypeSubstringLengthPropertyHasTheAttributeDontdelete()
{
RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.15/S15.5.4.15_A9.js", false);
}
}
}
| |
/*
* MSR Tools - tools for mining software repositories
*
* Copyright (C) 2010-2011 Semyon Kirnosenko
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MSR.Data;
using MSR.Data.Entities;
using MSR.Data.Entities.Mapping;
using MSR.Data.Entities.Mapping.PathSelectors;
using MSR.Data.Entities.DSL.Mapping;
using MSR.Data.Entities.DSL.Selection;
using MSR.Data.Entities.DSL.Selection.Metrics;
using MSR.Data.BugTracking;
using MSR.Data.VersionControl;
namespace MSR.Tools.Mapper
{
public class MappingTool : Tool
{
private IScmData scmData;
private IScmData scmDataWithoutCache;
private bool automaticallyFixDiffErrors;
private Func<ProjectFileSelectionExpression,ProjectFileSelectionExpression> pathFilter;
public MappingTool(string configFile)
: base(configFile, "mappingtool")
{
scmData = GetScmData();
scmDataWithoutCache = GetScmDataWithoutCache();
}
public void Info()
{
Console.WriteLine("Database info:");
using (var s = data.OpenSession())
{
Console.WriteLine("Revisions: {0}",
s.Queryable<Commit>().Count()
);
Console.WriteLine("Last revision: {0}", s.LastRevision());
Console.WriteLine("Period: {0}-{1}",
s.Queryable<Commit>().Min(c => c.Date),
s.Queryable<Commit>().Max(c => c.Date)
);
Console.WriteLine("LOC: {0}",
s.SelectionDSL().CodeBlocks().CalculateLOC()
);
Console.WriteLine("Releases: {0}",
s.Queryable<Release>().Count()
);
Console.WriteLine("Files: {0}",
s.Queryable<ProjectFile>().Count()
);
Console.WriteLine("Fixes: {0}",
s.Queryable<BugFix>().Count()
);
}
}
public void Map(bool createSchema, int stopRevisionNumber)
{
Map(createSchema, scmData.RevisionByNumber(stopRevisionNumber));
}
public void Map(bool createDataBase, string stopRevision)
{
MappingController mapping = GetConfiguredType<MappingController>();
mapping.CreateDataBase = createDataBase;
mapping.StopRevision = stopRevision;
Map(mapping);
}
public void PartialMap(int startRevisionNumber, IPathSelector[] pathSelectors)
{
PartialMap(scmData.RevisionByNumber(startRevisionNumber), pathSelectors);
}
public void PartialMap(string startRevision, IPathSelector[] pathSelectors)
{
MappingController mapping = GetConfiguredType<MappingController>();
mapping.StartRevision = startRevision;
mapping.RegisterMapper(GetConfiguredType<CommitMapperForExistentRevision>());
var fileMapper = GetConfiguredType<ProjectFileMapper>();
fileMapper.PathSelectors = pathSelectors;
mapping.RegisterMapper(fileMapper);
mapping.KeepOnlyMappers(new Type[]
{
typeof(Commit),
typeof(ProjectFile),
typeof(Modification),
typeof(CodeBlock)
});
Map(mapping);
}
public void MapReleaseEntity(string revision, string tag)
{
using (ConsoleTimeLogger.Start("entity mapping time"))
using (var s = data.OpenSession())
{
s.Add(new Release()
{
Commit = s.Queryable<Commit>().Single(c =>
c.Revision == revision
),
Tag = tag
});
s.SubmitChanges();
}
}
public void Truncate(int numberOfRevisionsToKeep)
{
Truncate(scmData.RevisionByNumber(numberOfRevisionsToKeep));
}
public void Truncate(string lastRevisionToKeep)
{
using (ConsoleTimeLogger.Start("truncating time"))
using (var s = data.OpenSession())
{
var selectionDSL = s.SelectionDSL();
var addedCommits = selectionDSL.Commits().AfterRevision(lastRevisionToKeep);
var addedBugFixes = addedCommits.BugFixes().InCommits();
var addedModifications = addedCommits.Modifications().InCommits();
var addedFiles = addedCommits.Files().AddedInCommits();
var deletedFiles = addedCommits.Files().DeletedInCommits();
var addedCodeBlocks = addedModifications.CodeBlocks().InModifications();
foreach (var codeBlock in addedCodeBlocks)
{
s.Delete(codeBlock);
}
foreach (var modification in addedModifications)
{
s.Delete(modification);
}
foreach (var file in addedFiles)
{
s.Delete(file);
}
foreach (var file in deletedFiles)
{
file.DeletedInCommit = null;
}
foreach (var bugFix in addedBugFixes)
{
s.Delete(bugFix);
}
foreach (var commit in addedCommits)
{
s.Delete(commit);
}
s.SubmitChanges();
}
}
public void MapReleases(IDictionary<string,string> releases)
{
using (ConsoleTimeLogger.Start("releases mapping time"))
using (var s = data.OpenSession())
{
foreach (var release in releases)
{
s.MappingDSL()
.Commit(release.Key).IsRelease(release.Value);
}
s.SubmitChanges();
}
}
public void MapSyntheticReleases(int count)
{
MapSyntheticReleases(count, 0.9);
}
public void MapSyntheticReleases(int count, double stabilizationProbability)
{
Dictionary<string,string> releases = new Dictionary<string,string>();
using (var s = data.OpenSession())
{
double stabilizationPeriod = s.SelectionDSL().BugFixes()
.CalculateStabilizationPeriod(stabilizationProbability);
DateTime from = s.Queryable<Commit>().Single(c => c.Revision == s.FirstRevision()).Date;
DateTime to = s.Queryable<Commit>().Single(c => c.Revision == s.LastRevision()).Date.AddDays(- stabilizationPeriod);
int duration = (to - from).Days;
int delta = duration / count;
DateTime releaseDate = from;
for (int i = 1; i <= count; i++)
{
releaseDate = releaseDate.AddDays(delta);
var q = s.Queryable<Commit>()
.Where(x => x.Date <= releaseDate)
.OrderByDescending(x => x.Date).ToList();
releases.Add(
s.Queryable<Commit>()
.Where(x => x.Date <= releaseDate)
.OrderByDescending(x => x.Date)
.First().Revision,
"Synthetic Release # " + i.ToString()
);
}
}
MapReleases(releases);
}
public void Check(int stopRevisionNumber)
{
Check(stopRevisionNumber, null, false);
}
public void Check(int stopRevisionNumber, string path, bool automaticallyFixDiffErrors)
{
Check(
scmData.RevisionByNumber(stopRevisionNumber),
path,
automaticallyFixDiffErrors
);
}
public void Check(string stopRevision, string path, bool automaticallyFixDiffErrors)
{
pathFilter = e => path == null ? e : e.PathIs(path);
this.automaticallyFixDiffErrors = automaticallyFixDiffErrors;
using (ConsoleTimeLogger.Start("checking time"))
using (var s = data.OpenSession())
{
string testRevision = stopRevision;
if (s.Queryable<Commit>().SingleOrDefault(c => c.Revision == testRevision) == null)
{
Console.WriteLine("Could not find revision {0}.", testRevision);
return;
}
CheckEmptyCodeBlocks(s, testRevision);
CheckCodeSizeForDeletedFiles(s, testRevision);
CheckTargetsForCodeBlocks(s, testRevision);
CheckDeletedCodeBlocksVsAdded(s, testRevision);
CheckLinesContent(s, scmDataWithoutCache, testRevision);
if (automaticallyFixDiffErrors)
{
s.SubmitChanges();
}
}
}
private void Map(MappingController mapping)
{
using (ConsoleTimeLogger.Start("mapping time"))
{
mapping.OnRevisionMapping += (r, n) => Console.WriteLine(
"mapping of revision {0}{1}",
r,
r != n ? string.Format(" ({0})", n) : ""
);
mapping.Map(data);
}
}
private void CheckEmptyCodeBlocks(IRepository repository, string testRevision)
{
foreach (var zeroCodeBlock in
from cb in repository.Queryable<CodeBlock>()
join m in repository.Queryable<Modification>() on cb.ModificationID equals m.ID
join f in repository.Queryable<ProjectFile>() on m.FileID equals f.ID
join c in repository.Queryable<Commit>() on m.CommitID equals c.ID
let testRevisionNumber = repository.Queryable<Commit>()
.Single(x => x.Revision == testRevision)
.OrderedNumber
where
c.OrderedNumber <= testRevisionNumber
&&
cb.Size == 0
select new { path = f.Path, revision = c.Revision }
)
{
Console.WriteLine("Empty code block in file {0} in revision {1}!",
zeroCodeBlock.path, zeroCodeBlock.revision
);
}
}
private void CheckTargetsForCodeBlocks(IRepository repository, string testRevision)
{
foreach (var codeBlockWithWrongTarget in
from cb in repository.Queryable<CodeBlock>()
join m in repository.Queryable<Modification>() on cb.ModificationID equals m.ID
join f in repository.Queryable<ProjectFile>() on m.FileID equals f.ID
join c in repository.Queryable<Commit>() on m.CommitID equals c.ID
let testRevisionNumber = repository.Queryable<Commit>()
.Single(x => x.Revision == testRevision)
.OrderedNumber
where
c.OrderedNumber <= testRevisionNumber
&&
(
(cb.Size > 0 && cb.TargetCodeBlockID != null)
||
(cb.Size < 0 && cb.TargetCodeBlockID == null)
)
select new
{
CodeSize = cb.Size,
Path = f.Path,
Revision = c.Revision
}
)
{
Console.WriteLine("Code block in revision {0} with size {1} for file {2} should{3} have target!",
codeBlockWithWrongTarget.Revision,
codeBlockWithWrongTarget.CodeSize,
codeBlockWithWrongTarget.Path,
codeBlockWithWrongTarget.CodeSize < 0 ? "" : " not"
);
}
}
private void CheckCodeSizeForDeletedFiles(IRepository repository, string testRevision)
{
foreach (var codeSizeForDeletedFile in
(
from cb in repository.Queryable<CodeBlock>()
join m in repository.Queryable<Modification>() on cb.ModificationID equals m.ID
join f in repository.Queryable<ProjectFile>() on m.FileID equals f.ID
join c in repository.Queryable<Commit>() on m.CommitID equals c.ID
let testRevisionNumber = repository.Queryable<Commit>()
.Single(x => x.Revision == testRevision)
.OrderedNumber
where
c.OrderedNumber <= testRevisionNumber
&&
f.DeletedInCommitID != null
&&
repository.Queryable<Commit>()
.Single(x => x.ID == f.DeletedInCommitID)
.OrderedNumber <= testRevisionNumber
group cb by f into g
select new
{
Path = g.Key.Path,
DeletedInRevision = repository.Queryable<Commit>()
.Single(x => x.ID == g.Key.DeletedInCommitID)
.Revision,
CodeSize = g.Sum(x => x.Size)
}
).Where(x => x.CodeSize != 0)
)
{
Console.WriteLine("For file {0} deleted in revision {1} code size is not 0. {2} should be 0.",
codeSizeForDeletedFile.Path,
codeSizeForDeletedFile.DeletedInRevision,
codeSizeForDeletedFile.CodeSize
);
}
}
private void CheckDeletedCodeBlocksVsAdded(IRepository repository, string testRevision)
{
foreach (var codeBlockWithWrongTarget in
(
from cb in repository.Queryable<CodeBlock>()
join m in repository.Queryable<Modification>() on cb.ModificationID equals m.ID
join f in repository.Queryable<ProjectFile>() on m.FileID equals f.ID
join c in repository.Queryable<Commit>() on m.CommitID equals c.ID
let testRevisionNumber = repository.Queryable<Commit>()
.Single(x => x.Revision == testRevision)
.OrderedNumber
let addedCodeID = cb.Size < 0 ? cb.TargetCodeBlockID : cb.ID
where
c.OrderedNumber <= testRevisionNumber
group cb.Size by addedCodeID into g
select new
{
CodeSize = g.Sum(),
Path = repository.Queryable<ProjectFile>()
.Single(f => f.ID == repository.Queryable<Modification>()
.Single(m => m.ID == repository.Queryable<CodeBlock>()
.Single(cb => cb.ID == g.Key).ModificationID
).FileID
).Path,
AddedCodeSize = repository.Queryable<CodeBlock>()
.Single(cb => cb.ID == g.Key)
.Size,
Revision = repository.Queryable<Commit>()
.Single(c => c.ID == repository.Queryable<Modification>()
.Single(m => m.ID == repository.Queryable<CodeBlock>()
.Single(cb => cb.ID == g.Key).ModificationID
).CommitID
).Revision
}
).Where(x => x.CodeSize < 0)
)
{
Console.WriteLine("There are too many deleted code blocks for code block in revision {0} for file {1} for code with size {2}. Code size {3} should be greater or equal to 0",
codeBlockWithWrongTarget.Revision,
codeBlockWithWrongTarget.Path,
codeBlockWithWrongTarget.AddedCodeSize,
codeBlockWithWrongTarget.CodeSize
);
}
}
private void CheckLinesContent(IRepository repository, IScmData scmData, string testRevision)
{
var existentFiles = repository.SelectionDSL()
.Files()
.Reselect(pathFilter)
.ExistInRevision(testRevision);
foreach (var existentFile in existentFiles)
{
CheckLinesContent(repository, scmData, testRevision, existentFile, false);
}
}
private bool CheckLinesContent(IRepository repository, IScmData scmData, string testRevision, ProjectFile file, bool resultOnly)
{
IBlame fileBlame = null;
try
{
fileBlame = scmData.Blame(testRevision, file.Path);
}
catch
{
}
if (fileBlame == null)
{
if (! resultOnly)
{
Console.WriteLine("File {0} does not exist.", file.Path);
}
return false;
}
double currentLOC = repository.SelectionDSL()
.Commits().TillRevision(testRevision)
.Files().IdIs(file.ID)
.Modifications().InCommits().InFiles()
.CodeBlocks().InModifications()
.CalculateLOC();
bool correct = currentLOC == fileBlame.Count;
if (! correct)
{
if (! resultOnly)
{
Console.WriteLine("Incorrect number of lines in file {0}. {1} should be {2}",
file.Path, currentLOC, fileBlame.Count
);
}
else
{
return false;
}
}
SmartDictionary<string, int> linesByRevision = new SmartDictionary<string, int>(x => 0);
foreach (var line in fileBlame)
{
linesByRevision[line.Value]++;
}
var codeBySourceRevision =
(
from f in repository.Queryable<ProjectFile>()
join m in repository.Queryable<Modification>() on f.ID equals m.FileID
join cb in repository.Queryable<CodeBlock>() on m.ID equals cb.ModificationID
join c in repository.Queryable<Commit>() on m.CommitID equals c.ID
let addedCodeBlock = repository.Queryable<CodeBlock>()
.Single(x => x.ID == (cb.Size < 0 ? cb.TargetCodeBlockID : cb.ID))
let codeAddedInitiallyInRevision = repository.Queryable<Commit>()
.Single(x => x.ID == addedCodeBlock.AddedInitiallyInCommitID)
.Revision
let testRevisionNumber = repository.Queryable<Commit>()
.Single(x => x.Revision == testRevision)
.OrderedNumber
where
f.ID == file.ID
&&
c.OrderedNumber <= testRevisionNumber
group cb.Size by codeAddedInitiallyInRevision into g
select new
{
FromRevision = g.Key,
CodeSize = g.Sum()
}
).Where(x => x.CodeSize != 0).ToList();
var errorCode =
(
from codeFromRevision in codeBySourceRevision
where
codeFromRevision.CodeSize != linesByRevision[codeFromRevision.FromRevision]
select new
{
SourceRevision = codeFromRevision.FromRevision,
CodeSize = codeFromRevision.CodeSize,
RealCodeSize = linesByRevision[codeFromRevision.FromRevision]
}
).ToList();
correct =
correct
&&
codeBySourceRevision.Count() == linesByRevision.Count
&&
errorCode.Count == 0;
if (! resultOnly)
{
if (codeBySourceRevision.Count() != linesByRevision.Count)
{
Console.WriteLine("Number of revisions file {0} contains code from is incorrect. {1} should be {2}",
file.Path, codeBySourceRevision.Count(), linesByRevision.Count
);
}
foreach (var error in errorCode)
{
Console.WriteLine("Incorrect number of lines in file {0} from revision {1}. {2} should be {3}",
file.Path,
error.SourceRevision,
error.CodeSize,
error.RealCodeSize
);
}
if ((! correct) && (errorCode.Count > 0))
{
string latestCodeRevision = repository.LastRevision(errorCode.Select(x => x.SourceRevision));
var commitsFileTouchedIn = repository.SelectionDSL()
.Files().IdIs(file.ID)
.Commits().FromRevision(latestCodeRevision).TouchFiles()
.OrderBy(c => c.OrderedNumber);
foreach (var commit in commitsFileTouchedIn)
{
if (!CheckLinesContent(repository, scmData, commit.Revision, file, true))
{
Console.WriteLine("{0} - incorrectly mapped commit.", commit.Revision);
if ((automaticallyFixDiffErrors) && (errorCode.Sum(x => x.CodeSize - x.RealCodeSize) == 0))
{
var incorrectDeleteCodeBlocks =
from cb in repository.SelectionDSL()
.Commits().RevisionIs(commit.Revision)
.Files().PathIs(file.Path)
.Modifications().InCommits().InFiles()
.CodeBlocks().InModifications().Deleted()
join tcb in repository.Queryable<CodeBlock>() on cb.TargetCodeBlockID equals tcb.ID
join m in repository.Queryable<Modification>() on tcb.ModificationID equals m.ID
join c in repository.Queryable<Commit>() on m.CommitID equals c.ID
where
errorCode.Select(x => x.SourceRevision).Contains(c.Revision)
select new
{
Code = cb,
TargetRevision = c.Revision
};
foreach (var error in errorCode)
{
var incorrectDeleteCodeBlock = incorrectDeleteCodeBlocks.SingleOrDefault(x => x.TargetRevision == error.SourceRevision);
var codeBlock = incorrectDeleteCodeBlock == null ? null : incorrectDeleteCodeBlock.Code;
double difference = error.CodeSize - error.RealCodeSize;
if (codeBlock == null)
{
codeBlock = new CodeBlock()
{
Size = 0,
Modification = repository.SelectionDSL()
.Commits().RevisionIs(commit.Revision)
.Files().PathIs(file.Path)
.Modifications().InCommits().InFiles().Single(),
};
repository.Add(codeBlock);
}
Console.WriteLine("Fix code block size for file {0} in revision {1}:", file.Path, commit.Revision);
Console.Write("Was {0}", codeBlock.Size);
codeBlock.Size -= difference;
if (codeBlock.Size == 0)
{
repository.Delete(codeBlock);
}
else if ((codeBlock.Size > 0) && (codeBlock.AddedInitiallyInCommitID == null))
{
codeBlock.AddedInitiallyInCommit = commit;
}
else if ((codeBlock.Size < 0) && (codeBlock.TargetCodeBlockID == null))
{
codeBlock.TargetCodeBlock = repository.SelectionDSL()
.Commits().RevisionIs(error.SourceRevision)
.Files().PathIs(file.Path)
.Modifications().InFiles()
.CodeBlocks().InModifications().AddedInitiallyInCommits().Single();
}
Console.WriteLine(", now {0}", codeBlock.Size);
}
}
break;
}
}
}
}
return correct;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a highly-precise pixel coordinate.
/// </summary>
/// <remarks><para>This class behaves similar to the <strong>PointF</strong> structure in the
/// <strong>System.Drawing</strong> namespace, except that it supports double-precision
/// values and can be converted into a geographic coordinate. This structure is also
/// supported on the Compact Framework version of the <strong>DotSpatial.Positioning</strong>,
/// whereas <strong>PointF</strong> is not.</para>
/// <para>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (its properties can only be changed via constructors).</para></remarks>
[TypeConverter("DotSpatial.Positioning.Design.PointDConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=1.0.0.0, PublicKeyToken=b4b0b185210c9dae")]
#endif
public struct PointD : IFormattable, IEquatable<PointD>, IXmlSerializable
{
/// <summary>
///
/// </summary>
private double _x;
/// <summary>
///
/// </summary>
private double _y;
#region Fields
/// <summary>
/// Returns a point with no value.
/// </summary>
public static readonly PointD Empty = new PointD(0, 0);
/// <summary>
/// Represents an invalid coordinate.
/// </summary>
public static readonly PointD Invalid = new PointD(double.NaN, double.NaN);
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new instance for the specified coordinates.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public PointD(double x, double y)
{
_x = x;
_y = y;
}
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
public PointD(string value)
: this(value, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
public PointD(string value, CultureInfo culture)
{
// Trim the string and remove double spaces
value = value.Replace(" ", " ").Trim();
// And separate it via the list separator
string[] values = value.Split(Convert.ToChar(culture.TextInfo.ListSeparator, culture));
// Return the converted values
_x = double.Parse(values[0], NumberStyles.Any, culture);
_y = double.Parse(values[1], NumberStyles.Any, culture);
}
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="reader">The reader.</param>
public PointD(XmlReader reader)
{
_x = _y = 0.0;
ReadXml(reader);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Gets or sets the x-coordinate of this PointD.
/// </summary>
/// <value>The X.</value>
public double X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// For projected coordinates, this is the factor Lamda or the longitude parameter.
/// For readability only, the value is X.
/// </summary>
/// <value>The lam.</value>
public double Lam
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// Gets or sets the x-coordinate of this PointD.
/// </summary>
/// <value>The Y.</value>
public double Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// For projected coordinates, this is the factor Phi or the latitude parameter.
/// For readability only, the value is Y.
/// </summary>
/// <value>The phi.</value>
public double Phi
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// Returns whether the current instance has no value.
/// </summary>
public bool IsEmpty
{
get
{
return (_x == 0 && _y == 0);
}
}
/// <summary>
/// Returns whether the current instance has an invalid value.
/// </summary>
public bool IsInvalid
{
get
{
double fail = _x * _y;
return (double.IsNaN(fail) || double.IsInfinity(fail));
}
}
#endregion Public Properties
#region Public Methods
/*
/// <summary>Calculates the direction from one point to another.</summary>
public Azimuth BearingTo(PointD value)
{
double Result = value.Subtract(this).ToPolarCoordinate().Theta.DecimalDegrees;
return new Azimuth(Result).Normalize();
}
*/
/// <summary>
/// Calculates the distance to another pixel.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public double DistanceTo(PointD value)
{
return Math.Sqrt(Math.Abs(value.X - _x) * Math.Abs(value.X - _x)
+ Math.Abs(value.Y - _y) * Math.Abs(value.Y - _y));
}
/// <summary>
/// Indicates if the current instance is closer to the top of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the specified value is above; otherwise, <c>false</c>.</returns>
public bool IsAbove(PointD value)
{
return _y < value.Y;
}
/// <summary>
/// Indicates if the current instance is closer to the bottom of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the specified value is below; otherwise, <c>false</c>.</returns>
public bool IsBelow(PointD value)
{
return _y > value.Y;
}
/// <summary>
/// Indicates if the current instance is closer to the left of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if [is left of] [the specified value]; otherwise, <c>false</c>.</returns>
public bool IsLeftOf(PointD value)
{
return _x < value.X;
}
/// <summary>
/// Indicates if the current instance is closer to the right of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if [is right of] [the specified value]; otherwise, <c>false</c>.</returns>
public bool IsRightOf(PointD value)
{
return _x > value.X;
}
/// <summary>
/// Returns the current instance with its signs switched.
/// </summary>
/// <returns></returns>
/// <remarks>This method returns a new point where the signs of X and Y are flipped. For example, if
/// a point, represents (20, 40), this function will return (-20, -40).</remarks>
public PointD Mirror()
{
return new PointD(-_x, -_y);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns the current instance rotated about (0, 0).
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns></returns>
public PointD Rotate(Angle angle)
{
return Rotate(angle.DecimalDegrees);
}
/// <summary>
/// Returns the current instance rotated about (0, 0).
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns></returns>
public PointD Rotate(double angle)
{
// Convert the angle to radians
double angleRadians = Radian.FromDegrees(angle).Value;
double angleCos = Math.Cos(angleRadians);
double angleSin = Math.Sin(angleRadians);
// Yes. Rotate the point about 0, 0
return new PointD(angleCos * _x - angleSin * _y, angleSin * _x + angleCos * _y);
}
/// <summary>
/// Returns the current instance rotated about the specified point.
/// </summary>
/// <param name="angle">The angle.</param>
/// <param name="center">The center.</param>
/// <returns></returns>
public PointD RotateAt(Angle angle, PointD center)
{
return RotateAt(angle.DecimalDegrees, center);
}
/// <summary>
/// Rotates at.
/// </summary>
/// <param name="angle">The angle.</param>
/// <param name="center">The center.</param>
/// <returns></returns>
public PointD RotateAt(double angle, PointD center)
{
if (angle == 0)
return this;
// Shift the point by its center, rotate, then add the center back in
return Subtract(center).Rotate(angle).Add(center);
}
#endregion Public Methods
#region Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is PointD)
return Equals((PointD)obj);
return false;
}
/// <summary>
/// Returns a unique code used for hash tables.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return _x.GetHashCode() ^ _y.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region Static Methods
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static PointD Parse(string value)
{
return new PointD(value);
}
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public static PointD Parse(string value, CultureInfo culture)
{
return new PointD(value, culture);
}
#endregion Static Methods
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(PointD left, PointD right)
{
return left.Equals(right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(PointD left, PointD right)
{
return !left.Equals(right);
}
/// <summary>
/// Implements the operator +.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator +(PointD left, PointD right)
{
return new PointD(left.X + right.X, left.Y + right.Y);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator -(PointD left, PointD right)
{
return new PointD(left.X - right.X, left.Y - right.Y);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator *(PointD left, PointD right)
{
return new PointD(left.X * right.X, left.Y * right.Y);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator /(PointD left, PointD right)
{
return new PointD(left.X / right.X, left.Y / right.Y);
}
/// <summary>
/// Returns the sum of two points by adding X and Y values together.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method adds the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Add(PointD offset)
{
return new PointD(_x + offset.X, _y + offset.Y);
//return Offset(offset.X, offset.Y);
}
/// <summary>
/// Returns the sum of two points by adding X and Y values together.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
/// <remarks>This method adds the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Add(double offsetX, double offsetY)
{
return new PointD(_x + offsetX, _y + offsetY);
}
/// <summary>
/// Returns the difference of two points by subtracting the specified X and Y values.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method subtracts the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Subtract(PointD offset)
{
return new PointD(_x - offset.X, _y - offset.Y);
}
/// <summary>
/// Returns the difference of two points by subtracting the specified X and Y values.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
/// <remarks>This method subtracts the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Subtract(double offsetX, double offsetY)
{
return new PointD(_x - offsetX, _y - offsetY);
}
/// <summary>
/// Returns the product of two points by multiplying X and Y values together.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method multiplies the X and Y coordinates together and returns a new point at that location. This
/// is typically used to scale a point from one coordinate system to another.</remarks>
public PointD Multiply(PointD offset)
{
return new PointD(_x * offset.X, _y * offset.Y);
}
/// <summary>
/// Multiplies the specified offset X.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
public PointD Multiply(double offsetX, double offsetY)
{
return new PointD(_x * offsetX, _y * offsetY);
}
/// <summary>
/// Divides the specified offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
public PointD Divide(PointD offset)
{
return new PointD(_x / offset.X, _y / offset.Y);
}
/// <summary>
/// Divides the specified offset X.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
public PointD Divide(double offsetX, double offsetY)
{
return new PointD(_x / offsetX, _y / offsetY);
}
#endregion Operators
#region Conversions
/// <summary>
/// Performs an explicit conversion from <see cref="DotSpatial.Positioning.PointD"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator string(PointD value)
{
return value.ToString();
}
#endregion Conversions
#region IEquatable<PointD> Members
/// <summary>
/// Equalses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool Equals(PointD value)
{
return (_x == value.X) && (_y == value.Y);
}
/// <summary>
/// Equalses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="precision">The precision.</param>
/// <returns></returns>
public bool Equals(PointD value, int precision)
{
return ((Math.Round(_x, precision) == Math.Round(value.X, precision))
&& (Math.Round(_y, precision) == Math.Round(value.Y, precision)));
}
#endregion IEquatable<PointD> Members
#region IFormattable Members
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
return _x.ToString(format, formatProvider)
+ culture.TextInfo.ListSeparator
+ _y.ToString(format, formatProvider);
}
#endregion IFormattable Members
#region IXmlSerializable Members
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("X",
_x.ToString("G17", CultureInfo.InvariantCulture));
writer.WriteAttributeString("Y",
_y.ToString("G", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
public void ReadXml(XmlReader reader)
{
double.TryParse(reader.GetAttribute("X"), NumberStyles.Any, CultureInfo.InvariantCulture, out _x);
double.TryParse(reader.GetAttribute("Y"), NumberStyles.Any, CultureInfo.InvariantCulture, out _y);
reader.Read();
}
#endregion IXmlSerializable Members
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.DateTimeOffset
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// A sample API that tests datetimeoffset usage for date-time
/// </summary>
public partial class SwaggerDateTimeOffsetClient : ServiceClient<SwaggerDateTimeOffsetClient>, ISwaggerDateTimeOffsetClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDateTimeOffsetClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDateTimeOffsetClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerDateTimeOffsetClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerDateTimeOffsetClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://localhost:3000/api");
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PatchProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma warning disable 0420
//
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Security;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.Threading
{
/// <summary>
/// Signals to a <see cref="System.Threading.CancellationToken"/> that it should be canceled.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="T:System.Threading.CancellationTokenSource"/> is used to instantiate a <see
/// cref="T:System.Threading.CancellationToken"/>
/// (via the source's <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property)
/// that can be handed to operations that wish to be notified of cancellation or that can be used to
/// register asynchronous operations for cancellation. That token may have cancellation requested by
/// calling to the source's <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see>
/// method.
/// </para>
/// <para>
/// All members of this class, except <see cref="Dispose">Dispose</see>, are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[ComVisible(false)]
[HostProtection(Synchronization = true, ExternalThreading = true)]
public class CancellationTokenSource : IDisposable
{
// Legal values for m_state
private const int NOT_CANCELED = 0;
private const int NOTIFYING = 1;
private const int NOTIFYING_COMPLETE = 2;
private const int CANNOT_BE_CANCELED = 3;
// Static sources that can be used as the backing source for 'fixed' CancellationTokens that never change state.
private static readonly CancellationTokenSource s_preCanceled = new CancellationTokenSource(true);
private static readonly CancellationTokenSource s_notCancelable = new CancellationTokenSource(false);
private static readonly TimerCallback s_timerCallback = new TimerCallback(TimerCallbackLogic);
private static readonly object s_callbackSentinel = new object();
private volatile int m_state;
private object m_callbacks; // This will be either s_callbackSentinel or a List<CancellationCallbackInfo>.
private bool m_disposed;
private volatile Timer m_timer;
private volatile ManualResetEvent m_kernelEvent;
private volatile Thread m_currentCallbackThread;
private volatile CancellationCallbackInfo m_executingCallback;
#if DISABLED_FOR_LLILUM
private CancellationTokenRegistration[] m_linkingRegistrations; //lazily initialized if required.
private static readonly Action<object> s_LinkedTokenCancelDelegate = new Action<object>(LinkedTokenCancelDelegate);
#endif // DISABLED_FOR_LLILUM
#if DISABLED_FOR_LLILUM
private static void LinkedTokenCancelDelegate(object source)
{
CancellationTokenSource cts = source as CancellationTokenSource;
Contract.Assert(source != null);
cts.Cancel();
}
#endif // DISABLED_FOR_LLILUM
/// <summary>
/// Initializes the <see cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
public CancellationTokenSource()
{
}
/// <summary>
/// Constructs a <see cref="T:System.Threading.CancellationTokenSource"/> that will be canceled after a specified time span.
/// </summary>
/// <param name="delay">The time span to wait before canceling this <see cref="T:System.Threading.CancellationTokenSource"/></param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The exception that is thrown when <paramref name="delay"/> is less than -1 or greater than Int32.MaxValue.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the delay starts during the call to the constructor. When the delay expires,
/// the constructed <see cref="T:System.Threading.CancellationTokenSource"/> is canceled, if it has
/// not been canceled already.
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the delay for the constructed
/// <see cref="T:System.Threading.CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public CancellationTokenSource(TimeSpan delay)
{
long totalMilliseconds = (long)delay.TotalMilliseconds;
if ((totalMilliseconds < -1) || (totalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(delay));
}
m_timer = new Timer(s_timerCallback, this, (int)totalMilliseconds, -1);
}
/// <summary>
/// Constructs a <see cref="T:System.Threading.CancellationTokenSource"/> that will be canceled after a specified time span.
/// </summary>
/// <param name="millisecondsDelay">The time span to wait before canceling this <see cref="T:System.Threading.CancellationTokenSource"/></param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The exception that is thrown when <paramref name="millisecondsDelay"/> is less than -1.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the millisecondsDelay starts during the call to the constructor. When the millisecondsDelay expires,
/// the constructed <see cref="T:System.Threading.CancellationTokenSource"/> is canceled (if it has
/// not been canceled already).
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the millisecondsDelay for the constructed
/// <see cref="T:System.Threading.CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public CancellationTokenSource(int millisecondsDelay)
{
if (millisecondsDelay < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
}
m_timer = new Timer(s_timerCallback, this, millisecondsDelay, -1);
}
/// <summary>
/// Initializes static source with a preset status.
/// </summary>
/// <param name="canceled">Whether the source should be pre-canceled.</param>
private CancellationTokenSource(bool canceled)
{
m_state = canceled ? NOTIFYING_COMPLETE : CANNOT_BE_CANCELED;
}
/// <summary>
/// Gets whether cancellation has been requested for this <see
/// cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see>.
/// </summary>
/// <value>Whether cancellation has been requested for this <see
/// cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see>.</value>
/// <remarks>
/// <para>
/// This property indicates whether cancellation has been requested for this token source, such as
/// due to a call to its
/// <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see> method.
/// </para>
/// <para>
/// If this property returns true, it only guarantees that cancellation has been requested. It does not
/// guarantee that every handler registered with the corresponding token has finished executing, nor
/// that cancellation requests have finished propagating to all registered handlers. Additional
/// synchronization may be required, particularly in situations where related objects are being
/// canceled concurrently.
/// </para>
/// </remarks>
public bool IsCancellationRequested
{
get
{
int state = m_state;
return (state == NOTIFYING) || (state == NOTIFYING_COMPLETE);
}
}
/// <summary>
/// Gets the <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// associated with this <see cref="CancellationTokenSource"/>.
/// </summary>
/// <value>The <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// associated with this <see cref="CancellationTokenSource"/>.</value>
/// <exception cref="T:System.ObjectDisposedException">The token source has been
/// disposed.</exception>
public CancellationToken Token
{
get
{
ThrowIfDisposed();
return new CancellationToken(this);
}
}
internal bool CanBeCanceled
{
get
{
return m_state != CANNOT_BE_CANCELED;
}
}
internal WaitHandle WaitHandle
{
get
{
ThrowIfDisposed();
// fast path if already allocated.
if (m_kernelEvent != null)
{
return m_kernelEvent;
}
// lazy-init the mre.
ManualResetEvent mre = new ManualResetEvent(false);
if (Interlocked.CompareExchange(ref m_kernelEvent, mre, null) != null)
{
((IDisposable)mre).Dispose();
}
// There is a race condition between checking IsCancellationRequested and setting the event.
// However, at this point, the kernel object definitely exists and the cases are:
// 1. if IsCancellationRequested = true, then we will call Set()
// 2. if IsCancellationRequested = false, then Cancel will see that the event exists, and will call Set().
if (IsCancellationRequested)
{
m_kernelEvent.Set();
}
return m_kernelEvent;
}
}
internal bool IsDisposed
{
get
{
return m_disposed;
}
}
/// <summary>
/// Communicates a request for cancellation.
/// </summary>
/// <remarks>
/// <para>
/// The associated <see cref="T:System.Threading.CancellationToken" /> will be
/// notified of the cancellation and will transition to a state where
/// <see cref="System.Threading.CancellationToken.IsCancellationRequested">IsCancellationRequested</see> returns true.
/// Any callbacks or cancelable operations
/// registered with the <see cref="T:System.Threading.CancellationToken"/> will be executed.
/// </para>
/// <para>
/// Cancelable operations and callbacks registered with the token should not throw exceptions.
/// However, this overload of Cancel will aggregate any exceptions thrown into a <see cref="System.AggregateException"/>,
/// such that one callback throwing an exception will not prevent other registered callbacks from being executed.
/// </para>
/// <para>
/// The <see cref="T:System.Threading.ExecutionContext"/> that was captured when each callback was registered
/// will be reestablished when the callback is invoked.
/// </para>
/// </remarks>
/// <exception cref="T:System.AggregateException">An aggregate exception containing all the exceptions thrown
/// by the registered callbacks on the associated <see cref="T:System.Threading.CancellationToken"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">This <see
/// cref="T:System.Threading.CancellationTokenSource"/> has been disposed.</exception>
public void Cancel()
{
Cancel(false);
}
/// <summary>
/// Communicates a request for cancellation.
/// </summary>
/// <remarks>
/// <para>
/// The associated <see cref="T:System.Threading.CancellationToken" /> will be
/// notified of the cancellation and will transition to a state where
/// <see cref="System.Threading.CancellationToken.IsCancellationRequested">IsCancellationRequested</see> returns true.
/// Any callbacks or cancelable operations
/// registered with the <see cref="T:System.Threading.CancellationToken"/> will be executed.
/// </para>
/// <para>
/// Cancelable operations and callbacks registered with the token should not throw exceptions.
/// If <paramref name="throwOnFirstException"/> is true, an exception will immediately propagate out of the
/// call to Cancel, preventing the remaining callbacks and cancelable operations from being processed.
/// If <paramref name="throwOnFirstException"/> is false, this overload will aggregate any
/// exceptions thrown into a <see cref="System.AggregateException"/>,
/// such that one callback throwing an exception will not prevent other registered callbacks from being executed.
/// </para>
/// <para>
/// The <see cref="T:System.Threading.ExecutionContext"/> that was captured when each callback was registered
/// will be reestablished when the callback is invoked.
/// </para>
/// </remarks>
/// <param name="throwOnFirstException">Specifies whether exceptions should immediately propagate.</param>
/// <exception cref="T:System.AggregateException">An aggregate exception containing all the exceptions thrown
/// by the registered callbacks on the associated <see cref="T:System.Threading.CancellationToken"/>.</exception>
/// <exception cref="T:System.ObjectDisposedException">This <see
/// cref="T:System.Threading.CancellationTokenSource"/> has been disposed.</exception>
public void Cancel(bool throwOnFirstException)
{
ThrowIfDisposed();
// Do nothing if we've already been canceled.
if (IsCancellationRequested)
{
return;
}
// If we're the first to signal cancellation, do the main extra work.
if (NOT_CANCELED == Interlocked.CompareExchange(ref m_state, NOTIFYING, NOT_CANCELED))
{
// Dispose of the timer, if any.
m_timer?.Dispose();
// If the kernel event is null at this point, it will be set during lazy construction.
m_kernelEvent?.Set();
m_currentCallbackThread = Thread.CurrentThread;
// - late enlisters to the Canceled event will have their callbacks called immediately in the Register() methods.
// - Callbacks are not called inside a lock.
// - After transition, no more delegates will be added to the
// - list of handlers, and hence it can be consumed and cleared at leisure by ExecuteCallbackHandlers.
ExecuteCallbackHandlers(throwOnFirstException);
#if ENABLE_CONTRACTS
Contract.Assert(IsCancellationCompleted, "Expected cancellation to have finished.");
#endif // ENABLE_CONTRACTS
}
}
/// <summary>
/// Schedules a Cancel operation on this <see cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
/// <param name="delay">The time span to wait before canceling this <see
/// cref="T:System.Threading.CancellationTokenSource"/>.
/// </param>
/// <exception cref="T:System.ObjectDisposedException">The exception thrown when this <see
/// cref="T:System.Threading.CancellationTokenSource"/> has been disposed.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The exception thrown when <paramref name="delay"/> is less than -1 or
/// greater than Int32.MaxValue.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the delay starts during this call. When the delay expires,
/// this <see cref="T:System.Threading.CancellationTokenSource"/> is canceled, if it has
/// not been canceled already.
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the delay for this
/// <see cref="T:System.Threading.CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public void CancelAfter(TimeSpan delay)
{
long totalMilliseconds = (long)delay.TotalMilliseconds;
if ((totalMilliseconds < -1) || (totalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(delay));
}
CancelAfter((int)totalMilliseconds);
}
/// <summary>
/// Schedules a Cancel operation on this <see cref="T:System.Threading.CancellationTokenSource"/>.
/// </summary>
/// <param name="millisecondsDelay">The time span to wait before canceling this <see
/// cref="T:System.Threading.CancellationTokenSource"/>.
/// </param>
/// <exception cref="T:System.ObjectDisposedException">The exception thrown when this <see
/// cref="T:System.Threading.CancellationTokenSource"/> has been disposed.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The exception thrown when <paramref name="millisecondsDelay"/> is less than -1.
/// </exception>
/// <remarks>
/// <para>
/// The countdown for the millisecondsDelay starts during this call. When the millisecondsDelay expires,
/// this <see cref="T:System.Threading.CancellationTokenSource"/> is canceled, if it has
/// not been canceled already.
/// </para>
/// <para>
/// Subsequent calls to CancelAfter will reset the millisecondsDelay for this
/// <see cref="T:System.Threading.CancellationTokenSource"/>, if it has not been
/// canceled already.
/// </para>
/// </remarks>
public void CancelAfter(int millisecondsDelay)
{
ThrowIfDisposed();
if (millisecondsDelay < -1)
{
throw new ArgumentOutOfRangeException(nameof(millisecondsDelay));
}
if (IsCancellationRequested)
{
return;
}
throw new NotImplementedException();
#if DISABLED_FOR_LLILUM
// There is a race condition here as a Cancel could occur between the check of
// IsCancellationRequested and the creation of the timer. This is benign; in the
// worst case, a timer will be created that has no effect when it expires.
// Also, if Dispose() is called right here (after ThrowIfDisposed(), before timer
// creation), it would result in a leaked Timer object (at least until the timer
// expired and Disposed itself). But this would be considered bad behavior, as
// Dispose() is not thread-safe and should not be called concurrently with CancelAfter().
if (m_timer == null)
{
// Lazily initialize the timer in a thread-safe fashion.
// Initially set to "never go off" because we don't want to take a
// chance on a timer "losing" the initialization and then
// cancelling the token before it (the timer) can be disposed.
Timer newTimer = new Timer(s_timerCallback, this, -1, -1);
if (Interlocked.CompareExchange(ref m_timer, newTimer, null) != null)
{
// We did not initialize the timer. Dispose the new timer.
newTimer.Dispose();
}
}
// It is possible that m_timer has already been disposed, so we must do
// the following in a try/catch block.
try
{
m_timer.Change(millisecondsDelay, -1);
}
catch (ObjectDisposedException)
{
// Just eat the exception. There is no other way to tell that
// the timer has been disposed, and even if there were, there
// would not be a good way to deal with the observe/dispose
// race condition.
}
#endif // DISABLED_FOR_LLILUM
}
/// <summary>
/// Creates a <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> that will be in the canceled state
/// when any of the source tokens are in the canceled state.
/// </summary>
/// <param name="token1">The first <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to observe.</param>
/// <param name="token2">The second <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to observe.</param>
/// <returns>A <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> that is linked
/// to the source tokens.</returns>
public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2)
{
throw new NotImplementedException();
#if DISABLED_FOR_LLILUM
CancellationTokenSource linkedTokenSource = new CancellationTokenSource();
bool token2CanBeCanceled = token2.CanBeCanceled;
if (token1.CanBeCanceled)
{
linkedTokenSource.m_linkingRegistrations = new CancellationTokenRegistration[token2CanBeCanceled ? 2 : 1]; // there will be at least 1 and at most 2 linkings
linkedTokenSource.m_linkingRegistrations[0] = token1.InternalRegisterWithoutEC(s_LinkedTokenCancelDelegate, linkedTokenSource);
}
if (token2CanBeCanceled)
{
int index = 1;
if (linkedTokenSource.m_linkingRegistrations == null)
{
linkedTokenSource.m_linkingRegistrations = new CancellationTokenRegistration[1]; // this will be the only linking
index = 0;
}
linkedTokenSource.m_linkingRegistrations[index] = token2.InternalRegisterWithoutEC(s_LinkedTokenCancelDelegate, linkedTokenSource);
}
return linkedTokenSource;
#endif // DISABLED_FOR_LLILUM
}
/// <summary>
/// Creates a <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> that will be in the canceled state
/// when any of the source tokens are in the canceled state.
/// </summary>
/// <param name="tokens">The <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances to observe.</param>
/// <returns>A <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> that is linked
/// to the source tokens.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="tokens"/> is null.</exception>
public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens)
{
throw new NotImplementedException();
#if DISABLED_FOR_LLILUM
if (tokens == null)
{
throw new ArgumentNullException(nameof(tokens));
}
if (tokens.Length == 0)
{
throw new ArgumentException("No tokens were supplied.");
}
// a defensive copy is not required as the array has value-items that have only a single IntPtr field,
// hence each item cannot be null itself, and reads of the payloads cannot be torn.
Contract.EndContractBlock();
CancellationTokenSource linkedTokenSource = new CancellationTokenSource();
linkedTokenSource.m_linkingRegistrations = new CancellationTokenRegistration[tokens.Length];
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].CanBeCanceled)
{
linkedTokenSource.m_linkingRegistrations[i] = tokens[i].InternalRegisterWithoutEC(s_LinkedTokenCancelDelegate, linkedTokenSource);
}
// Empty slots in the array will be default(CancellationTokenRegistration), which are nops to Dispose.
// Based on usage patterns, such occurrences should also be rare, such that it's not worth resizing
// the array and incurring the related costs.
}
return linkedTokenSource;
#endif // DISABLED_FOR_LLILUM
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.CancellationTokenSource" />.
/// </summary>
/// <remarks>
/// This method is not thread-safe for any other concurrent calls.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.Threading.CancellationTokenSource" /> class and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// NOTE: This is intentionally exposed as "protected" rather than "internal" to match CoreCLR's interface.
if (disposing)
{
// We specifically tolerate that a callback can be deregistered after the CTS has been disposed and/or
// concurrently with cts.Dispose(). This is safe without locks because the reg.Dispose() only mutates a
// sparseArrayFragment and then reads from properties of the CTS that are not invalidated by cts.Dispose().
//
// We also tolerate that a callback can be registered after the CTS has been disposed. This is safe
// without locks because InternalRegister is tolerant of m_registeredCallbacksLists becoming null during
// its execution. However, we run the acceptable risk of m_registeredCallbacksLists getting reinitialized
// to non-null if there is a race between Dispose and Register, in which case this instance may
// unnecessarily hold onto a registered callback. But that's no worse than if Dispose wasn't safe to use
// concurrently, as Dispose would never be called, and thus no handlers would be dropped.
if (m_disposed)
{
return;
}
m_timer?.Dispose();
#if DISABLED_FOR_LLILUM
var linkingRegistrations = m_linkingRegistrations;
if (linkingRegistrations != null)
{
m_linkingRegistrations = null; // free for GC once we're done enumerating
for (int i = 0; i < linkingRegistrations.Length; i++)
{
linkingRegistrations[i].Dispose();
}
}
// Registered callbacks are now either complete or will never run, due to guarantees made by ctr.Dispose()
// so we can now perform main disposal work without risk of linking callbacks trying to use this CTS.
m_registeredCallbacksLists = null; // free for GC.
#endif // DISABLED_FOR_LLILUM
if (m_kernelEvent != null)
{
m_kernelEvent.Close(); // the critical cleanup to release an OS handle
m_kernelEvent = null; // free for GC.
}
m_disposed = true;
}
}
/// <summary>
/// Throws an exception if the source has been disposed.
/// </summary>
internal void ThrowIfDisposed()
{
if (m_disposed)
{
throw new ObjectDisposedException(null, "The CancellationTokenSource has been disposed.");
}
}
internal CancellationTokenRegistration RegisterCallback(Action<object> callback, object stateForCallback)
{
CancellationCallbackInfo callbackInfo = TryRegisterCallback(callback, stateForCallback);
if (callbackInfo == null)
{
callback(stateForCallback);
return new CancellationTokenRegistration();
}
return new CancellationTokenRegistration(callbackInfo);
}
/// <summary>
/// Registers a callback object and returns the wrapped callback info.
/// </summary>
/// <returns>Callback information if successful; otherwise null.</returns>
internal CancellationCallbackInfo TryRegisterCallback(Action<object> callback, object stateForCallback)
{
ThrowIfDisposed();
#if ENABLE_CONTRACTS
// The CancellationToken has already checked that the token is cancelable before calling this method.
Contract.Assert(CanBeCanceled, "Cannot register for uncancelable token src");
#endif // ENABLE_CONTRACTS
// If this source has already been canceled, we'll run the callback synchronously and skip the registration.
if (IsCancellationRequested)
{
return null;
}
// Ensure that the callbacks list exists. In the event that we hit a very narrow race, we'll temporarily
// allocate an extra list and drop it. This is acceptable overhead to keep the implementation light.
if (m_callbacks == null)
{
var newCallbacks = new List<CancellationCallbackInfo>(1);
Interlocked.CompareExchange(ref m_callbacks, newCallbacks, null);
}
// Resample m_callbacks in case there was a race above. This is guaranteed to be either a list or the
// s_callbackSentinel token.
var list = m_callbacks as List<CancellationCallbackInfo>;
// If the list is null, we must already be executing callbacks, so execute this one synchronously.
if (list == null)
{
return null;
}
lock (list)
{
// It's possible for invocation to begin right after we snap the list, so check the sentinel again.
if (m_callbacks == s_callbackSentinel)
{
return null;
}
CancellationCallbackInfo callbackInfo = new CancellationCallbackInfo(callback, stateForCallback, this);
list.Add(callbackInfo);
return callbackInfo;
}
}
internal bool TryDeregisterCallback(CancellationCallbackInfo callbackInfo)
{
var callbacks = m_callbacks as List<CancellationCallbackInfo>;
if (callbacks == null)
{
return false;
}
lock (callbacks)
{
// It's possible for invocation to begin right after we snap the list, so check the sentinel again.
if (m_callbacks == s_callbackSentinel)
{
return false;
}
return callbacks.Remove(callbackInfo);
}
}
/// <summary>
/// Invoke the Canceled event.
/// </summary>
/// <remarks>
/// The handlers are invoked synchronously in LIFO order.
/// </remarks>
private void ExecuteCallbackHandlers(bool throwOnFirstException)
{
#if ENABLE_CONTRACTS
Contract.Assert(IsCancellationRequested, "ExecuteCallbackHandlers should only be called after setting IsCancellationRequested->true");
#endif // ENABLE_CONTRACTS
// Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'. This is
// intended to help with nesting scenarios so that child enlisters cancel before their parents.
object callbackObject = Interlocked.Exchange(ref m_callbacks, s_callbackSentinel);
// Trivial case: If we have no callbacks to call, we're done.
if (callbackObject == null)
{
m_state = NOTIFYING_COMPLETE;
return;
}
List<Exception> exceptionList = null;
try
{
#if ENABLE_CONTRACTS
Contract.Assert(callbackObject != s_callbackSentinel, "ExecuteCallbackHandlers should only be called once.");
#endif // ENABLE_CONTRACTS
// We don't want to invoke these callbacks under a lock, so create a copy.
CancellationCallbackInfo[] callbacks;
lock (callbackObject)
{
callbacks = ((List<CancellationCallbackInfo>)callbackObject).ToArray();
}
for (int i = callbacks.Length - 1; i >= 0; --i)
{
try
{
m_executingCallback = callbacks[i];
m_executingCallback.Invoke();
}
catch (Exception ex)
{
if (throwOnFirstException)
{
throw;
}
if (exceptionList == null)
{
exceptionList = new List<Exception>();
}
exceptionList.Add(ex);
}
}
}
finally
{
m_state = NOTIFYING_COMPLETE;
m_executingCallback = null;
m_currentCallbackThread = null;
}
if (exceptionList != null)
{
#if ENABLE_CONTRACTS
Contract.Assert(exceptionList.Count > 0, "Expected exception count > 0");
#endif // ENABLE_CONTRACTS
throw new AggregateException(exceptionList);
}
}
/// <summary>
/// InternalGetStaticSource()
/// </summary>
/// <param name="canceled">Whether the source should be set.</param>
/// <returns>A static source to be shared among multiple tokens.</returns>
internal static CancellationTokenSource InternalGetStaticSource(bool canceled)
{
return canceled ? s_preCanceled : s_notCancelable;
}
/// <summary>
/// Wait for a singlre callback to complete. It's OK to call this method after the callback has already finished,
/// but calling this before the target callback has started is not allowed.
/// </summary>
/// <param name="callbackInfo">The callback to wait for.</param>
internal void WaitForCallbackToComplete(CancellationCallbackInfo callbackInfo)
{
// Design decision: In order to avoid deadlocks, we won't block if the callback is being executed on the
// current thread. It's generally poor form to do this, but it does happen in consumer code.
if ((m_state == NOTIFYING) && (m_currentCallbackThread != Thread.CurrentThread))
{
// It's OK to spin here since callbacks are expected to be relatively fast and calling this wait method
// should be relatively rare.
SpinWait spinWait = new SpinWait();
while (m_executingCallback == callbackInfo)
{
spinWait.SpinOnce();
}
}
}
private static void TimerCallbackLogic(object obj)
{
CancellationTokenSource cts = (CancellationTokenSource)obj;
// Cancel the source; handle a race condition with cts.Dispose()
if (!cts.m_disposed)
{
// There is a small window for a race condition where a cts.Dispose can sneak
// in right here. I'll wrap the cts.Cancel() in a try/catch to proof us
// against this race condition.
try
{
cts.Cancel(); // will take care of disposing of m_timer
}
catch (ObjectDisposedException)
{
// If the ODE was not due to the target cts being disposed, then propagate the ODE.
if (!cts.m_disposed)
{
throw;
}
}
}
}
}
/// <summary>
/// A helper class for collating the various bits of information required to execute
/// cancellation callbacks.
/// </summary>
internal class CancellationCallbackInfo
{
internal readonly Action<object> Callback;
internal readonly object StateForCallback;
internal readonly CancellationTokenSource CancellationTokenSource;
internal CancellationCallbackInfo(
Action<object> callback,
object stateForCallback,
CancellationTokenSource cancellationTokenSource)
{
Callback = callback;
StateForCallback = stateForCallback;
CancellationTokenSource = cancellationTokenSource;
}
[SecuritySafeCritical]
internal void Invoke()
{
Callback(StateForCallback);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using Arcade.Build.FlowStack;
using Arcade.Dsl;
using Arcade.Engine;
using Arcade.Run.Aspects;
using Arcade.Run.Execution;
using Arcade.Run.Messages;
using Arcade.Run.RunVectors;
using Arcade.Tests;
using NUnit.Framework;
using System.Diagnostics;
using System.Reflection;
namespace Windows.Tests.Fixture
{
[TestFixture]
public class RuntimeEngineFixture
{
private FlowConfiguration[] _flows;
private RuntimeEngine _sut;
private RuntimeConfiguration _runtimeConfig;
private readonly ManualResetEvent _mre = new ManualResetEvent(false);
private volatile string _lastTriggerValue;
[SetUp]
public void SetUp()
{
_mre.Reset();
_runtimeConfig = new RuntimeConfiguration();
_runtimeConfig.For<IAmAnInterface>().Use(() => new InterfaceImplementation());
_runtimeConfig.AddAspect(new TracePreExecutionAdvice(Console.WriteLine));
_flows = new[]
{
Flow.StartWith<InitialOutflow, string>("SimpleFlow1")
.ContinueWithEbc<ContinueFlow, string, int>(() => new ContinueFlow())
.ContinueWithEbc<CheckFlow, int, bool>(() => new CheckFlow())
.ContinueWithEbc<SomeOtherFlow, bool, string>(() => new SomeOtherFlow())
.Exit(),
Flow.StartWith<InitialOutflow, string>("ContinuationFlow1")
.ContinueWithEbc<ContinueFlow, string, int>()
.ContinueWithContinuation<IntToStringContinuation, int, string>()
.ContinueWithEbc<ContinueFlow, string, int>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("FunctionFlow1")
.ContinueWithEbc<ContinueFlow, string, int>()
.ContinueWithFunction<int, string>(i => i.ToString())
.ContinueWithEbc<ContinueFlow, string, int>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("SimpleFlow2")
.ContinueWithEbc<CheckFlow, int, bool>()
.ContinueWithEbc<SomeOtherFlow, bool, string>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("BranchFlow1")
.ContinueWithEbc<CheckFlow, int, bool>()
.BranchWhen(b => !b, configurer =>
configurer
.ContinueWithEbc<FlowOutputDependingOnInput, bool, string>(
() =>
new FlowOutputDependingOnInput("On Main", "On Branch"))
.JoinOnExit())
.ContinueWithEbc<FlowOutputDependingOnInput, bool, string>(
() => new FlowOutputDependingOnInput("On Main", "On Branch"))
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("BranchFlow2")
.ContinueWithEbc<CheckFlow, int, bool>()
.BranchWhen(b => b, configurer =>
configurer
.ContinueWithEbc<FlowOutputDependingOnInput, bool, string>(
() =>
new FlowOutputDependingOnInput("On Branch", "On Main"))
.JoinAt("Rejoin"))
.ContinueWithEbc<FlowOutputDependingOnInput, bool, string>(
() => new FlowOutputDependingOnInput("On Branch", "On Main"))
.JoinOrContinueWithEbc<ContinueFlow, string, int>("Rejoin")
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("InvalidBranchFlow")
.ContinueWithEbc<CheckFlow, int, bool>()
.BranchWhen(b => b, configurer =>
configurer.ContinueWithFunction(i => 3.4)
.JoinAt("Rejoin"))
.ContinueWithEbc<FlowOutputDependingOnInput, bool, string>(
() => new FlowOutputDependingOnInput("On Branch", "On Main"))
.JoinOrContinueWithEbc<ContinueFlow, string, int>("Rejoin")
.Exit(),
// Flow.StartWith<InitialOutflow, string>("ScatterGather")
// .ContinueWithEbc<StringSplitter, string, IEnumerable<char>>()
// .Scatter<char, string>(configurer => configurer
// .ContinueWithEbc<CharShifter, char, char>()
// .GatherTo<StringFromChars, char, string>())
// .Exit(),
Flow.StartWith<InitialOutflow, string>("ContinueWithNamedFlow")
.ContinueWithNamedFlow<string, string>("SimpleFlow2")
.ContinueWithEbc<ContinueFlow, string, int>()
.ContinueWithEbc<CheckFlow, int, bool>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("FailingFlow")
.ContinueWithEbc<ContinueFlow, string, int>()
.ContinueWithEbc<FailingFlow, int, string>()
.ContinueWithNamedFlow<string, string>("SimpleFlow2")
.Exit(),
Flow.StartWith<InitialOutflow, string>("SagaFlow1")
.WaitOnPort<string, string>("Port1")
.ContinueWithEbc<ContinueFlow, string, int>()
.ContinueWithEbc<CheckFlow, int, bool>()
.ContinueWithEbc<SomeOtherFlow, bool, string>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("GotoFlow1")
.ContinueWithEbc<ContinueFlow, string, int>()
.JoinOrContinueWithFunction(i => ++i, "Goto")
.BranchWhen(y => y < 12, configurer => configurer
.WaitOnPort<int, int>("Port1")
.JoinAt("Goto"))
.ContinueWithEbc<CheckFlow, int, bool>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("GotoFlow2")
.ContinueWithEbc<ContinueFlow, string, int>()
.JoinOrContinueWithFunction(i => ++i, "Goto")
.BranchWhen(y => y < 10, configurer => configurer
.WaitOnPort<int, int>("Port1")
.JoinAt("Gotoe"))
.ContinueWithEbc<CheckFlow, int, bool>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("StackOverflowFlow")
.JoinOrContinueWithFunction(i => i, "Goto")
.BranchWhen(i => i < 10, configurer =>
configurer
.JoinAt("Goto"))
.ContinueWithEbc<TranslateNumberToLocaleMonth, int, string>()
.ContinueWithEbc<DependingOnInterfaceFlow, string, string>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("DependencyInjectedFlow")
.JoinOrContinueWithFunction(i => i, "Goto")
.BranchWhen(i => i < 10, configurer =>
configurer
.ContinueWithFunction(i => ++i)
.JoinAt("Goto"))
.ContinueWithEbc<TranslateNumberToLocaleMonth, int, string>()
.ContinueWithEbc<DependingOnInterfaceFlow, string, string>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("GotoFlow3")
.JoinOrContinueWithFunction(i => ++i, "Goto")
.ContinueWithFunction(i =>
{
Debug.WriteLine(i.ToString());
return i;
})
.GoToJoinpointIf("Goto", i => i < 10)
.ContinueWithEbc<TranslateNumberToLocaleMonth, int, string>()
.ContinueWithEbc<DependingOnInterfaceFlow, string, string>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("TriggerFlow")
.JoinOrContinueWithFunction(i => ++i, "Goto")
.Trigger("Trigger", i => i.ToString())
.GoToJoinpointIf("Goto", i => i < 10)
.ContinueWithEbc<TranslateNumberToLocaleMonth, int, string>()
.ContinueWithEbc<DependingOnInterfaceFlow, string, string>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("JoinAtTriggerFlow")
.ContinueWithEbc<ContinueFlow, string, int>()
.JoinAtTrigger(i => i.ToString(), "Goto", "Trigger")
.ContinueWithFunction(i => ++i)
.BranchWhen(y => y < 10, configurer => configurer
.ContinueWithFunction(i => i)
.JoinAt("Goto"))
.ContinueWithFunction(i => i)
.Exit(),
Flow.StartWith<InitialOutflow, string>("ScatterGather")
.ContinueWithEbc<StringSplitter, string, IEnumerable<char>>()
.ScatterTo<IEnumerable<char>, char, char, IEnumerable<char>>(configurer => configurer
.ContinueWithEbc<CharShifter, char, char>()
.Gather())
.ContinueWithEbc<StringFromChars, IEnumerable<char>, string>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("StrictFailingScatterGather")
.ContinueWithEbc<StringSplitter, string, IEnumerable<char>>()
.ScatterTo<IEnumerable<char>, char, char, IEnumerable<char>>(configurer => configurer
.ContinueWithContinuation<FailingCharShifter, char, char>()
.Gather())
.ContinueWithEbc<StringFromChars, IEnumerable<char>, string>()
.Exit(),
Flow.StartWith<InitialOutflow, string>("IndulgentFailingScatterGather")
.ContinueWithEbc<StringSplitter, string, IEnumerable<char>>()
.ScatterTo<IEnumerable<char>, char, char, IEnumerable<char>>(configurer => configurer
.ContinueWithContinuation<FailingCharShifter, char, char>()
.Gather(TreatExceptionsWhenGathering.ContinueFlow))
.ContinueWithEbc<StringFromChars, IEnumerable<char>, string>()
.Exit(),
Flow.StartWithFunc<string, string[]>("WordCountingSubflow", str => str.Split(' '))
.ContinueWithFunction(strings => strings.Length)
.Exit(),
Flow.StartWithFunc<string, string[]>("CharCountingSubflow", s => s.Split(' '))
.ScatterTo<string[], string, int, int[]>(configurer => configurer
.ContinueWithFunction(s => s.ToCharArray())
.ContinueWithFunction(c => c.Length)
.Gather())
.ContinueWithContinuation<Aggregator, int[], int>()
.Exit(),
Flow.StartWithFunc<string, string[]>("WordCountingFlow", s => s.Split('.'))
.ScatterTo<string[], string, int, int[]>(configurer => configurer
.ContinueWithNamedFlow<string, int>("WordCountingSubflow")
.Gather())
.ContinueWithContinuation<Aggregator, int[], int>()
.Exit(),
Flow.StartWithFunc<string, string[]>("CharCountingFlow", s => s.Split('.'))
.ScatterTo<string[], string, int, int[]>(configurer => configurer
.ContinueWithNamedFlow<string, int>("CharCountingSubflow")
.Gather())
.ContinueWithContinuation<Aggregator, int[], int>()
.Exit(),
Flow.StartWithFunc<string, string[]>("CharCountingFullFlow", s => s.Split('.'))
.ScatterTo<string[], string, int, int[]>(configurer => configurer
.ContinueWithFunction(s => s.Split(' '))
.ScatterTo<string[], string, int, int[]>(flowConfigurer => flowConfigurer
.ContinueWithFunction(s => s.ToCharArray())
.ContinueWithFunction(c => c.Length)
.Gather())
.ContinueWithContinuation<Aggregator, int[], int>()
.Gather())
.ContinueWithContinuation<Aggregator, int[], int>()
.Exit(),
Flow.StartWithFunc<int[], int[]>("SimpleScatterGather", ints => ints)
.ScatterTo<int[], int, string, string[]>(configurer => configurer
.ContinueWithFunction(i => i.ToString())
.Gather())
.ContinueWithFunction(String.Concat)
.Exit(),
Flow.StartWithFunc<Tuple<int, string>, Tuple<int, string>>("StateStoringFlow", tuple => tuple)
.WriteState(tuple => tuple.Item1, tuple => tuple.Item2)
.ContinueWithFunction(s => s.Length)
.ReadState<int, int, Tuple<int, int>>((i, state) => new Tuple<int, int>(i, state))
.ContinueWithFunction(tuple => tuple.Item1 + tuple.Item2)
.Exit(),
Flow.StartWithFunc<int, int[]>("ScatteredStateStoringFlow", i => new[]{i, i, i, i})
.ScatterTo<int[], int, int, int[]>(configurer => configurer
.WriteState(i => i)
.ReadState<int, int, int>((i, state) => state)
.ContinueWithFunction(i => ++i)
.WriteState(i => i)
.Gather())
.ContinueWithContinuation<Aggregator, int[], int>()
.Exit(),
Flow.StartWithFunc<string, IEnumerable<string>>("StringToIntConvertingFlow", str => str.Split(','))
.WriteState(enumerable => enumerable)
.ScatterTo<IEnumerable<string>, string, int, IEnumerable<int>>(configurer => configurer
.ContinueWithFunction(Int32.Parse)
.Gather())
.ReadState<IEnumerable<int>, IEnumerable<string>, IEnumerable<int>>((ints, strings) => ints)
.Exit(),
Flow.StartWithFunc<int, int>("TimeoutFlow", i => (i+3))
.ContinueWithContinuation<IntToStringContinuation, int, string>()
.ContinueWithContinuation<TimingOutContinuation, string, string>()
.Exit(),
Flow.StartWith<ContinueFlow, string, int>("SyncFunctionsFlow")
.ContinueWithFunction(Functions.IntToString)
//.ContinueWithFunction()
.Exit()
};
_sut = new RuntimeEngine(_runtimeConfig, _flows);
_sut.Start();
}
[Test]
public void SimpleFlowWithTask()
{
var flowName = "SimpleFlow2";
var task = _sut.RunFlow<string, string>("Hello World", flowName);
if(!task.Wait(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within reasonable time.");
}
Assert.AreEqual("Hi from SimpleFlow!", task.Result);
}
[Test]
public void TimeoutBugExposure()
{
var flowName = "TimeoutFlow";
var input = 12;
string result = null;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<int>(flowName);
processor(input);
if (!_mre.WaitOne(3.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(result);
Assert.IsNotNull(exception);
}
_sut.Stop();
}
[Test]
public void ReadStateOnHigherInheritanceLevel()
{
var flowName = "StringToIntConvertingFlow";
var input = "12,13,14,15,16,17";
var result = Enumerable.Empty<int>();
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<IEnumerable<int>>(flowName, ints =>
{
result = ints;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
processor(input);
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(6, result.Count());
}
_sut.Stop();
}
[Test]
public void ScatteringWithNoItemsToScatter()
{
var flowName = "SimpleScatterGather";
var result = "Hello";
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<string>(flowName, s =>
{
result = s;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<int[]>(flowName);
processor(new int[0]);
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(String.Empty, result);
}
_sut.Stop();
}
[Test]
public void StoreIndividualStateInScatterFlows()
{
var flowName = "ScatteredStateStoringFlow";
var result = 0;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<int>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<int>(flowName);
processor(1);
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(8, result);
}
_sut.Stop();
}
[Test]
public void SimpleStateStoringFlow()
{
var flowName = "StateStoringFlow";
var result = 0;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<int>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<Tuple<int, string>>(flowName);
processor(new Tuple<int, string>(10, flowName));
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual((flowName.Length + 10), result);
}
_sut.Stop();
}
[Test]
public void ScatterGatherWithNoErrorDuringScatter()
{
var flowName = "ScatterGather";
var result = String.Empty;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(5.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(9, result.Length);
Assert.AreNotEqual("Scrambled", result);
}
_sut.Stop();
}
[Test]
public void ScatterGatherWithErrorDuringScatterAndIndulgentGatherStrategy()
{
var flowName = "IndulgentFailingScatterGather";
var result = String.Empty;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(4, result.Length);
}
_sut.Stop();
}
[Test]
public void ScatterGatherWithErrorDuringScatterAndStrictGatherStrategy()
{
var flowName = "StrictFailingScatterGather";
var result = String.Empty;
Exception exception = null;
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
}, ex =>
{
Debug.WriteLine("Expected exception!");
exception = ex;
_mre.Set ();
});
_sut.ExecutionException += executionException =>
{
Debug.WriteLine("Execution engine exception!");
Debug.WriteLine(executionException.ToString());
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNotNull(exception);
Assert.AreEqual(String.Empty, result);
Assert.AreEqual(typeof(AggregateException), exception.GetType());
((AggregateException)exception).Handle(x =>
{
Assert.AreEqual(typeof(ScatterFlowFailedException), x.GetType());
Assert.AreEqual(typeof(InvalidOperationException), x.InnerException.GetType());
return true;
});
}
_sut.Stop();
}
[Test]
public void ScatterToSubflow()
{
var flowName = "WordCountingFlow";
var result = 0;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<int>(flowName, i =>
{
result = i;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
var input = "Aurea prima sata est aetas, quae vindice nullo, sponte sua, sine lege fidem rectumque colebat." +
"Poena metusque aberant, nec verba minantia fixo aere legebantur, nec supplex turba timebat iudicis ora sui, sed erant sine vindice tuti." +
"nondum caesa suis, peregrinum ut viseret orbem, montibus in liquidas pinus descenderat undas, nullaque mortales praeter sua litora norant;";
processor(input);
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(55, result);
}
_sut.Stop();
}
[Test]
public void ScatterToNestedNamedSubflowWithTask()
{
var flowName = "CharCountingFlow";
var input = "Aurea prima sata est aetas, quae vindice nullo, sponte sua, sine lege fidem rectumque colebat." +
"Poena metusque aberant, nec verba minantia fixo aere legebantur, nec supplex turba timebat iudicis ora sui, sed erant sine vindice tuti." +
"nondum caesa suis, peregrinum ut viseret orbem, montibus in liquidas pinus descenderat undas, nullaque mortales praeter sua litora norant;";
RuntimeEngineExecutionException exception = null;
_sut.ExecutionException += executionException =>
{
exception = executionException;
};
var cts = new CancellationTokenSource();
var task = _sut.RunFlow<string, int>(input, flowName, cts.Token);
if (!task.Wait(TimeSpan.FromSeconds(2)))
Assert.Fail("Failed to complete within reasonable time!");
else
{
Assert.IsNull(exception);
Assert.AreEqual(314, task.Result);
}
_sut.Stop();
}
[Test]
public void ScatterToNestedNamedSubflowWithCancelledTask()
{
var flowName = "CharCountingFlow";
var input = "Aurea prima sata est aetas, quae vindice nullo, sponte sua, sine lege fidem rectumque colebat." +
"Poena metusque aberant, nec verba minantia fixo aere legebantur, nec supplex turba timebat iudicis ora sui, sed erant sine vindice tuti." +
"nondum caesa suis, peregrinum ut viseret orbem, montibus in liquidas pinus descenderat undas, nullaque mortales praeter sua litora norant;";
RuntimeEngineExecutionException exception = null;
_sut.ExecutionException += executionException =>
{
exception = executionException;
};
var cts = new CancellationTokenSource();
var task = _sut.RunFlow<string, int>(input, flowName, cts.Token);
cts.CancelAfter (10);
try
{
task.Wait(1000);
Assert.IsNull(exception);
}
catch (Exception ex)
{
Assert.IsNotNull(ex);
Debug.WriteLine(ex.ToString());
Assert.AreEqual (typeof(AggregateException), ex.GetType ());
}
_sut.Stop();
}
[Test]
public void TaskedScatterGatherWithErrorDuringScatterAndStrictGatherStrategy()
{
var flowName = "StrictFailingScatterGather";
Exception runtimeException = null;
_sut.ExecutionException += executionException =>
{
runtimeException = executionException;
};
try
{
var task = _sut.RunFlow<string>(flowName);
task.Wait(TimeSpan.FromSeconds(4));
Assert.Fail("No exception?!?!");
}
catch (AggregateException ex)
{
//ex.Handle(exception => { Assert.IsInstanceOf<RuntimeGatherException>(exception);
// return true;
//});
Assert.IsNull(runtimeException);
Assert.Pass();
}
//var task = _sut.RunFlow<string>(flowName);
//var ex = Assert.Catch<AggregateException>(() => { task.Wait(TimeSpan.FromSeconds(2)); });
//ex.Handle (e =>
//{
// Assert.AreEqual(typeof(RuntimeGatherException), e.GetType());
// return true;
//});
//Assert.IsNull(runtimeException);
_sut.Stop();
}
[Test]
public void ScatterToNestedScatterFlow()
{
var flowName = "CharCountingFullFlow";
var result = 0;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<int>(flowName, i =>
{
result = i;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
var input = "Aurea prima sata est aetas, quae vindice nullo, sponte sua, sine lege fidem rectumque colebat." +
"Poena metusque aberant, nec verba minantia fixo aere legebantur, nec supplex turba timebat iudicis ora sui, sed erant sine vindice tuti." +
"nondum caesa suis, peregrinum ut viseret orbem, montibus in liquidas pinus descenderat undas, nullaque mortales praeter sua litora norant;";
processor(input);
if (!_mre.WaitOne(4.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(314, result);
}
_sut.Stop();
}
[Test]
public void ScatterToNestedNamedSubflow()
{
var flowName = "CharCountingFlow";
var result = 0;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<int>(flowName, i =>
{
result = i;
_mre.Set();
});
_sut.ExecutionException += executionException =>
{
exception = executionException;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
var input = "Aurea prima sata est aetas, quae vindice nullo, sponte sua, sine lege fidem rectumque colebat." +
"Poena metusque aberant, nec verba minantia fixo aere legebantur, nec supplex turba timebat iudicis ora sui, sed erant sine vindice tuti." +
"nondum caesa suis, peregrinum ut viseret orbem, montibus in liquidas pinus descenderat undas, nullaque mortales praeter sua litora norant;";
var expected = System.Text.RegularExpressions.Regex.Replace(input, @"\s", "").Length - 2;//account for 2 '.' chars that are split away
processor(input);
if (!_mre.WaitOne(4.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(expected, result);
}
_sut.Stop();
}
[Test]
public void JoinAtTriggerTest()
{
var flowName = "JoinAtTriggerFlow";
_lastTriggerValue = String.Empty;
var result = 0;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<int>(flowName, i =>
{
result = i;
_mre.Set();
});
_sut.ExecutionException += obj =>
{
exception = obj;
_mre.Set();
};
var processor = _sut.CreateProcessor(flowName);
var trigger = _sut.CreateTrigger<string>("*", "Trigger");
trigger.When += str =>
{
_lastTriggerValue = str;
Debug.WriteLine("Current number: " + str);
};
processor();
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual(10, result);
Assert.AreEqual("9", _lastTriggerValue);
}
_sut.Stop();
}
[Test]
public void StarTriggerTest()
{
var flowName = "TriggerFlow";
var counter = 0;
var result = String.Empty;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += obj =>
{
exception = obj;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
var trigger = _sut.CreateTrigger<string>("*", "Trigger");
trigger.When += str =>
{
counter += 1;
Debug.WriteLine("Current number: " + str);
};
processor("Als");
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual("Oktober", result);
Assert.AreEqual(7, counter);
}
_sut.Stop();
}
[Test]
public void TriggerFlowTest()
{
var flowName = "TriggerFlow";
var counter = 0;
var result = String.Empty;
RuntimeEngineExecutionException exception = null;
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
_sut.ExecutionException += obj =>
{
exception = obj;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
var trigger = _sut.CreateTrigger<string>(flowName, "Trigger");
trigger.When += str =>
{
counter += 1;
Debug.WriteLine("Current number: " + str);
};
processor("Als");
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual("Oktober", result);
Assert.AreEqual(7, counter);
}
_sut.Stop();
}
[Test]
public void StandardGotoJoinpointFlow()
{
var flowName = "GotoFlow3";
var result = String.Empty;
RuntimeEngineExecutionException exception = null;
_sut.ExecutionException += (obj) =>
{
exception = obj;
_mre.Set();
};
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Abc");
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual("Oktober", result);
}
_sut.Stop();
}
[Test]
public void AvoidStackOverflowsInConfiguration()
{
var flowName = "StackOverflowFlow";
RuntimeEngineExecutionException exception = null;
_sut.ExecutionException += obj =>
{
exception = obj;
_mre.Set();
};
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hallo");
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNotNull(exception);
Assert.AreEqual(typeof(BuildFlowStackException), exception.InnerException.GetType());
}
_sut.Stop();
}
[Test]
public void DependencyInjectionViaRuntimeConfiguration()
{
var flowName = "DependencyInjectedFlow";
var result = String.Empty;
RuntimeEngineExecutionException exception = null;
_sut.ExecutionException += obj =>
{
exception = obj;
_mre.Set();
};
_sut.WaitForResult<string>(flowName, str =>
{
result = str;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hallo");
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNull(exception);
Assert.AreEqual("Oktober", result);
}
_sut.Stop();
}
[Test]
public void ThrowExceptionWhenBuildingFlowStackFails()
{
var flowName = "GotoFlow2";
RuntimeEngineExecutionException result = null;
_sut.WaitForResult<int>(flowName, i => { });
var processor = _sut.CreateProcessor(flowName);
_sut.ExecutionException += exception => {
result = exception;
_mre.Set();
};
processor();
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNotNull(result);
Assert.AreEqual(typeof(BuildFlowStackException), result.InnerException.GetType());
}
_sut.Stop();
}
[Test]
public void CheckIfBranchAndJoinCanWorkAsGoto()
{
var flowName = "GotoFlow1";
var counter = 0;
var result = false;
_sut.WaitForResult<bool>(flowName, b =>
{
result = b;
_mre.Set();
});
var processor = _sut.CreateProcessor(flowName);
var port = _sut.CreatePort<int, int>(flowName, "Port1");
port.AssignActor((i, action) =>
{
counter++;
action(i);
});
processor();
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsFalse(result);
Assert.AreEqual(2, counter);
}
_sut.Stop();
}
[Test]
public void WhenABranchFlowDoesNotReturnTheRequiredResultType()
{
var flowName = "InvalidBranchFlow";
RuntimeEngineExecutionException result = null;
_sut.WaitForResult<int>(flowName, i => { });
var processor = _sut.CreateProcessor<string>(flowName);
_sut.ExecutionException += exception => {
result = exception;
_mre.Set();
};
processor("Hello");
if (!_mre.WaitOne(2.Seconds()))
{
Assert.Fail("Failed to complete within reasonable time!");
}
else
{
Assert.IsNotNull(result);
Assert.AreEqual(typeof(InputTypeNotMatchingOutputTypeException), result.InnerException.GetType());
}
_sut.Stop();
}
[Test]
public void TestSagaFlow1()
{
var flowName = "SagaFlow1";
int counter = 0;
_sut.WaitForResult<string>(flowName, str => _mre.Set());
var port = _sut.CreatePort<string, string>(flowName, "Port1");
port.AssignActor((s, action) =>
{
counter++;
action("This is my action!");
});
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.AreNotEqual(0, counter);
}
port.Dispose();
_sut.Stop();
}
[Test]
public void TestFunctionFlow()
{
var flowName = "FunctionFlow1";
int result = 0;
_sut.WaitForResult<int>(flowName, i =>
{
result = i;
Debug.Write(Thread.CurrentThread.ManagedThreadId);
_mre.Set();
});
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.AreEqual(1, result);
}
_sut.Stop();
}
[Test]
public void TestContinuationFlow()
{
var flowName = "ContinuationFlow1";
int result = 0;
_sut.WaitForResult<int>(flowName, i =>
{
result = i;
Debug.Write(Thread.CurrentThread.ManagedThreadId);
_mre.Set();
});
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.AreEqual(1, result);
}
_sut.Stop();
}
[Test]
public void TestFailingFlow()
{
FlowFailedMessage result = null;
_sut.RegisterObserver<FlowFailedMessage>(msg =>{
result = msg;
_mre.Set();
});
var processor = _sut.CreateProcessor("FailingFlow");
processor();
if (!_mre.WaitOne(TimeSpan.FromSeconds(10)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.IsNotNull(result);
Assert.AreEqual("FailingFlow", result.RunId.ToString());
Assert.AreEqual(typeof(InvalidOperationException), result.Exception.GetType());
}
_sut.Stop();
}
[Test]
public void RunFlowWithSubflow()
{
var flowName = "ContinueWithNamedFlow";
Debug.Write(Thread.CurrentThread.ManagedThreadId);
bool? result = null;
_sut.WaitForResult<bool>(flowName, b => {
result = b;
Debug.Write(Thread.CurrentThread.ManagedThreadId);
_mre.Set();
});
Exception exception = null;
_sut.ExecutionException += ex =>
{
exception = ex;
_mre.Set();
};
var processor = _sut.CreateProcessor(flowName);
processor();
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.IsNull(exception);
Assert.IsTrue(result.HasValue);
Assert.IsTrue(result.Value);
}
_sut.Stop();
}
// [Test]
// public void ScatterGatherFlow()
// {
// var processor = _sut.CreateProcessor("ScatterGather");
//
// processor();
//
// if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
// {
// Assert.Fail("Failed to complete within 2 seconds");
// }
// else
// {
// Assert.IsNotNull(_result);
// Assert.AreEqual("Strizzi", _result);
// }
// }
[Test]
public void ExecuteBranchFlow2OnBranch()
{
var flowName = "BranchFlow2";
int result = 0;
_sut.WaitForResult<int>(flowName, i => {
result = i;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hello");
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.AreEqual(9, result);
}
_sut.Stop();
}
[Test]
public void ExecuteBranchFlow2OnMain()
{
var flowName = "BranchFlow2";
int result = 0;
_sut.WaitForResult<int>(flowName, i => {
result = i;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hell");
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.AreEqual(7, result);
}
_sut.Stop();
}
[Test]
public void BuildBranchFlow1()
{
var flowName = "BranchFlow1";
string result = String.Empty;
_sut.WaitForResult<string>(flowName, str => {
result = str;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hello");
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.IsFalse(String.IsNullOrEmpty(result));
Assert.AreEqual("On Main", result);
}
_sut.Stop();
}
[Test]
public void RunIntoBranchOfBranchFlow1()
{
var flowName = "BranchFlow1";
string result = String.Empty;
_sut.WaitForResult<string>(flowName, str => {
result = str;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hell");
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.IsFalse(String.IsNullOrEmpty(result));
Assert.AreEqual("On Branch", result);
}
_sut.Stop();
}
[Test]
public void ThrowExceptionIfFlowNotFound()
{
Assert.Throws<FlowNotFoundException>(() => _sut.CreateProcessor("UnknownFlow"));
}
[Test]
public void BuildSimpleFlow1()
{
var flowName = "SimpleFlow1";
var result = String.Empty;
_sut.WaitForResult<string>(flowName, str => {
result = str;
_mre.Set();
});
var processor = _sut.CreateProcessor(flowName);
processor();
if(!_mre.WaitOne(TimeSpan.FromSeconds(10)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.IsFalse(String.IsNullOrEmpty(result));
Assert.AreEqual("Hi from SimpleFlow!", result);
}
}
[Test]
public void BuildSimpleFlow2()
{
var flowName = "SimpleFlow2";
var result = String.Empty;
_sut.WaitForResult<string>(flowName, str => {
result = str;
_mre.Set();
});
var processor = _sut.CreateProcessor<string>(flowName);
processor("Hello");
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Failed to complete within 2 seconds");
}
else
{
Assert.IsFalse(String.IsNullOrEmpty(result));
Assert.AreEqual("Hi from SimpleFlow!", result);
}
}
[Test]
public void MyRuntimeEngineTest1()
{
// var re = new MyRuntimeEngine(new RuntimeConfiguration(), _flows);
// re.Start();
_sut.RegisterObserver<FlowFailedMessage>(evt =>
{
Debug.WriteLine("Observing a failed flow with name: " + evt.RunId+ " reason: " + evt.Exception.ToString());
_mre.Set();
});
_sut.RegisterObserver<FlowCompleteMessage>(evt =>
{
Debug.WriteLine("Observing a completed flow with name: " + evt.RunId + " result: " + evt.Result.Value);
_mre.Set();
});
var processor = _sut.CreateProcessor("SimpleFlow1");
processor();
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Test did not complete within reasonable time!");
} else
{
Assert.Pass();
}
_sut.Stop();
}
[Test]
public void MyRuntimeEngineTest2()
{
_sut.RegisterObserver<FlowFailedMessage>(evt =>
{
Debug.WriteLine("Observing a failed flow with name: " + evt.RunId+ " reason: " + evt.Exception.ToString());
_mre.Set();
});
_sut.RegisterObserver<FlowCompleteMessage>(evt =>
{
Debug.WriteLine("Observing a completed flow with name: " + evt.RunId+ " result: " + evt.Result.Value);
_mre.Set();
});
var processor = _sut.CreateProcessor<string>("SimpleFlow2");
processor("Hello World");
if (!_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
Assert.Fail("Test did not complete within reasonable time!");
} else
{
Assert.Pass();
}
_sut.Stop();
}
[Test]
public void ReflectiveEventWiring()
{
var ebc = new ContinueFlow();
var bc = new BoxingContinuation<int>();
bc.AttachContinuation(x => _mre.Set());
var input = (object)"Hello World";
var evt = ebc.GetType().GetEvent("Result");
var invoker = Delegate.CreateDelegate(evt.EventHandlerType, bc, bc.GetType().GetMethod("Process"));
try
{
evt.AddEventHandler(ebc, invoker);
} catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
_mre.Reset();
ebc.GetType().GetMethod("Process").Invoke(ebc, BindingFlags.InvokeMethod, null, new[]{input}, CultureInfo.InvariantCulture);
if (_mre.WaitOne(TimeSpan.FromSeconds(2)))
{
evt.RemoveEventHandler(ebc, invoker);
Assert.Pass();
}
else
{
Assert.Fail();
}
}
}
public interface ICompletionEvent
{
event Action Completed;
}
public sealed class ResultStore<T> : ICompletionEvent
{
private T _result;
public ResultStore()
{
_result = default(T);
Completed += () => { };
}
public void SetResult(T result)
{
_result = result;
Completed();
}
public T Result { get { return _result; } }
#region ICompletionEvent implementation
public event Action Completed;
#endregion
}
public sealed class CompletionListener : ICompletionEvent
{
public CompletionListener()
{
Completed += () => { };
}
public void SetComplete()
{
Completed();
}
#region ICompletionEvent implementation
public event Action Completed;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
using Moq;
namespace OpenQA.Selenium.Support.Events
{
[TestFixture]
public class EventFiringWebDriverTest
{
private Mock<IWebDriver> mockDriver;
private Mock<IWebElement> mockElement;
private Mock<INavigation> mockNavigation;
private IWebDriver stubDriver;
private StringBuilder log;
[SetUp]
public void Setup()
{
mockDriver = new Mock<IWebDriver>();
mockElement = new Mock<IWebElement>();
mockNavigation = new Mock<INavigation>();
log = new StringBuilder();
}
[Test]
public void ShouldFireNavigationEvents()
{
mockDriver.SetupSet(_ => _.Url = It.Is<string>(x => x == "http://www.get.com"));
mockDriver.Setup(_ => _.Navigate()).Returns(mockNavigation.Object);
mockNavigation.Setup(_ => _.GoToUrl(It.Is<string>(x => x == "http://www.navigate-to.com")));
mockNavigation.Setup(_ => _.Back());
mockNavigation.Setup(_ => _.Forward());
EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object);
firingDriver.Navigating += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_Navigating);
firingDriver.Navigated += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_Navigated);
firingDriver.NavigatingBack += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatingBack);
firingDriver.NavigatedBack += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatedBack);
firingDriver.NavigatingForward += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatingForward);
firingDriver.NavigatedForward += new EventHandler<WebDriverNavigationEventArgs>(firingDriver_NavigatedForward);
firingDriver.Url = "http://www.get.com";
firingDriver.Navigate().GoToUrl("http://www.navigate-to.com");
firingDriver.Navigate().Back();
firingDriver.Navigate().Forward();
string expectedLog = @"Navigating http://www.get.com
Navigated http://www.get.com
Navigating http://www.navigate-to.com
Navigated http://www.navigate-to.com
Navigating back
Navigated back
Navigating forward
Navigated forward
";
mockDriver.VerifySet(x => x.Url = "http://www.get.com", Times.Once);
mockDriver.Verify(x => x.Navigate(), Times.Exactly(3));
mockNavigation.Verify(x => x.GoToUrl("http://www.navigate-to.com"), Times.Once);
mockNavigation.Verify(x => x.Back(), Times.Once);
mockNavigation.Verify(x => x.Forward(), Times.Once);
Assert.AreEqual(expectedLog, log.ToString());
}
[Test]
public void ShouldFireClickEvent()
{
mockDriver.Setup(_ => _.FindElement(It.IsAny<By>())).Returns(mockElement.Object);
mockElement.Setup(_ => _.Click());
EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object);
firingDriver.ElementClicking += new EventHandler<WebElementEventArgs>(firingDriver_ElementClicking);
firingDriver.ElementClicked += new EventHandler<WebElementEventArgs>(firingDriver_ElementClicked);
firingDriver.FindElement(By.Name("foo")).Click();
string expectedLog = @"Clicking
Clicked
";
Assert.AreEqual(expectedLog, log.ToString());
}
[Test]
public void ShouldFireValueChangedEvent()
{
mockDriver.Setup(_ => _.FindElement(It.IsAny<By>())).Returns(mockElement.Object);
mockElement.Setup(_ => _.Clear());
mockElement.Setup(_ => _.SendKeys(It.IsAny<string>()));
EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object);
firingDriver.ElementValueChanging += (sender, e) => log.AppendFormat("ValueChanging '{0}'", e.Value).AppendLine();
firingDriver.ElementValueChanged += (sender, e) => log.AppendFormat("ValueChanged '{0}'", e.Value).AppendLine();
var element = firingDriver.FindElement(By.Name("foo"));
element.Clear();
element.SendKeys("Dummy Text");
string expectedLog = @"ValueChanging ''
ValueChanged ''
ValueChanging 'Dummy Text'
ValueChanged 'Dummy Text'
";
Assert.AreEqual(expectedLog, log.ToString());
}
[Test]
public void ShouldFireFindByEvent()
{
IList<IWebElement> driverElements = new List<IWebElement>();
IList<IWebElement> subElements = new List<IWebElement>();
Mock<IWebElement> ignored = new Mock<IWebElement>();
mockDriver.Setup(_ => _.FindElement(It.Is<By>(x => x.Equals(By.Id("foo"))))).Returns(mockElement.Object);
mockElement.Setup(_ => _.FindElement(It.IsAny<By>())).Returns(ignored.Object);
mockElement.Setup(_ => _.FindElements(It.Is<By>(x => x.Equals(By.Name("xyz"))))).Returns(new ReadOnlyCollection<IWebElement>(driverElements));
mockDriver.Setup(_ => _.FindElements(It.Is<By>(x => x.Equals(By.XPath("//link[@type = 'text/css']"))))).Returns(new ReadOnlyCollection<IWebElement>(subElements));
EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object);
firingDriver.FindingElement += new EventHandler<FindElementEventArgs>(firingDriver_FindingElement);
firingDriver.FindElementCompleted += new EventHandler<FindElementEventArgs>(firingDriver_FindElementCompleted);
IWebElement element = firingDriver.FindElement(By.Id("foo"));
element.FindElement(By.LinkText("bar"));
element.FindElements(By.Name("xyz"));
firingDriver.FindElements(By.XPath("//link[@type = 'text/css']"));
string expectedLog = @"FindingElement from IWebDriver By.Id: foo
FindElementCompleted from IWebDriver By.Id: foo
FindingElement from IWebElement By.LinkText: bar
FindElementCompleted from IWebElement By.LinkText: bar
FindingElement from IWebElement By.Name: xyz
FindElementCompleted from IWebElement By.Name: xyz
FindingElement from IWebDriver By.XPath: //link[@type = 'text/css']
FindElementCompleted from IWebDriver By.XPath: //link[@type = 'text/css']
";
Assert.AreEqual(expectedLog, log.ToString());
}
[Test]
public void ShouldCallListenerOnException()
{
NoSuchElementException exception = new NoSuchElementException("argh");
mockDriver.Setup(_ => _.FindElement(It.Is<By>(x => x.Equals(By.Id("foo"))))).Throws(exception);
EventFiringWebDriver firingDriver = new EventFiringWebDriver(mockDriver.Object);
firingDriver.ExceptionThrown += new EventHandler<WebDriverExceptionEventArgs>(firingDriver_ExceptionThrown);
try
{
firingDriver.FindElement(By.Id("foo"));
Assert.Fail("Expected exception to be propogated");
}
catch (NoSuchElementException)
{
// Fine
}
Assert.IsTrue(log.ToString().Contains(exception.Message));
}
[Test]
public void ShouldUnwrapElementArgsWhenCallingScripts()
{
Mock<IExecutingDriver> executingDriver = new Mock<IExecutingDriver>();
executingDriver.Setup(_ => _.FindElement(It.Is<By>(x => x.Equals(By.Id("foo"))))).Returns(mockElement.Object);
executingDriver.Setup(_ => _.ExecuteScript(It.IsAny<string>(), It.IsAny<object[]>())).Returns("foo");
EventFiringWebDriver testedDriver = new EventFiringWebDriver(executingDriver.Object);
IWebElement element = testedDriver.FindElement(By.Id("foo"));
try
{
testedDriver.ExecuteScript("foo", element);
}
catch (Exception e)
{
// This is the error we're trying to fix
throw e;
}
}
[Test]
public void ShouldBeAbleToWrapSubclassesOfSomethingImplementingTheWebDriverInterface()
{
// We should get this far
EventFiringWebDriver testDriver = new EventFiringWebDriver(new ChildDriver());
}
[Test]
public void ShouldBeAbleToAccessWrappedInstanceFromEventCalls()
{
stubDriver = new StubDriver();
EventFiringWebDriver testDriver = new EventFiringWebDriver(stubDriver);
StubDriver wrapped = ((IWrapsDriver)testDriver).WrappedDriver as StubDriver;
Assert.AreEqual(stubDriver, wrapped);
testDriver.Navigating += new EventHandler<WebDriverNavigationEventArgs>(testDriver_Navigating);
testDriver.Url = "http://example.org";
}
void testDriver_Navigating(object sender, WebDriverNavigationEventArgs e)
{
Assert.AreEqual(e.Driver, stubDriver);
}
void firingDriver_ExceptionThrown(object sender, WebDriverExceptionEventArgs e)
{
log.AppendLine(e.ThrownException.Message);
}
void firingDriver_FindingElement(object sender, FindElementEventArgs e)
{
log.Append("FindingElement from ").Append(e.Element == null ? "IWebDriver " : "IWebElement ").AppendLine(e.FindMethod.ToString());
}
void firingDriver_FindElementCompleted(object sender, FindElementEventArgs e)
{
log.Append("FindElementCompleted from ").Append(e.Element == null ? "IWebDriver " : "IWebElement ").AppendLine(e.FindMethod.ToString());
}
void firingDriver_ElementClicking(object sender, WebElementEventArgs e)
{
log.AppendLine("Clicking");
}
void firingDriver_ElementClicked(object sender, WebElementEventArgs e)
{
log.AppendLine("Clicked");
}
void firingDriver_Navigating(object sender, WebDriverNavigationEventArgs e)
{
log.Append("Navigating ").Append(e.Url).AppendLine();
}
void firingDriver_Navigated(object sender, WebDriverNavigationEventArgs e)
{
log.Append("Navigated ").Append(e.Url).AppendLine();
}
void firingDriver_NavigatingBack(object sender, WebDriverNavigationEventArgs e)
{
log.AppendLine("Navigating back");
}
void firingDriver_NavigatedBack(object sender, WebDriverNavigationEventArgs e)
{
log.AppendLine("Navigated back");
}
void firingDriver_NavigatingForward(object sender, WebDriverNavigationEventArgs e)
{
log.AppendLine("Navigating forward");
}
void firingDriver_NavigatedForward(object sender, WebDriverNavigationEventArgs e)
{
log.AppendLine("Navigated forward");
}
public interface IExecutingDriver : IWebDriver, IJavaScriptExecutor
{
}
public class ChildDriver : StubDriver
{
}
}
}
| |
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\Collision
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:37
#region Using directives
using DungeonQuest.Helpers;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
#endregion
namespace DungeonQuest.Collision
{
/// <summary>
/// Collision mesh
/// </summary>
class CollisionGeometry
{
#region Constants
/// <summary>
/// Default Extension for Collada files exported with 3ds max.
/// </summary>
public const string ColladaDirectory = "Content\\Models",
ColladaExtension = "DAE";
#endregion
#region Variables
/// <summary>
/// Vectors for this mesh, we don't care about anything else!
/// </summary>
private Vector3[] vectors;
/// <summary>
/// Indices for all the triangles. Should be optimized together with
/// the vectors (no duplicates there) for the best performance.
/// This array is just used for loading, for processing the collision
/// we use the collision faces and the collision tree!
/// </summary>
private int[] indices;
/// <summary>
/// Collision mesh faces
/// </summary>
CollisionPolygon[] faces;
/// <summary>
/// Collision tree with meshes faces
/// </summary>
CollisionHelper tree;
#endregion
#region Constructor
/// <summary>
/// Create a collision mesh from a collada file
/// </summary>
/// <param name="setName">Set name</param>
public CollisionGeometry(string setName)
{
// Set name to identify this model and build the filename
string filename = Path.Combine(ColladaDirectory,
StringHelper.ExtractFilename(setName, true) + "." +
ColladaExtension);
// Load file
Stream file = File.OpenRead(filename);
string colladaXml = new StreamReader(file).ReadToEnd();
XmlNode colladaFile = XmlHelper.LoadXmlFromText(colladaXml);
// Load mesh (vectors and indices)
LoadMesh(colladaFile);
// Close file, we are done.
file.Close();
} // CollisionMesh(setName)
#endregion
#region Load collada matrix helper method
/// <summary>
/// Create matrix from collada float value array. The matrices in collada
/// are stored differently from the xna format (row based instead of
/// columns).
/// </summary>
/// <param name="mat">mat</param>
/// <returns>Matrix</returns>
protected Matrix LoadColladaMatrix(float[] mat, int offset)
{
return new Matrix(
mat[offset + 0], mat[offset + 4], mat[offset + 8], mat[offset + 12],
mat[offset + 1], mat[offset + 5], mat[offset + 9], mat[offset + 13],
mat[offset + 2], mat[offset + 6], mat[offset + 10], mat[offset + 14],
mat[offset + 3], mat[offset + 7], mat[offset + 11], mat[offset + 15]);
} // LoadColladaMatrix(mat, offset)
/// <summary>
/// Only scale transformation down to globalScaling, left rest of
/// the matrix intact. This is required for rendering because all the
/// models have their own scaling!
/// </summary>
/// <param name="mat">Matrix</param>
/// <returns>Matrix</returns>
protected Matrix OnlyScaleTransformation(Matrix mat)
{
mat.Translation = mat.Translation * globalScaling;
return mat;
} // OnlyScaleTransformation(mat)
/// <summary>
/// Only scale transformation inverse
/// </summary>
/// <param name="mat">Matrix</param>
/// <returns>Matrix</returns>
protected Matrix OnlyScaleTransformationInverse(Matrix mat)
{
mat.Translation = mat.Translation / globalScaling;
return mat;
} // OnlyScaleTransformationInverse(mat)
#endregion
#region Load mesh
/// <summary>
/// Load mesh, must be called after we got all bones. Will also create
/// the vertex and index buffers and optimize the vertices as much as
/// we can.
/// </summary>
/// <param name="colladaFile">Collada file</param>
private void LoadMesh(XmlNode colladaFile)
{
XmlNode geometrys =
XmlHelper.GetChildNode(colladaFile, "library_geometries");
if (geometrys == null)
throw new InvalidOperationException(
"library_geometries node not found in collision file");
foreach (XmlNode geometry in geometrys)
if (geometry.Name == "geometry")
{
// Load everything from the mesh node
LoadMeshGeometry(colladaFile,
XmlHelper.GetChildNode(colladaFile, "mesh"),
XmlHelper.GetXmlAttribute(geometry, "name"));
// Optimize vertices first and build index buffer from that!
indices = OptimizeVertexBuffer();
// Copy and create everything to CollisionFace
faces = new CollisionPolygon[indices.Length / 3];
for (int i = 0; i < indices.Length / 3; i++)
{
faces[i] = new CollisionPolygon(i * 3, indices, 0, vectors);
} // for (int)
BoxHelper box = new BoxHelper(float.MaxValue, -float.MaxValue);
for (int i = 0; i < vectors.Length; i++)
box.AddPoint(vectors[i]);
uint subdivLevel = 4; // max 8^6 nodes
tree = new CollisionHelper(box, subdivLevel);
for (int i = 0; i < faces.Length; i++)
tree.AddElement(faces[i]);
// Get outa here, we currently only support one single mesh!
return;
} // foreach if (geometry.Name)
} // LoadMesh(colladaFile)
/// <summary>
/// Helpers to remember how we can reuse vertices for OptimizeVertexBuffer.
/// See below for more details.
/// </summary>
int[] reuseVertexPositions;
/// <summary>
/// Reverse reuse vertex positions, this one is even more important because
/// this way we can get a list of used vertices for a shared vertex pos.
/// </summary>
List<int>[] reverseReuseVertexPositions;
/// <summary>
/// Global scaling we get for importing the mesh and all positions.
/// This is important because 3DS max might use different units than we are.
/// </summary>
protected float globalScaling = 1.0f;
/// <summary>
/// Object matrix. Not really needed here.
/// </summary>
Matrix objectMatrix = Matrix.Identity;
/// <summary>
/// Load mesh geometry
/// </summary>
/// <param name="geometry"></param>
private void LoadMeshGeometry(XmlNode colladaFile,
XmlNode meshNode, string meshName)
{
#region Load all source nodes
Dictionary<string, List<float>> sources = new Dictionary<string,
List<float>>();
foreach (XmlNode node in meshNode)
{
if (node.Name != "source")
continue;
XmlNode floatArray = XmlHelper.GetChildNode(node, "float_array");
List<float> floats = new List<float>(
StringHelper.ConvertStringToFloatArray(floatArray.InnerText));
// Fill the array up
int count = Convert.ToInt32(XmlHelper.GetXmlAttribute(floatArray,
"count"), NumberFormatInfo.InvariantInfo);
while (floats.Count < count)
floats.Add(0.0f);
sources.Add(XmlHelper.GetXmlAttribute(node, "id"), floats);
} // foreach (node)
#endregion
#region Vertices
// Also add vertices node, redirected to position node into sources
XmlNode verticesNode = XmlHelper.GetChildNode(meshNode, "vertices");
XmlNode posInput = XmlHelper.GetChildNode(verticesNode, "input");
if (XmlHelper.GetXmlAttribute(posInput, "semantic").ToLower(
CultureInfo.InvariantCulture) != "position")
throw new InvalidOperationException(
"unsupported feature found in collada \"vertices\" node");
string verticesValueName = XmlHelper.GetXmlAttribute(posInput,
"source").Substring(1);
sources.Add(XmlHelper.GetXmlAttribute(verticesNode, "id"),
sources[verticesValueName]);
#endregion
#region Get the global scaling from the exported units to meters!
XmlNode unitNode = XmlHelper.GetChildNode(
XmlHelper.GetChildNode(colladaFile, "asset"), "unit");
globalScaling = Convert.ToSingle(
XmlHelper.GetXmlAttribute(unitNode, "meter"),
NumberFormatInfo.InvariantInfo);
#endregion
#region Get the object matrix (its in the visual_scene node at the end)
XmlNode sceneStuff = XmlHelper.GetChildNode(
XmlHelper.GetChildNode(colladaFile, "library_visual_scenes"),
"visual_scene");
if (sceneStuff == null)
throw new InvalidOperationException(
"library_visual_scenes node not found in collision file");
// Search for the node with the name of this geometry.
foreach (XmlNode node in sceneStuff)
if (node.Name == "node" &&
XmlHelper.GetXmlAttribute(node, "name") == meshName &&
XmlHelper.GetChildNode(node, "matrix") != null)
{
// Get the object matrix
objectMatrix = LoadColladaMatrix(
StringHelper.ConvertStringToFloatArray(
XmlHelper.GetChildNode(node, "matrix").InnerText), 0) *
Matrix.CreateScale(globalScaling);
break;
} // foreach if (node.Name)
#endregion
#region Construct all triangle polygons from the vertex data
// Construct and generate vertices lists. Every 3 vertices will
// span one triangle polygon, but everything is optimized later.
foreach (XmlNode trianglenode in meshNode)
{
if (trianglenode.Name != "triangles")
continue;
// Find data source nodes
XmlNode positionsnode = XmlHelper.GetChildNode(trianglenode,
"semantic", "VERTEX");
// All the rest is ignored
// Get the data of the sources
List<float> positions = sources[XmlHelper.GetXmlAttribute(
positionsnode, "source").Substring(1)];
// Find the Offsets
int positionsoffset = Convert.ToInt32(XmlHelper.GetXmlAttribute(
positionsnode, "offset"), NumberFormatInfo.InvariantInfo);
// Get the indexlist
XmlNode p = XmlHelper.GetChildNode(trianglenode, "p");
int[] pints = StringHelper.ConvertStringToIntArray(p.InnerText);
int trianglecount = Convert.ToInt32(XmlHelper.GetXmlAttribute(
trianglenode, "count"), NumberFormatInfo.InvariantInfo);
// The number of ints that form one vertex:
int vertexcomponentcount = pints.Length / trianglecount / 3;
// Construct data
// Initialize reuseVertexPositions and reverseReuseVertexPositions
// to make it easier to use them below
reuseVertexPositions = new int[trianglecount * 3];
reverseReuseVertexPositions = new List<int>[positions.Count / 3];
for (int i = 0; i < reverseReuseVertexPositions.Length; i++)
reverseReuseVertexPositions[i] = new List<int>();
vectors = new Vector3[trianglecount * 3];
// We have to use int indices here because we often have models
// with more than 64k triangles (even if that gets optimized later).
for (int i = 0; i < trianglecount * 3; i++)
{
// Position
int pos = pints[i * vertexcomponentcount + positionsoffset] * 3;
Vector3 position = new Vector3(
positions[pos], positions[pos + 1], positions[pos + 2]);
// For the cave mesh we are not going to use a world matrix,
// Just scale everything correctly right here!
position *= globalScaling;
// Set the vertex
vectors[i] = position;
// Remember pos for optimizing the vertices later more easily.
reuseVertexPositions[i] = pos / 3;
reverseReuseVertexPositions[pos / 3].Add(i);
} // for (int)
// Only support one mesh for now, get outta here.
return;
} // foreach (trianglenode)
throw new InvalidOperationException(
"No mesh found in this collada file, unable to continue!");
#endregion
} // LoadMeshGeometry(colladaFile, meshNode, meshName)
#endregion
#region Optimize vertex buffer
#region Flip index order
/// <summary>
/// Little helper method to flip indices from 0, 1, 2 to 0, 2, 1.
/// This way we can render with CullClockwiseFace (default for XNA).
/// </summary>
/// <param name="oldIndex"></param>
/// <returns></returns>
private int FlipIndexOrder(int oldIndex)
{
int polygonIndex = oldIndex % 3;
if (polygonIndex == 0)
return oldIndex;
else if (polygonIndex == 1)
return oldIndex + 1;
else //if (polygonIndex == 2)
return oldIndex - 1;
} // FlipIndexOrder(oldIndex)
#endregion
#region OptimizeVertexBuffer
/// <summary>
/// Optimize vertex buffer. Note: The vertices list array will be changed
/// and shorted quite a lot here. We are also going to create the indices
/// for the index buffer here (we don't have them yet, they are just
/// sequential from the loading process above).
///
/// Note: This method is highly optimized for speed, it performs
/// hundred of times faster than OptimizeVertexBufferSlow, see below!
/// </summary>
/// <returns>int array for the optimized indices</returns>
private int[] OptimizeVertexBuffer()
{
List<Vector3> newVertices =
new List<Vector3>();
List<int> newIndices = new List<int>();
// Helper to only search already added newVertices and for checking the
// old position indices by transforming them into newVertices indices.
List<int> newVerticesPositions = new List<int>();
// Go over all vertices (indices are currently 1:1 with the vertices)
for (int num = 0; num < vectors.Length; num++)
{
// Get current vertex
Vector3 currentVertex = vectors[num];
bool reusedExistingVertex = false;
// Find out which position index was used, then we can compare
// all other vertices that share this position. They will not
// all be equal, but some of them can be merged.
int sharedPos = reuseVertexPositions[num];
foreach (int otherVertexIndex in reverseReuseVertexPositions[sharedPos])
{
// Only check the indices that have already been added!
if (otherVertexIndex != num &&
// Make sure we already are that far in our new index list
otherVertexIndex < newIndices.Count &&
// And make sure this index has been added to newVertices yet!
newIndices[otherVertexIndex] < newVertices.Count &&
// Then finally compare vertices (this call is slow, but thanks to
// all the other optimizations we don't have to call it that often)
currentVertex == newVertices[newIndices[otherVertexIndex]])
{
// Reuse the existing vertex, don't add it again, just
// add another index for it!
newIndices.Add(newIndices[otherVertexIndex]);
reusedExistingVertex = true;
break;
} // if (otherVertexIndex)
} // foreach (otherVertexIndex)
if (reusedExistingVertex == false)
{
// Add the currentVertex and set it as the current index
newIndices.Add(newVertices.Count);
newVertices.Add(currentVertex);
} // if (reusedExistingVertex)
} // for (num)
// Finally flip order of all triangles to allow us rendering
// with CullCounterClockwiseFace (default for XNA) because all the data
// is in CullClockwiseFace format right now!
for (int num = 0; num < newIndices.Count / 3; num++)
{
int swap = newIndices[num * 3 + 1];
newIndices[num * 3 + 1] = newIndices[num * 3 + 2];
newIndices[num * 3 + 2] = swap;
} // for (num)
// Reassign the vertices, we might have deleted some duplicates!
vectors = newVertices.ToArray();
// And return index list for the caller
return newIndices.ToArray();
} // OptimizeVertexBuffer()
#endregion
#endregion
#region Collision testing
/// <summary>
/// Point intersect
/// </summary>
/// <param name="ray_start">Ray _start</param>
/// <param name="ray_end">Ray _end</param>
/// <param name="distance">Intersect _distance</param>
/// <param name="collisionPosition">Intersect _position</param>
/// <param name="collisionNormal">Intersect _normal</param>
/// <returns>Bool</returns>
public bool DoesRayIntersect(Vector3 ray_start, Vector3 ray_end,
out float distance, out Vector3 collisionPosition,
out Vector3 collisionNormal)
{
return tree.DoesRayIntersect(
Ray.FromStartAndEnd(ray_start, ray_end), vectors,
out distance, out collisionPosition, out collisionNormal);
} // DoesRayIntersect(ray_start, ray_end, distance)
/// <summary>
/// Box intersect
/// </summary>
/// <param name="box">Box</param>
/// <param name="ray_start">Ray _start</param>
/// <param name="ray_end">Ray _end</param>
/// <param name="distance">Intersect _distance</param>
/// <param name="collisionPosition">Intersect _position</param>
/// <param name="collisionNormal">Intersect _normal</param>
/// <returns>Bool</returns>
public bool DoesBoxIntersect(BoxHelper box, Ray ray, out float distance,
out Vector3 collisionPosition, out Vector3 collisionNormal)
{
return tree.DoesBoxIntersect(box, ray, vectors,
out distance, out collisionPosition, out collisionNormal);
} // DoesBoxIntersect(box, ray_start, ray_end)
/// <summary>
/// Point move
/// </summary>
/// <param name="pointStart">Point _start</param>
/// <param name="pointEnd">Point _end</param>
/// <param name="frictionFactor">Friction _factor</param>
/// <param name="bumpFactor">Bump mapping _factor</param>
/// <param name="recurseLevel">Recurse _level</param>
/// <param name="pointResult">Point _result</param>
/// <param name="velocityResult">Velocity _result</param>
public void PointMove(Vector3 pointStart, Vector3 pointEnd,
float frictionFactor, float bumpFactor, uint recurseLevel,
out Vector3 pointResult, ref Vector3 velocityResult,
out Vector3 polyPoint)
{
tree.PointMove(pointStart, pointEnd, vectors, frictionFactor,
bumpFactor, recurseLevel, out pointResult, ref velocityResult,
out polyPoint);
} // PointMove(pointStart, pointEnd, frictionFactor)
/// <summary>
/// Box move
/// </summary>
/// <param name="box">Box</param>
/// <param name="pointStart">Point _start</param>
/// <param name="pointEnd">Point _end</param>
/// <param name="frictionFactor">Friction _factor</param>
/// <param name="bumpFactor">Bump mapping _factor</param>
/// <param name="recurseLevel">Recurse _level</param>
/// <param name="pointResult">Point _result</param>
/// <param name="velocityResult">Velocity _result</param>
public void BoxMove(BoxHelper box, Vector3 pointStart,
Vector3 pointEnd, float frictionFactor, float bumpFactor,
uint recurseLevel, out Vector3 pointResult, ref Vector3 velocityResult)
{
tree.BoxMove(box, pointStart, pointEnd, vectors, frictionFactor,
bumpFactor, recurseLevel, out pointResult, ref velocityResult);
} // BoxMove(box, pointStart, pointEnd)
/// <summary>
/// Get elements
/// </summary>
/// <param name="b">B</param>
/// <param name="e">E</param>
public void GetElements(BoxHelper b, List<BaseCollisionObject> e)
{
tree.GetElements(b, e);
} // GetElements(b, e)
#endregion
#region Unit Testing
#if DEBUG
//TODO?
#endif
#endregion
} // class CollisionMesh
} // namespace DungeonQuest.Collision
| |
// 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;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Net.Tests
{
public class WebUtilityTests
{
// HtmlEncode + HtmlDecode
public static IEnumerable<object[]> HtmlDecode_TestData()
{
yield return new object[] { "Hello! '"<&>\u2665♥\u00E7çç", "Hello! '\"<&>\u2665\u2665\u00E7\u00E7\u00E7" };
yield return new object[] { "Hello, world! \"<>\u2665\u00E7", "Hello, world! \"<>\u2665\u00E7" }; // No special chars
yield return new object[] { null, null };
yield return new object[] { "𣎴", char.ConvertFromUtf32(144308) };
}
[Theory]
[MemberData(nameof(HtmlDecode_TestData))]
public static void HtmlDecode(string value, string expected)
{
Assert.Equal(expected, WebUtility.HtmlDecode(value));
}
public static IEnumerable<object[]> HtmlEncode_TestData()
{
// Single quotes need to be encoded as ' rather than ' since ' is valid both for
// HTML and XHTML, but ' is valid only for XHTML.
// For more info: http://fishbowl.pastiche.org/2003/07/01/the_curse_of_apos/
yield return new object[] { "'", "'" };
yield return new object[] { "Hello! '\"<&>\u2665\u00E7 World", "Hello! '"<&>\u2665ç World" };
yield return new object[] { null, null };
yield return new object[] { "Hello, world!", "Hello, world!" }; // No special chars
yield return new object[] { char.ConvertFromUtf32(144308), "𣎴" }; // Default strict settings
}
[Theory]
[MemberData(nameof(HtmlEncode_TestData))]
public static void HtmlEncode(string value, string expected)
{
Assert.Equal(expected, WebUtility.HtmlEncode(value));
}
// Shared test data for UrlEncode + Decode and their ToBytes counterparts
public static IEnumerable<Tuple<string, string>> UrlDecode_SharedTestData()
{
// Escaping needed - case insensitive hex
yield return Tuple.Create("%2F%5C%22%09Hello!+%E2%99%A5%3F%2F%5C%22%09World!+%E2%99%A5%3F%E2%99%A5", "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665");
yield return Tuple.Create("%2f%5c%22%09Hello!+%e2%99%a5%3f%2f%5c%22%09World!+%e2%99%a5%3F%e2%99%a5", "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665");
// Surrogate pair
yield return Tuple.Create("%F0%90%8F%BF", "\uD800\uDFFF");
yield return Tuple.Create("\uD800\uDFFF", "\uD800\uDFFF");
// Spaces
yield return Tuple.Create("abc+def", "abc def");
yield return Tuple.Create("++++", " ");
yield return Tuple.Create(" ", " ");
// No escaping needed
yield return Tuple.Create("abc", "abc");
yield return Tuple.Create("Hello, world", "Hello, world");
yield return Tuple.Create("\u1234\u2345", "\u1234\u2345");
yield return Tuple.Create("abc\u1234\u2345def\u1234", "abc\u1234\u2345def\u1234");
// Invalid percent encoding
yield return Tuple.Create("%", "%");
yield return Tuple.Create("%A", "%A");
yield return Tuple.Create("%G1", "%G1");
yield return Tuple.Create("%1G", "%1G");
}
public static IEnumerable<Tuple<string, string>> UrlEncode_SharedTestData()
{
// Recent change brings function inline with RFC 3986 to return hex-encoded chars in uppercase
yield return Tuple.Create("/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665", "%2F%5C%22%09Hello!+%E2%99%A5%3F%2F%5C%22%09World!+%E2%99%A5%3F%E2%99%A5");
yield return Tuple.Create("'", "%27");
yield return Tuple.Create("\uD800\uDFFF", "%F0%90%8F%BF"); // Surrogate pairs should be encoded as 4 bytes together
// TODO: Uncomment this block out when dotnet/corefx#7166 is fixed.
/*
// Tests for stray surrogate chars (all should be encoded as U+FFFD)
// Relevant GitHub issue: dotnet/corefx#7036
yield return Tuple.Create("\uD800", "%EF%BF%BD"); // High surrogate
yield return Tuple.Create("\uDC00", "%EF%BF%BD"); // Low surrogate
yield return Tuple.Create("\uDC00\uD800", "%EF%BF%BD%EF%BF%BD"); // Low + high
yield return Tuple.Create("\uD900\uDA00", "%EF%BF%BD%EF%BF%BD"); // High + high
yield return Tuple.Create("\uDE00\uDF00", "%EF%BF%BD%EF%BF%BD"); // Low + low
yield return Tuple.Create("!\uDB00@", "!%EF%BF%BD%40"); // Non-surrogate + high + non-surrogate
yield return Tuple.Create("#\uDD00$", "%23%EF%BF%BD%24"); // Non-surrogate + low + non-surrogate
*/
}
public static IEnumerable<object[]> UrlEncodeDecode_Roundtrip_SharedTestData()
{
yield return new object[] { "'" };
yield return new object[] { "http://www.microsoft.com" };
yield return new object[] { "/\\\"\tHello! \u2665?/\\\"\tWorld! \u2665?\u2665" };
yield return new object[] { "\uD800\uDFFF" }; // Surrogate pairs
yield return new object[] { CharRange('\uE000', '\uF8FF') }; // BMP private use chars
yield return new object[] { CharRange('\uFDD0', '\uFDEF') }; // Low BMP non-chars
// TODO: Uncomment when dotnet/corefx#7166 is fixed.
// yield return new object[] { "\uFFFE\uFFFF" }; // High BMP non-chars
yield return new object[] { CharRange('\0', '\u001F') }; // C0 controls
yield return new object[] { CharRange('\u0080', '\u009F') }; // C1 controls
yield return new object[] { CharRange('\u202A', '\u202E') }; // BIDI embedding and override
yield return new object[] { CharRange('\u2066', '\u2069') }; // BIDI isolate
yield return new object[] { "\uFEFF" }; // BOM
// Astral plane private use chars
yield return new object[] { CharRange(0xF0000, 0xFFFFD) };
yield return new object[] { CharRange(0x100000, 0x10FFFD) };
// Astral plane non-chars
yield return new object[] { "\U0001FFFE" };
yield return new object[] { "\U0001FFFF" };
yield return new object[] { CharRange(0x2FFFE, 0x10FFFF) };
}
// UrlEncode + UrlDecode
public static IEnumerable<object[]> UrlDecode_TestData()
{
foreach (var tuple in UrlDecode_SharedTestData())
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(UrlDecode_TestData))]
public static void UrlDecode(string encodedValue, string expected)
{
Assert.Equal(expected, WebUtility.UrlDecode(encodedValue));
}
public static IEnumerable<object[]> UrlEncode_TestData()
{
foreach (var tuple in UrlEncode_SharedTestData())
yield return new object[] { tuple.Item1, tuple.Item2 };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(UrlEncode_TestData))]
public static void UrlEncode(string value, string expected)
{
Assert.Equal(expected, WebUtility.UrlEncode(value));
}
[Theory]
[MemberData(nameof(UrlEncodeDecode_Roundtrip_SharedTestData))]
public static void UrlEncodeDecode_Roundtrip(string value)
{
string encoded = WebUtility.UrlEncode(value);
Assert.Equal(value, WebUtility.UrlDecode(encoded));
}
// UrlEncode + DecodeToBytes
public static IEnumerable<object[]> UrlDecodeToBytes_TestData()
{
foreach (var tuple in UrlDecode_SharedTestData())
{
byte[] input = Encoding.UTF8.GetBytes(tuple.Item1);
byte[] output = Encoding.UTF8.GetBytes(tuple.Item2);
yield return new object[] { input, 0, input.Length, output };
}
yield return new object[] { null, 0, 0, null };
}
[Theory]
[MemberData(nameof(UrlDecodeToBytes_TestData))]
public static void UrlDecodeToBytes(byte[] value, int offset, int count, byte[] expected)
{
byte[] actual = WebUtility.UrlDecodeToBytes(value, offset, count);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlDecodeToBytes_Invalid()
{
Assert.Throws<ArgumentNullException>("bytes", () => WebUtility.UrlDecodeToBytes(null, 0, 1)); // Bytes is null
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlDecodeToBytes(new byte[1], -1, 1)); // Offset < 0
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlDecodeToBytes(new byte[1], 2, 1)); // Offset > bytes.Length
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlDecodeToBytes(new byte[1], 0, -1)); // Count < 0
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlDecodeToBytes(new byte[1], 0, 3)); // Count > bytes.Length
}
[Theory]
[InlineData("a", 0, 1)]
[InlineData("a", 1, 0)]
[InlineData("abc", 0, 3)]
[InlineData("abc", 1, 2)]
[InlineData("abc", 1, 1)]
[InlineData("abcd", 1, 2)]
[InlineData("abcd", 2, 2)]
public static void UrlEncodeToBytes_NothingToExpand_OutputMatchesSubInput(string inputString, int offset, int count)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(inputString);
byte[] subInputBytes = new byte[count];
Buffer.BlockCopy(inputBytes, offset, subInputBytes, 0, count);
Assert.Equal(inputString.Length, inputBytes.Length);
byte[] outputBytes = WebUtility.UrlEncodeToBytes(inputBytes, offset, count);
Assert.NotSame(inputBytes, outputBytes);
Assert.Equal(count, outputBytes.Length);
Assert.Equal(subInputBytes, outputBytes);
}
public static IEnumerable<object[]> UrlEncodeToBytes_TestData()
{
foreach (var tuple in UrlEncode_SharedTestData())
{
byte[] input = Encoding.UTF8.GetBytes(tuple.Item1);
byte[] output = Encoding.UTF8.GetBytes(tuple.Item2);
yield return new object[] { input, 0, input.Length, output };
}
yield return new object[] { null, 0, 0, null };
}
[Theory]
[MemberData(nameof(UrlEncodeToBytes_TestData))]
public static void UrlEncodeToBytes(byte[] value, int offset, int count, byte[] expected)
{
byte[] actual = WebUtility.UrlEncodeToBytes(value, offset, count);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlEncodeToBytes_Invalid()
{
Assert.Throws<ArgumentNullException>("bytes", () => WebUtility.UrlEncodeToBytes(null, 0, 1)); // Bytes is null
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlEncodeToBytes(new byte[1], -1, 1)); // Offset < 0
Assert.Throws<ArgumentOutOfRangeException>("offset", () => WebUtility.UrlEncodeToBytes(new byte[1], 2, 1)); // Offset > bytes.Length
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlEncodeToBytes(new byte[1], 0, -1)); // Count < 0
Assert.Throws<ArgumentOutOfRangeException>("count", () => WebUtility.UrlEncodeToBytes(new byte[1], 0, 3)); // Count > bytes.Length
}
[Theory]
[MemberData(nameof(UrlEncodeDecode_Roundtrip_SharedTestData))]
public static void UrlEncodeDecodeToBytes_Roundtrip(string url)
{
byte[] input = Encoding.UTF8.GetBytes(url);
byte[] encoded = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
Assert.Equal(input, WebUtility.UrlDecodeToBytes(encoded, 0, encoded.Length));
}
[Theory]
[InlineData("FooBarQuux", 3, 7, "BarQuux")]
public static void UrlEncodeToBytes_ExcludeIrrelevantData(string value, int offset, int count, string expected)
{
byte[] input = Encoding.UTF8.GetBytes(value);
byte[] encoded = WebUtility.UrlEncodeToBytes(input, offset, count);
string actual = Encoding.UTF8.GetString(encoded);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("FooBarQuux", 3, 7, "BarQuux")]
public static void UrlDecodeToBytes_ExcludeIrrelevantData(string value, int offset, int count, string expected)
{
byte[] input = Encoding.UTF8.GetBytes(value);
byte[] decoded = WebUtility.UrlDecodeToBytes(input, offset, count);
string actual = Encoding.UTF8.GetString(decoded);
Assert.Equal(expected, actual);
}
[Fact]
public static void UrlEncodeToBytes_NewArray()
{
// If no encoding is needed, the current implementation simply
// returns the input array to a method which then clones it.
// We have to make sure it always returns a new array, to
// prevent problems where the input array is changed if
// the output one is modified.
byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Encoding");
byte[] output = WebUtility.UrlEncodeToBytes(input, 0, input.Length);
Assert.NotSame(input, output);
}
[Fact]
public static void UrlDecodeToBytes_NewArray()
{
byte[] input = Encoding.UTF8.GetBytes("Dont.Need.Decoding");
byte[] output = WebUtility.UrlDecodeToBytes(input, 0, input.Length);
Assert.NotSame(input, output);
}
public static string CharRange(int start, int end)
{
Debug.Assert(start <= end);
int capacity = end - start + 1;
var builder = new StringBuilder(capacity);
for (int i = start; i <= end; i++)
{
// 0 -> \0, 65 -> A, 0x10FFFF -> \U0010FFFF
builder.Append(char.ConvertFromUtf32(i));
}
return builder.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
using EdgeData = IFunctionalMap<SymbolicValue, FList<SymbolicValue>>;
public class OldAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions, MethodResult>
: AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
public OldAnalysisDriver(
IBasicAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions> basicDriver
) : base(basicDriver)
{
}
public override IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions> MethodDriver(
Method method,
IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> classDriver,
bool removeInferredPrecondition = false)
{
return new MDriver(method, this, classDriver, removeInferredPrecondition);
}
private class MDriver
: BasicMethodDriverWithInference<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions>
, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions>
, IFactBase<SymbolicValue>
{
public IDictionary<CFGBlock, IFunctionalSet<ESymValue>> ModifiedAtCall { get; set; }
private OptimisticHeapAnalyzer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> optimisticHeapAnalysis;
private Converter<ExternalExpression<APC, SymbolicValue>, string> expr2String;
private IFullExpressionDecoder<Type, SymbolicValue, ExternalExpression<APC, SymbolicValue>> expressionDecoder;
private readonly IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> classDriver;
private readonly AnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> specializedParent;
private readonly bool RemoveInferredPreconditions;
public IDisjunctiveExpressionRefiner<SymbolicValue, BoxedExpression> DisjunctiveExpressionRefiner { get; set; }
public SyntacticInformation<Method, Field, SymbolicValue> AdditionalSyntacticInformation { get; set; }
public ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue, SymbolicValue, IValueContext<Local, Parameter, Method, Field, Type, SymbolicValue>, EdgeData>
ValueLayer
{ get; private set; }
public ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<APC, SymbolicValue>, SymbolicValue>, EdgeData>
ExpressionLayer
{ get; private set; }
public ICodeLayer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue, SymbolicValue, IValueContext<Local, Parameter, Method, Field, Type, SymbolicValue>, EdgeData>
HybridLayer
{ get; protected set; }
public IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> MetaDataDecoder
{ get { return this.RawLayer.MetaDataDecoder; } }
public MDriver(
Method method,
OldAnalysisDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, LogOptions, MethodResult> parent,
IClassDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, ExternalExpression<APC, SymbolicValue>, SymbolicValue, LogOptions, MethodResult> classDriver,
bool removeInferredPrecondition
)
: base(method, parent)
{
specializedParent = parent;
// Here we build our stack of adapters.
//
// Expr (expressions)
// Heap (symbolic values)
// StackDepth (Temp decoder for APC)
// CFG (Unit decoder for APC, including Assume)
// cciilprovider (Unit decoder for PC)
//
// The base class already built the first 3
// The last two are built on demand
this.classDriver = classDriver;
RemoveInferredPreconditions = removeInferredPrecondition;
}
public IExpressionContext<Local, Parameter, Method, Field, Type, ExternalExpression<APC, SymbolicValue>, SymbolicValue> Context { get { return this.ExpressionLayer.Decoder.AssumeNotNull().Context; } }
public Converter<SymbolicValue, int> KeyNumber { get { return SymbolicValue.GetUniqueKey; } }
public Comparison<SymbolicValue> VariableComparer { get { return SymbolicValue.Compare; } }
public void RunHeapAndExpressionAnalyses(DFAController controller)
{
if (optimisticHeapAnalysis != null) return;
optimisticHeapAnalysis = new OptimisticHeapAnalyzer<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(this.StackLayer, this.Options.TraceEGraph);
optimisticHeapAnalysis.TurnArgumentExceptionThrowsIntoAssertFalse = this.Options.TurnArgumentExceptionThrowsIntoAssertFalse;
optimisticHeapAnalysis.IgnoreExplicitAssumptions = this.Options.IgnoreExplicitAssumptions;
optimisticHeapAnalysis.TraceAssumptions = this.Options.TraceAssumptions;
var heapsolver = this.StackLayer.CreateForward(optimisticHeapAnalysis,
new DFAOptions { Trace = this.Options.TraceHeapAnalysis }, controller);
heapsolver(optimisticHeapAnalysis.InitialValue());
this.ValueLayer = CodeLayerFactory.Create(optimisticHeapAnalysis.GetDecoder(this.StackLayer.Decoder),
this.StackLayer.MetaDataDecoder,
this.StackLayer.ContractDecoder,
delegate (SymbolicValue source) { return source.ToString(); },
delegate (SymbolicValue dest) { return dest.ToString(); },
(v1, v2) => v1.symbol.GlobalId > v2.symbol.GlobalId
);
if (this.PrintIL)
{
Console.WriteLine("-----------------Value based CFG---------------------");
this.ValueLayer.Decoder.Context.MethodContext.CFG.Print(Console.Out, this.ValueLayer.Printer, optimisticHeapAnalysis.GetEdgePrinter(),
(block) => optimisticHeapAnalysis.GetContexts(block),
null);
}
var exprAnalysis = new ExpressionAnalysis<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, SymbolicValue, IValueContext<Local, Parameter, Method, Field, Type, SymbolicValue>, EdgeData>(
this.ValueLayer,
this.Options,
optimisticHeapAnalysis.IsUnreachable
);
var exprsolver = this.ValueLayer.CreateForward(exprAnalysis.CreateExpressionAnalyzer(),
new DFAOptions { Trace = this.Options.TraceExpressionAnalysis }, controller);
exprsolver(exprAnalysis.InitialValue(SymbolicValue.GetUniqueKey));
var exprDecoder = exprAnalysis.GetDecoder(this.ValueLayer.Decoder);
expr2String = ExprPrinter.Printer(exprDecoder.Context, this);
this.ExpressionLayer = CodeLayerFactory.Create(
exprDecoder,
this.ValueLayer.MetaDataDecoder,
this.ValueLayer.ContractDecoder,
expr2String,
this.ValueLayer.VariableToString,
(v1, v2) => v1.symbol.GlobalId > v2.symbol.GlobalId
);
if (this.PrintIL)
{
Console.WriteLine("-----------------Expression based CFG---------------------");
this.ExpressionLayer.Decoder.Context.MethodContext.CFG.Print(Console.Out, this.ExpressionLayer.Printer, exprAnalysis.GetBlockPrinter(expr2String),
(block) => exprAnalysis.GetContexts(block),
null);
}
this.HybridLayer = CodeLayerFactory.Create(
this.ValueLayer.Decoder,
this.ValueLayer.MetaDataDecoder,
this.ValueLayer.ContractDecoder,
this.ValueLayer.ExpressionToString,
this.ValueLayer.VariableToString,
this.ExpressionLayer.Printer,
this.ExpressionLayer.NewerThan
);
if (Options.TraceAssumptions)
{
#region Produce trace output to extract implicit assumptions. Please don't remove this code!
Console.WriteLine("<assumptions>");
Console.WriteLine(@"<subroutine id=""{0}"" methodName=""{1}"">", HybridLayer.Decoder.Context.MethodContext.CFG.Subroutine.Id, HybridLayer.Decoder.Context.MethodContext.CFG.Subroutine.Name);
foreach (var b in HybridLayer.Decoder.Context.MethodContext.CFG.Subroutine.Blocks)
{
Console.WriteLine(@"<block index=""{0}"">", b.Index);
foreach (var apc in b.APCs())
{
Console.WriteLine(@"<apc name=""{0}"" index=""{1}"" ilOffset=""{2}"" primarySourceContext=""{3}"" sourceContext=""{4}"">",
apc.ToString(), apc.Index, apc.ILOffset, apc.PrimarySourceContext(), HybridLayer.Decoder.Context.MethodContext.SourceContext(apc));
Console.WriteLine("<code>");
HybridLayer.Printer(apc, "", Console.Out);
Console.WriteLine("</code>");
optimisticHeapAnalysis.Dump(apc);
Console.WriteLine("</apc>");
}
Console.WriteLine("</block>");
}
Console.WriteLine("</subroutine>");
Console.WriteLine("</assumptions>");
#endregion
}
ModifiedAtCall = optimisticHeapAnalysis.ModifiedAtCall;
}
public Converter<ExternalExpression<APC, SymbolicValue>, string> ExpressionToString { get { return expr2String; } }
public State BackwardTransfer<State, Visitor>(APC from, APC to, State state, Visitor visitor)
where Visitor : IEdgeVisit<APC, Local, Parameter, Method, Field, Type, SymbolicValue, State>
{
if (this.IsUnreachable(to)) { throw new InvalidOperationException("Can not transfer to unreachable point"); }
if (from.Block != to.Block)
{
var renaming = optimisticHeapAnalysis.BackwardEdgeRenaming(from, to);
if (renaming != null)
{
return visitor.Rename(from, to, state, renaming);
}
else
{
return state;
}
}
return this.ValueLayer.Decoder.ForwardDecode<State, State, Visitor>(to, visitor, state);
}
#region IMethodDriver<APC,Local,Parameter,Method,Field,Type,Attribute,Assembly,ExternalExpression<APC,SymbolicValue>,SymbolicValue,LogOptions> Members
public IFullExpressionDecoder<Type, SymbolicValue, ExternalExpression<APC, SymbolicValue>> ExpressionDecoder
{
get
{
if (expressionDecoder == null)
{
Contract.Assert(this.Context != null);
expressionDecoder = ExternalExpressionDecoder.Create(this.MetaDataDecoder, this.Context);
}
return expressionDecoder;
}
}
public IFactBase<SymbolicValue> BasicFacts { get { return this; } }
public override bool CanAddRequires()
{
return this.CanAddContracts();
}
public override bool CanAddEnsures()
{
return !this.MetaDataDecoder.IsVirtual(this.Context.MethodContext.CurrentMethod) && this.CanAddContracts();
}
protected override bool CanAddInvariants()
{
if (classDriver == null)
return false;
return classDriver.CanAddInvariants();
}
protected override bool CanAddAssumes()
{
return this.Options.InferAssumesForBaseLining;
}
private bool CanAddContracts()
{
return !this.MetaDataDecoder.IsCompilerGenerated(this.Context.MethodContext.CurrentMethod) &&
(!this.MetaDataDecoder.IsVirtual(this.Context.MethodContext.CurrentMethod) ||
this.MetaDataDecoder.OverriddenAndImplementedMethods(this.method).AsIndexable(1).Count == 0);
}
public void EndAnalysis()
{
if (RemoveInferredPreconditions)
{
// we are done validating the inferred preconditions, so we can remove them from the method cache
specializedParent.RemoveInferredPrecondition(this.method);
}
else
{
specializedParent.InstallPreconditions(this.inferredPreconditions, this.method);
}
specializedParent.InstallPostconditions(this.inferredPostconditions, this.method);
// Let's add the witness
specializedParent.MethodCache.AddWitness(this.method, this.MayReturnNull);
// Install postconditons for other methods
if (otherPostconditions != null)
{
foreach (var tuple in otherPostconditions.GroupBy(t => t.Item1))
{
Contract.Assume(tuple.Any());
specializedParent.InstallPostconditions(tuple.Select(t => t.Item2).ToList(), tuple.First().Item1);
}
}
if (classDriver != null)
{
var methodThis = this.MetaDataDecoder.This(this.method);
classDriver.InstallInvariantsAsConstructorPostconditions(methodThis, this.inferredObjectInvariants, this.method);
// Really install object invariants. TODO: readonly fields only
// Missing something... how do I build a Contract.Invariant(...)?
var asAssume = this.inferredObjectInvariants.Select(be => (new BoxedExpression.AssumeExpression(be.One, "invariant", this.CFG.EntryAfterRequires, be.Two, be.One.ToString<Type>(type => OutputPrettyCS.TypeHelper.TypeFullName(this.MetaDataDecoder, type))))).Cast<BoxedExpression>();
specializedParent.InstallObjectInvariants(asAssume.ToList(), classDriver.ClassType);
}
}
#endregion
#region IFactBase<SymbolicValue> Members
public ProofOutcome IsNull(APC pc, SymbolicValue value)
{
return ProofOutcome.Top;
//this.ValueLayer.Decoder.Context.ValueContext.IsZero(pc, value);
}
public ProofOutcome IsNonNull(APC pc, SymbolicValue value)
{
return ProofOutcome.Top;
//this.ValueLayer.Decoder.Context.ValueContext.IsZero(pc, value);
}
public FList<BoxedExpression> InvariantAt(APC pc, FList<SymbolicValue> filter, bool replaceVarsWithAccessPath = true)
{
return FList<BoxedExpression>.Empty;
}
public bool IsUnreachable(APC pc)
{
return optimisticHeapAnalysis.IsUnreachable(pc);
}
#endregion
}
}
}
| |
// UMA Auto genered code, DO NOT MODIFY!!!
// All changes to this file will be destroyed without warning or confirmation!
// Use double { to escape a single curly bracket
//
// template junk executed per dna Field , the accumulated content is available through the {0:ID} tag
//
//#TEMPLATE GetValues UmaDnaChild_GetIndex_Fragment.cs.txt
//#TEMPLATE SetValues UmaDnaChild_SetIndex_Fragment.cs.txt
//#TEMPLATE GetValue UmaDnaChild_GetValue_Fragment.cs.txt
//#TEMPLATE SetValue UmaDnaChild_SetValue_Fragment.cs.txt
//#TEMPLATE GetNames UmaDnaChild_GetNames_Fragment.cs.txt
//
// Byte Serialization Handling
//
//#TEMPLATE Byte_Fields UmaDnaChild_Byte_Fields_Fragment.cs.txt
//#TEMPLATE Byte_ToDna UmaDnaChild_Byte_ToDna_Fragment.cs.txt
//#TEMPLATE Byte_FromDna UmaDnaChild_Byte_FromDna_Fragment.cs.txt
//
namespace UMA
{
public partial class UMADnaHumanoid
{
public override int Count { get { return 46; } }
public override float[] Values
{
get
{
return new float[]
{
height,
headSize,
headWidth,
neckThickness,
armLength,
forearmLength,
armWidth,
forearmWidth,
handsSize,
feetSize,
legSeparation,
upperMuscle,
lowerMuscle,
upperWeight,
lowerWeight,
legsSize,
belly,
waist,
gluteusSize,
earsSize,
earsPosition,
earsRotation,
noseSize,
noseCurve,
noseWidth,
noseInclination,
nosePosition,
nosePronounced,
noseFlatten,
chinSize,
chinPronounced,
chinPosition,
mandibleSize,
jawsSize,
jawsPosition,
cheekSize,
cheekPosition,
lowCheekPronounced,
lowCheekPosition,
foreheadSize,
foreheadPosition,
lipsSize,
mouthSize,
eyeRotation,
eyeSize,
breastSize,
};
}
set
{
height = value[0];
headSize = value[1];
headWidth = value[2];
neckThickness = value[3];
armLength = value[4];
forearmLength = value[5];
armWidth = value[6];
forearmWidth = value[7];
handsSize = value[8];
feetSize = value[9];
legSeparation = value[10];
upperMuscle = value[11];
lowerMuscle = value[12];
upperWeight = value[13];
lowerWeight = value[14];
legsSize = value[15];
belly = value[16];
waist = value[17];
gluteusSize = value[18];
earsSize = value[19];
earsPosition = value[20];
earsRotation = value[21];
noseSize = value[22];
noseCurve = value[23];
noseWidth = value[24];
noseInclination = value[25];
nosePosition = value[26];
nosePronounced = value[27];
noseFlatten = value[28];
chinSize = value[29];
chinPronounced = value[30];
chinPosition = value[31];
mandibleSize = value[32];
jawsSize = value[33];
jawsPosition = value[34];
cheekSize = value[35];
cheekPosition = value[36];
lowCheekPronounced = value[37];
lowCheekPosition = value[38];
foreheadSize = value[39];
foreheadPosition = value[40];
lipsSize = value[41];
mouthSize = value[42];
eyeRotation = value[43];
eyeSize = value[44];
breastSize = value[45];
}
}
public override float GetValue(int idx)
{
switch(idx)
{
case 0: return height;
case 1: return headSize;
case 2: return headWidth;
case 3: return neckThickness;
case 4: return armLength;
case 5: return forearmLength;
case 6: return armWidth;
case 7: return forearmWidth;
case 8: return handsSize;
case 9: return feetSize;
case 10: return legSeparation;
case 11: return upperMuscle;
case 12: return lowerMuscle;
case 13: return upperWeight;
case 14: return lowerWeight;
case 15: return legsSize;
case 16: return belly;
case 17: return waist;
case 18: return gluteusSize;
case 19: return earsSize;
case 20: return earsPosition;
case 21: return earsRotation;
case 22: return noseSize;
case 23: return noseCurve;
case 24: return noseWidth;
case 25: return noseInclination;
case 26: return nosePosition;
case 27: return nosePronounced;
case 28: return noseFlatten;
case 29: return chinSize;
case 30: return chinPronounced;
case 31: return chinPosition;
case 32: return mandibleSize;
case 33: return jawsSize;
case 34: return jawsPosition;
case 35: return cheekSize;
case 36: return cheekPosition;
case 37: return lowCheekPronounced;
case 38: return lowCheekPosition;
case 39: return foreheadSize;
case 40: return foreheadPosition;
case 41: return lipsSize;
case 42: return mouthSize;
case 43: return eyeRotation;
case 44: return eyeSize;
case 45: return breastSize;
}
return base.GetValue(idx);
}
public override void SetValue(int idx, float value)
{
switch(idx)
{
case 0: height = value; return;
case 1: headSize = value; return;
case 2: headWidth = value; return;
case 3: neckThickness = value; return;
case 4: armLength = value; return;
case 5: forearmLength = value; return;
case 6: armWidth = value; return;
case 7: forearmWidth = value; return;
case 8: handsSize = value; return;
case 9: feetSize = value; return;
case 10: legSeparation = value; return;
case 11: upperMuscle = value; return;
case 12: lowerMuscle = value; return;
case 13: upperWeight = value; return;
case 14: lowerWeight = value; return;
case 15: legsSize = value; return;
case 16: belly = value; return;
case 17: waist = value; return;
case 18: gluteusSize = value; return;
case 19: earsSize = value; return;
case 20: earsPosition = value; return;
case 21: earsRotation = value; return;
case 22: noseSize = value; return;
case 23: noseCurve = value; return;
case 24: noseWidth = value; return;
case 25: noseInclination = value; return;
case 26: nosePosition = value; return;
case 27: nosePronounced = value; return;
case 28: noseFlatten = value; return;
case 29: chinSize = value; return;
case 30: chinPronounced = value; return;
case 31: chinPosition = value; return;
case 32: mandibleSize = value; return;
case 33: jawsSize = value; return;
case 34: jawsPosition = value; return;
case 35: cheekSize = value; return;
case 36: cheekPosition = value; return;
case 37: lowCheekPronounced = value; return;
case 38: lowCheekPosition = value; return;
case 39: foreheadSize = value; return;
case 40: foreheadPosition = value; return;
case 41: lipsSize = value; return;
case 42: mouthSize = value; return;
case 43: eyeRotation = value; return;
case 44: eyeSize = value; return;
case 45: breastSize = value; return;
}
base.SetValue(idx, value);
}
public static string[] GetNames()
{
return new string[]
{
"height",
"headSize",
"headWidth",
"neckThickness",
"armLength",
"forearmLength",
"armWidth",
"forearmWidth",
"handsSize",
"feetSize",
"legSeparation",
"upperMuscle",
"lowerMuscle",
"upperWeight",
"lowerWeight",
"legsSize",
"belly",
"waist",
"gluteusSize",
"earsSize",
"earsPosition",
"earsRotation",
"noseSize",
"noseCurve",
"noseWidth",
"noseInclination",
"nosePosition",
"nosePronounced",
"noseFlatten",
"chinSize",
"chinPronounced",
"chinPosition",
"mandibleSize",
"jawsSize",
"jawsPosition",
"cheekSize",
"cheekPosition",
"lowCheekPronounced",
"lowCheekPosition",
"foreheadSize",
"foreheadPosition",
"lipsSize",
"mouthSize",
"eyeRotation",
"eyeSize",
"breastSize",
};
}
public override string[] Names
{
get
{
return GetNames();
}
}
public static UMADnaHumanoid LoadInstance(string data)
{
return LitJson.JsonMapper.ToObject<UMADnaHumanoid_Byte>(data).ToDna();
}
public static string SaveInstance(UMADnaHumanoid instance)
{
return LitJson.JsonMapper.ToJson(UMADnaHumanoid_Byte.FromDna(instance));
}
}
[System.Serializable]
public class UMADnaHumanoid_Byte
{
public System.Byte height;
public System.Byte headSize;
public System.Byte headWidth;
public System.Byte neckThickness;
public System.Byte armLength;
public System.Byte forearmLength;
public System.Byte armWidth;
public System.Byte forearmWidth;
public System.Byte handsSize;
public System.Byte feetSize;
public System.Byte legSeparation;
public System.Byte upperMuscle;
public System.Byte lowerMuscle;
public System.Byte upperWeight;
public System.Byte lowerWeight;
public System.Byte legsSize;
public System.Byte belly;
public System.Byte waist;
public System.Byte gluteusSize;
public System.Byte earsSize;
public System.Byte earsPosition;
public System.Byte earsRotation;
public System.Byte noseSize;
public System.Byte noseCurve;
public System.Byte noseWidth;
public System.Byte noseInclination;
public System.Byte nosePosition;
public System.Byte nosePronounced;
public System.Byte noseFlatten;
public System.Byte chinSize;
public System.Byte chinPronounced;
public System.Byte chinPosition;
public System.Byte mandibleSize;
public System.Byte jawsSize;
public System.Byte jawsPosition;
public System.Byte cheekSize;
public System.Byte cheekPosition;
public System.Byte lowCheekPronounced;
public System.Byte lowCheekPosition;
public System.Byte foreheadSize;
public System.Byte foreheadPosition;
public System.Byte lipsSize;
public System.Byte mouthSize;
public System.Byte eyeRotation;
public System.Byte eyeSize;
public System.Byte breastSize;
public UMADnaHumanoid ToDna()
{
var res = new UMADnaHumanoid();
res.height = height * (1f / 255f);
res.headSize = headSize * (1f / 255f);
res.headWidth = headWidth * (1f / 255f);
res.neckThickness = neckThickness * (1f / 255f);
res.armLength = armLength * (1f / 255f);
res.forearmLength = forearmLength * (1f / 255f);
res.armWidth = armWidth * (1f / 255f);
res.forearmWidth = forearmWidth * (1f / 255f);
res.handsSize = handsSize * (1f / 255f);
res.feetSize = feetSize * (1f / 255f);
res.legSeparation = legSeparation * (1f / 255f);
res.upperMuscle = upperMuscle * (1f / 255f);
res.lowerMuscle = lowerMuscle * (1f / 255f);
res.upperWeight = upperWeight * (1f / 255f);
res.lowerWeight = lowerWeight * (1f / 255f);
res.legsSize = legsSize * (1f / 255f);
res.belly = belly * (1f / 255f);
res.waist = waist * (1f / 255f);
res.gluteusSize = gluteusSize * (1f / 255f);
res.earsSize = earsSize * (1f / 255f);
res.earsPosition = earsPosition * (1f / 255f);
res.earsRotation = earsRotation * (1f / 255f);
res.noseSize = noseSize * (1f / 255f);
res.noseCurve = noseCurve * (1f / 255f);
res.noseWidth = noseWidth * (1f / 255f);
res.noseInclination = noseInclination * (1f / 255f);
res.nosePosition = nosePosition * (1f / 255f);
res.nosePronounced = nosePronounced * (1f / 255f);
res.noseFlatten = noseFlatten * (1f / 255f);
res.chinSize = chinSize * (1f / 255f);
res.chinPronounced = chinPronounced * (1f / 255f);
res.chinPosition = chinPosition * (1f / 255f);
res.mandibleSize = mandibleSize * (1f / 255f);
res.jawsSize = jawsSize * (1f / 255f);
res.jawsPosition = jawsPosition * (1f / 255f);
res.cheekSize = cheekSize * (1f / 255f);
res.cheekPosition = cheekPosition * (1f / 255f);
res.lowCheekPronounced = lowCheekPronounced * (1f / 255f);
res.lowCheekPosition = lowCheekPosition * (1f / 255f);
res.foreheadSize = foreheadSize * (1f / 255f);
res.foreheadPosition = foreheadPosition * (1f / 255f);
res.lipsSize = lipsSize * (1f / 255f);
res.mouthSize = mouthSize * (1f / 255f);
res.eyeRotation = eyeRotation * (1f / 255f);
res.eyeSize = eyeSize * (1f / 255f);
res.breastSize = breastSize * (1f / 255f);
return res;
}
public static UMADnaHumanoid_Byte FromDna(UMADnaHumanoid dna)
{
var res = new UMADnaHumanoid_Byte();
res.height = (System.Byte)(dna.height * 255f+0.5f);
res.headSize = (System.Byte)(dna.headSize * 255f+0.5f);
res.headWidth = (System.Byte)(dna.headWidth * 255f+0.5f);
res.neckThickness = (System.Byte)(dna.neckThickness * 255f+0.5f);
res.armLength = (System.Byte)(dna.armLength * 255f+0.5f);
res.forearmLength = (System.Byte)(dna.forearmLength * 255f+0.5f);
res.armWidth = (System.Byte)(dna.armWidth * 255f+0.5f);
res.forearmWidth = (System.Byte)(dna.forearmWidth * 255f+0.5f);
res.handsSize = (System.Byte)(dna.handsSize * 255f+0.5f);
res.feetSize = (System.Byte)(dna.feetSize * 255f+0.5f);
res.legSeparation = (System.Byte)(dna.legSeparation * 255f+0.5f);
res.upperMuscle = (System.Byte)(dna.upperMuscle * 255f+0.5f);
res.lowerMuscle = (System.Byte)(dna.lowerMuscle * 255f+0.5f);
res.upperWeight = (System.Byte)(dna.upperWeight * 255f+0.5f);
res.lowerWeight = (System.Byte)(dna.lowerWeight * 255f+0.5f);
res.legsSize = (System.Byte)(dna.legsSize * 255f+0.5f);
res.belly = (System.Byte)(dna.belly * 255f+0.5f);
res.waist = (System.Byte)(dna.waist * 255f+0.5f);
res.gluteusSize = (System.Byte)(dna.gluteusSize * 255f+0.5f);
res.earsSize = (System.Byte)(dna.earsSize * 255f+0.5f);
res.earsPosition = (System.Byte)(dna.earsPosition * 255f+0.5f);
res.earsRotation = (System.Byte)(dna.earsRotation * 255f+0.5f);
res.noseSize = (System.Byte)(dna.noseSize * 255f+0.5f);
res.noseCurve = (System.Byte)(dna.noseCurve * 255f+0.5f);
res.noseWidth = (System.Byte)(dna.noseWidth * 255f+0.5f);
res.noseInclination = (System.Byte)(dna.noseInclination * 255f+0.5f);
res.nosePosition = (System.Byte)(dna.nosePosition * 255f+0.5f);
res.nosePronounced = (System.Byte)(dna.nosePronounced * 255f+0.5f);
res.noseFlatten = (System.Byte)(dna.noseFlatten * 255f+0.5f);
res.chinSize = (System.Byte)(dna.chinSize * 255f+0.5f);
res.chinPronounced = (System.Byte)(dna.chinPronounced * 255f+0.5f);
res.chinPosition = (System.Byte)(dna.chinPosition * 255f+0.5f);
res.mandibleSize = (System.Byte)(dna.mandibleSize * 255f+0.5f);
res.jawsSize = (System.Byte)(dna.jawsSize * 255f+0.5f);
res.jawsPosition = (System.Byte)(dna.jawsPosition * 255f+0.5f);
res.cheekSize = (System.Byte)(dna.cheekSize * 255f+0.5f);
res.cheekPosition = (System.Byte)(dna.cheekPosition * 255f+0.5f);
res.lowCheekPronounced = (System.Byte)(dna.lowCheekPronounced * 255f+0.5f);
res.lowCheekPosition = (System.Byte)(dna.lowCheekPosition * 255f+0.5f);
res.foreheadSize = (System.Byte)(dna.foreheadSize * 255f+0.5f);
res.foreheadPosition = (System.Byte)(dna.foreheadPosition * 255f+0.5f);
res.lipsSize = (System.Byte)(dna.lipsSize * 255f+0.5f);
res.mouthSize = (System.Byte)(dna.mouthSize * 255f+0.5f);
res.eyeRotation = (System.Byte)(dna.eyeRotation * 255f+0.5f);
res.eyeSize = (System.Byte)(dna.eyeSize * 255f+0.5f);
res.breastSize = (System.Byte)(dna.breastSize * 255f+0.5f);
return res;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.Build.Framework;
namespace GodotSharpTools.Build
{
public class BuildInstance : IDisposable
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static string godot_icall_BuildInstance_get_MSBuildPath();
private static string MSBuildPath
{
get
{
string ret = godot_icall_BuildInstance_get_MSBuildPath();
if (ret == null)
throw new FileNotFoundException("Cannot find the MSBuild executable.");
return ret;
}
}
private string solution;
private string config;
private Process process;
private int exitCode;
public int ExitCode { get { return exitCode; } }
public bool IsRunning { get { return process != null && !process.HasExited; } }
public BuildInstance(string solution, string config)
{
this.solution = solution;
this.config = config;
}
public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
{
string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties);
ProcessStartInfo startInfo = new ProcessStartInfo(MSBuildPath, compilerArgs);
// No console output, thanks
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
}
return true;
}
public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
{
if (process != null)
throw new InvalidOperationException("Already in use");
string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties);
ProcessStartInfo startInfo = new ProcessStartInfo("msbuild", compilerArgs);
// No console output, thanks
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
process = new Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(BuildProcess_Exited);
process.Start();
return true;
}
private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties)
{
string arguments = string.Format(@"""{0}"" /v:normal /t:Build ""/p:{1}"" ""/l:{2},{3};{4}""",
solution,
"Configuration=" + config,
typeof(GodotBuildLogger).FullName,
loggerAssemblyPath,
loggerOutputDir
);
if (customProperties != null)
{
foreach (string customProperty in customProperties)
{
arguments += " /p:" + customProperty;
}
}
return arguments;
}
private void RemovePlatformVariable(StringDictionary environmentVariables)
{
// EnvironmentVariables is case sensitive? Seriously?
List<string> platformEnvironmentVariables = new List<string>();
foreach (string env in environmentVariables.Keys)
{
if (env.ToUpper() == "PLATFORM")
platformEnvironmentVariables.Add(env);
}
foreach (string env in platformEnvironmentVariables)
environmentVariables.Remove(env);
}
private void BuildProcess_Exited(object sender, System.EventArgs e)
{
exitCode = process.ExitCode;
godot_icall_BuildInstance_ExitCallback(solution, config, exitCode);
Dispose();
}
public void Dispose()
{
if (process != null)
{
process.Dispose();
process = null;
}
}
}
public class GodotBuildLogger : ILogger
{
public string Parameters { get; set; }
public LoggerVerbosity Verbosity { get; set; }
public void Initialize(IEventSource eventSource)
{
if (null == Parameters)
throw new LoggerException("Log directory was not set.");
string[] parameters = Parameters.Split(';');
string logDir = parameters[0];
if (String.IsNullOrEmpty(logDir))
throw new LoggerException("Log directory was not set.");
if (parameters.Length > 1)
throw new LoggerException("Too many parameters passed.");
string logFile = Path.Combine(logDir, "msbuild_log.txt");
string issuesFile = Path.Combine(logDir, "msbuild_issues.csv");
try
{
if (!Directory.Exists(logDir))
Directory.CreateDirectory(logDir);
this.logStreamWriter = new StreamWriter(logFile);
this.issuesStreamWriter = new StreamWriter(issuesFile);
}
catch (Exception ex)
{
if
(
ex is UnauthorizedAccessException
|| ex is ArgumentNullException
|| ex is PathTooLongException
|| ex is DirectoryNotFoundException
|| ex is NotSupportedException
|| ex is ArgumentException
|| ex is SecurityException
|| ex is IOException
)
{
throw new LoggerException("Failed to create log file: " + ex.Message);
}
else
{
// Unexpected failure
throw;
}
}
eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted);
eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted);
eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised);
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished);
}
void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
{
string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message);
if (e.ProjectFile.Length > 0)
line += string.Format(" [{0}]", e.ProjectFile);
WriteLine(line);
string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}",
e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape());
issuesStreamWriter.WriteLine(errorLine);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile);
if (e.ProjectFile != null && e.ProjectFile.Length > 0)
line += string.Format(" [{0}]", e.ProjectFile);
WriteLine(line);
string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}",
e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty);
issuesStreamWriter.WriteLine(warningLine);
}
void eventSource_MessageRaised(object sender, BuildMessageEventArgs e)
{
// BuildMessageEventArgs adds Importance to BuildEventArgs
// Let's take account of the verbosity setting we've been passed in deciding whether to log the message
if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal))
|| (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal))
|| (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed))
)
{
WriteLineWithSenderAndMessage(String.Empty, e);
}
}
void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
{
// TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
// To keep this log clean, this logger will ignore these events.
}
void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
{
WriteLine(e.Message);
indent++;
}
void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
{
indent--;
WriteLine(e.Message);
}
/// <summary>
/// Write a line to the log, adding the SenderName
/// </summary>
private void WriteLineWithSender(string line, BuildEventArgs e)
{
if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
{
// Well, if the sender name is MSBuild, let's leave it out for prettiness
WriteLine(line);
}
else
{
WriteLine(e.SenderName + ": " + line);
}
}
/// <summary>
/// Write a line to the log, adding the SenderName and Message
/// (these parameters are on all MSBuild event argument objects)
/// </summary>
private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e)
{
if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
{
// Well, if the sender name is MSBuild, let's leave it out for prettiness
WriteLine(line + e.Message);
}
else
{
WriteLine(e.SenderName + ": " + line + e.Message);
}
}
private void WriteLine(string line)
{
for (int i = indent; i > 0; i--)
{
logStreamWriter.Write("\t");
}
logStreamWriter.WriteLine(line);
}
public void Shutdown()
{
logStreamWriter.Close();
issuesStreamWriter.Close();
}
public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity)
{
return this.Verbosity >= checkVerbosity;
}
private StreamWriter logStreamWriter;
private StreamWriter issuesStreamWriter;
private int indent;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO
{
// This class implements a text reader that reads from a string.
//
public class StringReader : TextReader
{
private string _s;
private int _pos;
private int _length;
public StringReader(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
_s = s;
_length = s == null ? 0 : s.Length;
}
protected override void Dispose(bool disposing)
{
_s = null;
_pos = 0;
_length = 0;
base.Dispose(disposing);
}
// Returns the next available character without actually reading it from
// the underlying string. The current position of the StringReader is not
// changed by this operation. The returned value is -1 if no further
// characters are available.
//
[Pure]
public override int Peek()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
if (_pos == _length)
{
return -1;
}
return _s[_pos];
}
// Reads the next character from the underlying string. The returned value
// is -1 if no further characters are available.
//
public override int Read()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
if (_pos == _length)
{
return -1;
}
return _s[_pos++];
}
// Reads a block of characters. This method will read up to count
// characters from this StringReader into the buffer character
// array starting at position index. Returns the actual number of
// characters read, or zero if the end of the string is reached.
//
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int n = _length - _pos;
if (n > 0)
{
if (n > count)
{
n = count;
}
_s.CopyTo(_pos, buffer, index, n);
_pos += n;
}
return n;
}
public override string ReadToEnd()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
string s;
if (_pos == 0)
{
s = _s;
}
else
{
s = _s.Substring(_pos, _length - _pos);
}
_pos = _length;
return s;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the underlying string has been reached.
//
public override string ReadLine()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int i = _pos;
while (i < _length)
{
char ch = _s[i];
if (ch == '\r' || ch == '\n')
{
string result = _s.Substring(_pos, i - _pos);
_pos = i + 1;
if (ch == '\r' && _pos < _length && _s[_pos] == '\n')
{
_pos++;
}
return result;
}
i++;
}
if (i > _pos)
{
string result = _s.Substring(_pos, i - _pos);
_pos = i;
return result;
}
return null;
}
#region Task based Async APIs
public override Task<string> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
public override Task<string> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return Task.FromResult(ReadBlock(buffer, index, count));
}
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return Task.FromResult(Read(buffer, index, count));
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Conditions
{
using System;
using System.Globalization;
using System.IO;
#if !NET_CF && !SILVERLIGHT
using System.Runtime.Serialization.Formatters.Binary;
#endif
using NUnit.Framework;
#if !NUNIT
using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute;
using ExpectedException = Microsoft.VisualStudio.TestTools.UnitTesting.ExpectedExceptionAttribute;
#endif
using NLog.Conditions;
using NLog.Config;
[TestFixture]
public class ConditionEvaluatorTests : NLogTestBase
{
[Test]
public void BooleanOperatorTest()
{
AssertEvaluationResult(false, "false or false");
AssertEvaluationResult(true, "false or true");
AssertEvaluationResult(true, "true or false");
AssertEvaluationResult(true, "true or true");
AssertEvaluationResult(false, "false and false");
AssertEvaluationResult(false, "false and true");
AssertEvaluationResult(false, "true and false");
AssertEvaluationResult(true, "true and true");
AssertEvaluationResult(false, "not true");
AssertEvaluationResult(true, "not false");
AssertEvaluationResult(false, "not not false");
AssertEvaluationResult(true, "not not true");
}
[Test]
public void ConditionMethodsTest()
{
AssertEvaluationResult(true, "starts-with('foobar','foo')");
AssertEvaluationResult(false, "starts-with('foobar','bar')");
AssertEvaluationResult(true, "ends-with('foobar','bar')");
AssertEvaluationResult(false, "ends-with('foobar','foo')");
AssertEvaluationResult(0, "length('')");
AssertEvaluationResult(4, "length('${level}')");
AssertEvaluationResult(false, "equals(1, 2)");
AssertEvaluationResult(true, "equals(3.14, 3.14)");
AssertEvaluationResult(true, "contains('foobar','ooba')");
AssertEvaluationResult(false, "contains('foobar','oobe')");
AssertEvaluationResult(false, "contains('','foo')");
AssertEvaluationResult(true, "contains('foo','')");
}
[Test]
public void ConditionMethodNegativeTest1()
{
try
{
AssertEvaluationResult(true, "starts-with('foobar')");
Assert.Fail("Expected exception");
}
catch (ConditionParseException ex)
{
Assert.AreEqual("Cannot resolve function 'starts-with'", ex.Message);
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Condition method 'starts-with' expects 2 parameters, but passed 1.", ex.InnerException.Message);
}
}
[Test]
public void ConditionMethodNegativeTest2()
{
try
{
AssertEvaluationResult(true, "starts-with('foobar','baz','qux','zzz')");
Assert.Fail("Expected exception");
}
catch (ConditionParseException ex)
{
Assert.AreEqual("Cannot resolve function 'starts-with'", ex.Message);
Assert.IsNotNull(ex.InnerException);
Assert.AreEqual("Condition method 'starts-with' expects 2 parameters, but passed 4.", ex.InnerException.Message);
}
}
[Test]
public void LiteralTest()
{
AssertEvaluationResult(null, "null");
AssertEvaluationResult(0, "0");
AssertEvaluationResult(3, "3");
AssertEvaluationResult(3.1415, "3.1415");
AssertEvaluationResult(-1, "-1");
AssertEvaluationResult(-3.1415, "-3.1415");
AssertEvaluationResult(true, "true");
AssertEvaluationResult(false, "false");
AssertEvaluationResult(string.Empty, "''");
AssertEvaluationResult("x", "'x'");
AssertEvaluationResult("d'Artagnan", "'d''Artagnan'");
}
[Test]
public void LogEventInfoPropertiesTest()
{
AssertEvaluationResult(LogLevel.Warn, "level");
AssertEvaluationResult("some message", "message");
AssertEvaluationResult("MyCompany.Product.Class", "logger");
}
[Test]
public void RelationalOperatorTest()
{
AssertEvaluationResult(true, "1 < 2");
AssertEvaluationResult(false, "1 < 1");
AssertEvaluationResult(true, "2 > 1");
AssertEvaluationResult(false, "1 > 1");
AssertEvaluationResult(true, "1 <= 2");
AssertEvaluationResult(false, "1 <= 0");
AssertEvaluationResult(true, "2 >= 1");
AssertEvaluationResult(false, "0 >= 1");
AssertEvaluationResult(true, "2 == 2");
AssertEvaluationResult(false, "2 == 3");
AssertEvaluationResult(true, "2 != 3");
AssertEvaluationResult(false, "2 != 2");
AssertEvaluationResult(false, "1 < null");
AssertEvaluationResult(true, "1 > null");
AssertEvaluationResult(true, "null < 1");
AssertEvaluationResult(false, "null > 1");
AssertEvaluationResult(true, "null == null");
AssertEvaluationResult(false, "null != null");
AssertEvaluationResult(false, "null == 1");
AssertEvaluationResult(false, "1 == null");
AssertEvaluationResult(true, "null != 1");
AssertEvaluationResult(true, "1 != null");
}
[Test]
[ExpectedException(typeof(ConditionEvaluationException))]
public void UnsupportedRelationalOperatorTest()
{
var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1));
cond.Evaluate(LogEventInfo.CreateNullEvent());
}
[Test]
[ExpectedException(typeof(NotSupportedException))]
public void UnsupportedRelationalOperatorTest2()
{
var cond = new ConditionRelationalExpression("true", "true", (ConditionRelationalOperator)(-1));
cond.ToString();
}
[Test]
public void MethodWithLogEventInfoTest()
{
var factories = SetupConditionMethods();
Assert.AreEqual(true, ConditionParser.ParseExpression("IsValid()", factories).Evaluate(CreateWellKnownContext()));
}
[Test]
public void TypePromotionTest()
{
var factories = SetupConditionMethods();
Assert.AreEqual(true, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/01'", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(1)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("'42' == 42", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("42 == '42'", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToDouble(3) == 3", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("3 == ToDouble(3)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToSingle(3) == 3", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("3 == ToSingle(3)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToDecimal(3) == 3", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("3 == ToDecimal(3)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(3)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(3)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("true == ToInt16(1)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(true, ConditionParser.ParseExpression("ToInt16(1) == true", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '2010/01/02'", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToInt64(1) == ToInt32(2)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("'42' == 43", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("42 == '43'", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToDouble(3) == 4", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("3 == ToDouble(4)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToSingle(3) == 4", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("3 == ToSingle(4)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToDecimal(3) == 4", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("3 == ToDecimal(4)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToInt32(3) == ToInt16(4)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToInt16(3) == ToInt32(4)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("false == ToInt16(4)", factories).Evaluate(CreateWellKnownContext()));
Assert.AreEqual(false, ConditionParser.ParseExpression("ToInt16(1) == false", factories).Evaluate(CreateWellKnownContext()));
}
[Test]
[ExpectedException(typeof(ConditionEvaluationException))]
public void TypePromotionNegativeTest1()
{
var factories = SetupConditionMethods();
Assert.AreEqual(true, ConditionParser.ParseExpression("ToDateTime('2010/01/01') == '20xx/01/01'", factories).Evaluate(CreateWellKnownContext()));
}
[Test]
[ExpectedException(typeof(ConditionEvaluationException))]
public void TypePromotionNegativeTest2()
{
var factories = SetupConditionMethods();
Assert.AreEqual(true, ConditionParser.ParseExpression("GetGuid() == ToInt16(1)", factories).Evaluate(CreateWellKnownContext()));
}
[Test]
public void ExceptionTest1()
{
var ex1 = new ConditionEvaluationException();
Assert.IsNotNull(ex1.Message);
}
[Test]
public void ExceptionTest2()
{
var ex1 = new ConditionEvaluationException("msg");
Assert.AreEqual("msg", ex1.Message);
}
[Test]
public void ExceptionTest3()
{
var inner = new InvalidOperationException("f");
var ex1 = new ConditionEvaluationException("msg", inner);
Assert.AreEqual("msg", ex1.Message);
Assert.AreSame(inner, ex1.InnerException);
}
#if !SILVERLIGHT && !NET_CF
[Test]
public void ExceptionTest4()
{
var inner = new InvalidOperationException("f");
var ex1 = new ConditionEvaluationException("msg", inner);
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, ex1);
ms.Position = 0;
Exception ex2 = (Exception)bf.Deserialize(ms);
Assert.AreEqual("msg", ex2.Message);
Assert.AreEqual("f", ex2.InnerException.Message);
}
#endif
[Test]
public void ExceptionTest11()
{
var ex1 = new ConditionParseException();
Assert.IsNotNull(ex1.Message);
}
[Test]
public void ExceptionTest12()
{
var ex1 = new ConditionParseException("msg");
Assert.AreEqual("msg", ex1.Message);
}
[Test]
public void ExceptionTest13()
{
var inner = new InvalidOperationException("f");
var ex1 = new ConditionParseException("msg", inner);
Assert.AreEqual("msg", ex1.Message);
Assert.AreSame(inner, ex1.InnerException);
}
#if !SILVERLIGHT && !NET_CF
[Test]
public void ExceptionTest14()
{
var inner = new InvalidOperationException("f");
var ex1 = new ConditionParseException("msg", inner);
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, ex1);
ms.Position = 0;
Exception ex2 = (Exception)bf.Deserialize(ms);
Assert.AreEqual("msg", ex2.Message);
Assert.AreEqual("f", ex2.InnerException.Message);
}
#endif
private static ConfigurationItemFactory SetupConditionMethods()
{
var factories = new ConfigurationItemFactory();
factories.ConditionMethods.RegisterDefinition("GetGuid", typeof(MyConditionMethods).GetMethod("GetGuid"));
factories.ConditionMethods.RegisterDefinition("ToInt16", typeof(MyConditionMethods).GetMethod("ToInt16"));
factories.ConditionMethods.RegisterDefinition("ToInt32", typeof(MyConditionMethods).GetMethod("ToInt32"));
factories.ConditionMethods.RegisterDefinition("ToInt64", typeof(MyConditionMethods).GetMethod("ToInt64"));
factories.ConditionMethods.RegisterDefinition("ToDouble", typeof(MyConditionMethods).GetMethod("ToDouble"));
factories.ConditionMethods.RegisterDefinition("ToSingle", typeof(MyConditionMethods).GetMethod("ToSingle"));
factories.ConditionMethods.RegisterDefinition("ToDateTime", typeof(MyConditionMethods).GetMethod("ToDateTime"));
factories.ConditionMethods.RegisterDefinition("ToDecimal", typeof(MyConditionMethods).GetMethod("ToDecimal"));
factories.ConditionMethods.RegisterDefinition("IsValid", typeof(MyConditionMethods).GetMethod("IsValid"));
return factories;
}
private static void AssertEvaluationResult(object expectedResult, string conditionText)
{
ConditionExpression condition = ConditionParser.ParseExpression(conditionText);
LogEventInfo context = CreateWellKnownContext();
object actualResult = condition.Evaluate(context);
Assert.AreEqual(expectedResult, actualResult);
}
private static LogEventInfo CreateWellKnownContext()
{
var context = new LogEventInfo
{
Level = LogLevel.Warn,
Message = "some message",
LoggerName = "MyCompany.Product.Class"
};
return context;
}
/// <summary>
/// Conversion methods helpful in covering type promotion logic
/// </summary>
public class MyConditionMethods
{
public static Guid GetGuid()
{
return new Guid("{40190B01-C9C0-4F78-AA5A-615E413742E1}");
}
public static short ToInt16(object v)
{
return Convert.ToInt16(v, CultureInfo.InvariantCulture);
}
public static int ToInt32(object v)
{
return Convert.ToInt32(v, CultureInfo.InvariantCulture);
}
public static long ToInt64(object v)
{
return Convert.ToInt64(v, CultureInfo.InvariantCulture);
}
public static float ToSingle(object v)
{
return Convert.ToSingle(v, CultureInfo.InvariantCulture);
}
public static decimal ToDecimal(object v)
{
return Convert.ToDecimal(v, CultureInfo.InvariantCulture);
}
public static double ToDouble(object v)
{
return Convert.ToDouble(v, CultureInfo.InvariantCulture);
}
public static DateTime ToDateTime(object v)
{
return Convert.ToDateTime(v, CultureInfo.InvariantCulture);
}
public static bool IsValid(LogEventInfo context)
{
return true;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Threading;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Threading
{
public class AsynchronousWorkerTests
{
private readonly SynchronizationContext _foregroundSyncContext;
public AsynchronousWorkerTests()
{
TestWorkspace.ResetThreadAffinity();
_foregroundSyncContext = SynchronizationContext.Current;
Assert.NotNull(_foregroundSyncContext);
}
// Ensure a background action actually runs on the background.
[WpfFact]
public void TestBackgroundAction()
{
var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test");
var worker = new AsynchronousSerialWorkQueue(listener);
var doneEvent = new AutoResetEvent(initialState: false);
var actionRan = false;
worker.EnqueueBackgroundWork(() =>
{
// Assert.NotNull(SynchronizationContext.Current);
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
actionRan = true;
doneEvent.Set();
}, GetType().Name + ".TestBackgroundAction", CancellationToken.None);
doneEvent.WaitOne();
Assert.True(actionRan);
}
[WpfFact]
public void TestMultipleBackgroundAction()
{
// Test that background actions don't run at the same time.
var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test");
var worker = new AsynchronousSerialWorkQueue(listener);
var doneEvent = new AutoResetEvent(false);
var action1Ran = false;
var action2Ran = false;
worker.EnqueueBackgroundWork(() =>
{
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
action1Ran = true;
// Simulate work to ensure that if tasks overlap that we will
// see it.
Thread.Sleep(1000);
Assert.False(action2Ran);
}, "Test", CancellationToken.None);
worker.EnqueueBackgroundWork(() =>
{
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
action2Ran = true;
doneEvent.Set();
}, "Test", CancellationToken.None);
doneEvent.WaitOne();
Assert.True(action1Ran);
Assert.True(action2Ran);
}
[WpfFact]
public void TestBackgroundCancel1()
{
// Ensure that we can cancel a background action.
var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test");
var worker = new AsynchronousSerialWorkQueue(listener);
var taskRunningEvent = new AutoResetEvent(false);
var cancelEvent = new AutoResetEvent(false);
var doneEvent = new AutoResetEvent(false);
var source = new CancellationTokenSource();
var cancellationToken = source.Token;
var actionRan = false;
worker.EnqueueBackgroundWork(() =>
{
actionRan = true;
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
Assert.False(cancellationToken.IsCancellationRequested);
taskRunningEvent.Set();
cancelEvent.WaitOne();
Assert.True(cancellationToken.IsCancellationRequested);
doneEvent.Set();
}, "Test", source.Token);
taskRunningEvent.WaitOne();
source.Cancel();
cancelEvent.Set();
doneEvent.WaitOne();
Assert.True(actionRan);
}
[WpfFact]
public void TestBackgroundCancelOneAction()
{
// Ensure that when a background action is cancelled the next
// one starts (if it has a different cancellation token).
var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test");
var worker = new AsynchronousSerialWorkQueue(listener);
var taskRunningEvent = new AutoResetEvent(false);
var cancelEvent = new AutoResetEvent(false);
var doneEvent = new AutoResetEvent(false);
var source1 = new CancellationTokenSource();
var source2 = new CancellationTokenSource();
var token1 = source1.Token;
var token2 = source2.Token;
var action1Ran = false;
var action2Ran = false;
worker.EnqueueBackgroundWork(() =>
{
action1Ran = true;
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
Assert.False(token1.IsCancellationRequested);
taskRunningEvent.Set();
cancelEvent.WaitOne();
token1.ThrowIfCancellationRequested();
Assert.True(false);
}, "Test", source1.Token);
worker.EnqueueBackgroundWork(() =>
{
action2Ran = true;
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
Assert.False(token2.IsCancellationRequested);
taskRunningEvent.Set();
cancelEvent.WaitOne();
doneEvent.Set();
}, "Test", source2.Token);
// Wait for the first task to start.
taskRunningEvent.WaitOne();
// Cancel it
source1.Cancel();
cancelEvent.Set();
// Wait for the second task to start.
taskRunningEvent.WaitOne();
cancelEvent.Set();
// Wait for the second task to complete.
doneEvent.WaitOne();
Assert.True(action1Ran);
Assert.True(action2Ran);
}
[WpfFact]
public void TestBackgroundCancelMultipleActions()
{
// Ensure that multiple background actions are cancelled if they
// use the same cancellation token.
var listener = new AggregateAsynchronousOperationListener(Enumerable.Empty<Lazy<IAsynchronousOperationListener, FeatureMetadata>>(), "Test");
var worker = new AsynchronousSerialWorkQueue(listener);
var taskRunningEvent = new AutoResetEvent(false);
var cancelEvent = new AutoResetEvent(false);
var doneEvent = new AutoResetEvent(false);
var source = new CancellationTokenSource();
var cancellationToken = source.Token;
var action1Ran = false;
var action2Ran = false;
worker.EnqueueBackgroundWork(() =>
{
action1Ran = true;
Assert.NotSame(_foregroundSyncContext, SynchronizationContext.Current);
Assert.False(cancellationToken.IsCancellationRequested);
taskRunningEvent.Set();
cancelEvent.WaitOne();
cancellationToken.ThrowIfCancellationRequested();
Assert.True(false);
}, "Test", source.Token);
// We should not run this action.
worker.EnqueueBackgroundWork(() =>
{
action2Ran = true;
Assert.False(true);
}, "Test", source.Token);
taskRunningEvent.WaitOne();
source.Cancel();
cancelEvent.Set();
try
{
worker.WaitUntilCompletion_ForTestingPurposesOnly();
Assert.True(false);
}
catch (AggregateException ae)
{
Assert.IsAssignableFrom<OperationCanceledException>(ae.InnerException);
}
Assert.True(action1Ran);
Assert.False(action2Ran);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using C1.Win.C1Input;
using C1.Win.C1List;
using PCSComProduct.STDCost.BO;
using PCSComUtils.Common;
using PCSComUtils.Common.BO;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSProduct.STDCost
{
/// <summary>
/// Summary description for CostRollup.
/// </summary>
public class CostRollup : Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
const string THIS = "PCSProduct.STDCost.CostRollup";
string OriginalMessage = string.Empty;
private System.Windows.Forms.Label lblStandardCost;
private System.Windows.Forms.Label lblProcessing;
private System.Windows.Forms.PictureBox picProcessing;
private C1.Win.C1Input.C1DateEdit dtmDate;
private C1.Win.C1List.C1Combo cboCCN;
private System.Windows.Forms.Label lblDate;
private System.Windows.Forms.Label lblCCN;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.Button btnRollUp;
Thread thrProcess = null;
public CostRollup()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(CostRollup));
this.lblStandardCost = new System.Windows.Forms.Label();
this.lblProcessing = new System.Windows.Forms.Label();
this.picProcessing = new System.Windows.Forms.PictureBox();
this.dtmDate = new C1.Win.C1Input.C1DateEdit();
this.cboCCN = new C1.Win.C1List.C1Combo();
this.lblDate = new System.Windows.Forms.Label();
this.lblCCN = new System.Windows.Forms.Label();
this.btnHelp = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.btnRollUp = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dtmDate)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).BeginInit();
this.SuspendLayout();
//
// lblStandardCost
//
this.lblStandardCost.AccessibleDescription = resources.GetString("lblStandardCost.AccessibleDescription");
this.lblStandardCost.AccessibleName = resources.GetString("lblStandardCost.AccessibleName");
this.lblStandardCost.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblStandardCost.Anchor")));
this.lblStandardCost.AutoSize = ((bool)(resources.GetObject("lblStandardCost.AutoSize")));
this.lblStandardCost.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblStandardCost.Dock")));
this.lblStandardCost.Enabled = ((bool)(resources.GetObject("lblStandardCost.Enabled")));
this.lblStandardCost.Font = ((System.Drawing.Font)(resources.GetObject("lblStandardCost.Font")));
this.lblStandardCost.Image = ((System.Drawing.Image)(resources.GetObject("lblStandardCost.Image")));
this.lblStandardCost.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblStandardCost.ImageAlign")));
this.lblStandardCost.ImageIndex = ((int)(resources.GetObject("lblStandardCost.ImageIndex")));
this.lblStandardCost.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblStandardCost.ImeMode")));
this.lblStandardCost.Location = ((System.Drawing.Point)(resources.GetObject("lblStandardCost.Location")));
this.lblStandardCost.Name = "lblStandardCost";
this.lblStandardCost.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblStandardCost.RightToLeft")));
this.lblStandardCost.Size = ((System.Drawing.Size)(resources.GetObject("lblStandardCost.Size")));
this.lblStandardCost.TabIndex = ((int)(resources.GetObject("lblStandardCost.TabIndex")));
this.lblStandardCost.Text = resources.GetString("lblStandardCost.Text");
this.lblStandardCost.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblStandardCost.TextAlign")));
this.lblStandardCost.Visible = ((bool)(resources.GetObject("lblStandardCost.Visible")));
//
// lblProcessing
//
this.lblProcessing.AccessibleDescription = resources.GetString("lblProcessing.AccessibleDescription");
this.lblProcessing.AccessibleName = resources.GetString("lblProcessing.AccessibleName");
this.lblProcessing.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblProcessing.Anchor")));
this.lblProcessing.AutoSize = ((bool)(resources.GetObject("lblProcessing.AutoSize")));
this.lblProcessing.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblProcessing.Dock")));
this.lblProcessing.Enabled = ((bool)(resources.GetObject("lblProcessing.Enabled")));
this.lblProcessing.Font = ((System.Drawing.Font)(resources.GetObject("lblProcessing.Font")));
this.lblProcessing.Image = ((System.Drawing.Image)(resources.GetObject("lblProcessing.Image")));
this.lblProcessing.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblProcessing.ImageAlign")));
this.lblProcessing.ImageIndex = ((int)(resources.GetObject("lblProcessing.ImageIndex")));
this.lblProcessing.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblProcessing.ImeMode")));
this.lblProcessing.Location = ((System.Drawing.Point)(resources.GetObject("lblProcessing.Location")));
this.lblProcessing.Name = "lblProcessing";
this.lblProcessing.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblProcessing.RightToLeft")));
this.lblProcessing.Size = ((System.Drawing.Size)(resources.GetObject("lblProcessing.Size")));
this.lblProcessing.TabIndex = ((int)(resources.GetObject("lblProcessing.TabIndex")));
this.lblProcessing.Text = resources.GetString("lblProcessing.Text");
this.lblProcessing.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblProcessing.TextAlign")));
this.lblProcessing.Visible = ((bool)(resources.GetObject("lblProcessing.Visible")));
//
// picProcessing
//
this.picProcessing.AccessibleDescription = resources.GetString("picProcessing.AccessibleDescription");
this.picProcessing.AccessibleName = resources.GetString("picProcessing.AccessibleName");
this.picProcessing.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("picProcessing.Anchor")));
this.picProcessing.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("picProcessing.BackgroundImage")));
this.picProcessing.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("picProcessing.Dock")));
this.picProcessing.Enabled = ((bool)(resources.GetObject("picProcessing.Enabled")));
this.picProcessing.Font = ((System.Drawing.Font)(resources.GetObject("picProcessing.Font")));
this.picProcessing.Image = ((System.Drawing.Image)(resources.GetObject("picProcessing.Image")));
this.picProcessing.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("picProcessing.ImeMode")));
this.picProcessing.Location = ((System.Drawing.Point)(resources.GetObject("picProcessing.Location")));
this.picProcessing.Name = "picProcessing";
this.picProcessing.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("picProcessing.RightToLeft")));
this.picProcessing.Size = ((System.Drawing.Size)(resources.GetObject("picProcessing.Size")));
this.picProcessing.SizeMode = ((System.Windows.Forms.PictureBoxSizeMode)(resources.GetObject("picProcessing.SizeMode")));
this.picProcessing.TabIndex = ((int)(resources.GetObject("picProcessing.TabIndex")));
this.picProcessing.TabStop = false;
this.picProcessing.Text = resources.GetString("picProcessing.Text");
this.picProcessing.Visible = ((bool)(resources.GetObject("picProcessing.Visible")));
//
// dtmDate
//
this.dtmDate.AcceptsEscape = ((bool)(resources.GetObject("dtmDate.AcceptsEscape")));
this.dtmDate.AccessibleDescription = resources.GetString("dtmDate.AccessibleDescription");
this.dtmDate.AccessibleName = resources.GetString("dtmDate.AccessibleName");
this.dtmDate.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("dtmDate.Anchor")));
this.dtmDate.AutoSize = ((bool)(resources.GetObject("dtmDate.AutoSize")));
this.dtmDate.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dtmDate.BackgroundImage")));
this.dtmDate.BorderStyle = ((System.Windows.Forms.BorderStyle)(resources.GetObject("dtmDate.BorderStyle")));
//
// dtmDate.Calendar
//
this.dtmDate.Calendar.AccessibleDescription = resources.GetString("dtmDate.Calendar.AccessibleDescription");
this.dtmDate.Calendar.AccessibleName = resources.GetString("dtmDate.Calendar.AccessibleName");
this.dtmDate.Calendar.AnnuallyBoldedDates = ((System.DateTime[])(resources.GetObject("dtmDate.Calendar.AnnuallyBoldedDates")));
this.dtmDate.Calendar.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("dtmDate.Calendar.BackgroundImage")));
this.dtmDate.Calendar.BoldedDates = ((System.DateTime[])(resources.GetObject("dtmDate.Calendar.BoldedDates")));
this.dtmDate.Calendar.CalendarDimensions = ((System.Drawing.Size)(resources.GetObject("dtmDate.Calendar.CalendarDimensions")));
this.dtmDate.Calendar.Enabled = ((bool)(resources.GetObject("dtmDate.Calendar.Enabled")));
this.dtmDate.Calendar.FirstDayOfWeek = ((System.Windows.Forms.Day)(resources.GetObject("dtmDate.Calendar.FirstDayOfWeek")));
this.dtmDate.Calendar.Font = ((System.Drawing.Font)(resources.GetObject("dtmDate.Calendar.Font")));
this.dtmDate.Calendar.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmDate.Calendar.ImeMode")));
this.dtmDate.Calendar.MonthlyBoldedDates = ((System.DateTime[])(resources.GetObject("dtmDate.Calendar.MonthlyBoldedDates")));
this.dtmDate.Calendar.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmDate.Calendar.RightToLeft")));
this.dtmDate.Calendar.ShowClearButton = ((bool)(resources.GetObject("dtmDate.Calendar.ShowClearButton")));
this.dtmDate.Calendar.ShowTodayButton = ((bool)(resources.GetObject("dtmDate.Calendar.ShowTodayButton")));
this.dtmDate.Calendar.ShowWeekNumbers = ((bool)(resources.GetObject("dtmDate.Calendar.ShowWeekNumbers")));
this.dtmDate.CaseSensitive = ((bool)(resources.GetObject("dtmDate.CaseSensitive")));
this.dtmDate.Culture = ((int)(resources.GetObject("dtmDate.Culture")));
this.dtmDate.CurrentTimeZone = ((bool)(resources.GetObject("dtmDate.CurrentTimeZone")));
this.dtmDate.CustomFormat = resources.GetString("dtmDate.CustomFormat");
this.dtmDate.DaylightTimeAdjustment = ((C1.Win.C1Input.DaylightTimeAdjustmentEnum)(resources.GetObject("dtmDate.DaylightTimeAdjustment")));
this.dtmDate.DisableOnNoData = false;
this.dtmDate.DisplayFormat.CustomFormat = resources.GetString("dtmDate.DisplayFormat.CustomFormat");
this.dtmDate.DisplayFormat.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmDate.DisplayFormat.FormatType")));
this.dtmDate.DisplayFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmDate.DisplayFormat.Inherit")));
this.dtmDate.DisplayFormat.NullText = resources.GetString("dtmDate.DisplayFormat.NullText");
this.dtmDate.DisplayFormat.TrimEnd = ((bool)(resources.GetObject("dtmDate.DisplayFormat.TrimEnd")));
this.dtmDate.DisplayFormat.TrimStart = ((bool)(resources.GetObject("dtmDate.DisplayFormat.TrimStart")));
this.dtmDate.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("dtmDate.Dock")));
this.dtmDate.DropDownFormAlign = ((C1.Win.C1Input.DropDownFormAlignmentEnum)(resources.GetObject("dtmDate.DropDownFormAlign")));
this.dtmDate.EditFormat.CustomFormat = resources.GetString("dtmDate.EditFormat.CustomFormat");
this.dtmDate.EditFormat.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmDate.EditFormat.FormatType")));
this.dtmDate.EditFormat.Inherit = ((C1.Win.C1Input.FormatInfoInheritFlags)(resources.GetObject("dtmDate.EditFormat.Inherit")));
this.dtmDate.EditFormat.NullText = resources.GetString("dtmDate.EditFormat.NullText");
this.dtmDate.EditFormat.TrimEnd = ((bool)(resources.GetObject("dtmDate.EditFormat.TrimEnd")));
this.dtmDate.EditFormat.TrimStart = ((bool)(resources.GetObject("dtmDate.EditFormat.TrimStart")));
this.dtmDate.EditMask = resources.GetString("dtmDate.EditMask");
this.dtmDate.EmptyAsNull = ((bool)(resources.GetObject("dtmDate.EmptyAsNull")));
this.dtmDate.Enabled = ((bool)(resources.GetObject("dtmDate.Enabled")));
this.dtmDate.ErrorInfo.BeepOnError = ((bool)(resources.GetObject("dtmDate.ErrorInfo.BeepOnError")));
this.dtmDate.ErrorInfo.ErrorMessage = resources.GetString("dtmDate.ErrorInfo.ErrorMessage");
this.dtmDate.ErrorInfo.ErrorMessageCaption = resources.GetString("dtmDate.ErrorInfo.ErrorMessageCaption");
this.dtmDate.ErrorInfo.ShowErrorMessage = ((bool)(resources.GetObject("dtmDate.ErrorInfo.ShowErrorMessage")));
this.dtmDate.ErrorInfo.ValueOnError = ((object)(resources.GetObject("dtmDate.ErrorInfo.ValueOnError")));
this.dtmDate.Font = ((System.Drawing.Font)(resources.GetObject("dtmDate.Font")));
this.dtmDate.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmDate.FormatType")));
this.dtmDate.GapHeight = ((int)(resources.GetObject("dtmDate.GapHeight")));
this.dtmDate.GMTOffset = ((System.TimeSpan)(resources.GetObject("dtmDate.GMTOffset")));
this.dtmDate.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("dtmDate.ImeMode")));
this.dtmDate.InitialSelection = ((C1.Win.C1Input.InitialSelectionEnum)(resources.GetObject("dtmDate.InitialSelection")));
this.dtmDate.Location = ((System.Drawing.Point)(resources.GetObject("dtmDate.Location")));
this.dtmDate.MaskInfo.AutoTabWhenFilled = ((bool)(resources.GetObject("dtmDate.MaskInfo.AutoTabWhenFilled")));
this.dtmDate.MaskInfo.CaseSensitive = ((bool)(resources.GetObject("dtmDate.MaskInfo.CaseSensitive")));
this.dtmDate.MaskInfo.CopyWithLiterals = ((bool)(resources.GetObject("dtmDate.MaskInfo.CopyWithLiterals")));
this.dtmDate.MaskInfo.EditMask = resources.GetString("dtmDate.MaskInfo.EditMask");
this.dtmDate.MaskInfo.EmptyAsNull = ((bool)(resources.GetObject("dtmDate.MaskInfo.EmptyAsNull")));
this.dtmDate.MaskInfo.ErrorMessage = resources.GetString("dtmDate.MaskInfo.ErrorMessage");
this.dtmDate.MaskInfo.Inherit = ((C1.Win.C1Input.MaskInfoInheritFlags)(resources.GetObject("dtmDate.MaskInfo.Inherit")));
this.dtmDate.MaskInfo.PromptChar = ((char)(resources.GetObject("dtmDate.MaskInfo.PromptChar")));
this.dtmDate.MaskInfo.ShowLiterals = ((C1.Win.C1Input.ShowLiteralsEnum)(resources.GetObject("dtmDate.MaskInfo.ShowLiterals")));
this.dtmDate.MaskInfo.StoredEmptyChar = ((char)(resources.GetObject("dtmDate.MaskInfo.StoredEmptyChar")));
this.dtmDate.MaxLength = ((int)(resources.GetObject("dtmDate.MaxLength")));
this.dtmDate.Name = "dtmDate";
this.dtmDate.NullText = resources.GetString("dtmDate.NullText");
this.dtmDate.ParseInfo.CaseSensitive = ((bool)(resources.GetObject("dtmDate.ParseInfo.CaseSensitive")));
this.dtmDate.ParseInfo.CustomFormat = resources.GetString("dtmDate.ParseInfo.CustomFormat");
this.dtmDate.ParseInfo.DateTimeStyle = ((C1.Win.C1Input.DateTimeStyleFlags)(resources.GetObject("dtmDate.ParseInfo.DateTimeStyle")));
this.dtmDate.ParseInfo.EmptyAsNull = ((bool)(resources.GetObject("dtmDate.ParseInfo.EmptyAsNull")));
this.dtmDate.ParseInfo.ErrorMessage = resources.GetString("dtmDate.ParseInfo.ErrorMessage");
this.dtmDate.ParseInfo.FormatType = ((C1.Win.C1Input.FormatTypeEnum)(resources.GetObject("dtmDate.ParseInfo.FormatType")));
this.dtmDate.ParseInfo.Inherit = ((C1.Win.C1Input.ParseInfoInheritFlags)(resources.GetObject("dtmDate.ParseInfo.Inherit")));
this.dtmDate.ParseInfo.NullText = resources.GetString("dtmDate.ParseInfo.NullText");
this.dtmDate.ParseInfo.TrimEnd = ((bool)(resources.GetObject("dtmDate.ParseInfo.TrimEnd")));
this.dtmDate.ParseInfo.TrimStart = ((bool)(resources.GetObject("dtmDate.ParseInfo.TrimStart")));
this.dtmDate.PasswordChar = ((char)(resources.GetObject("dtmDate.PasswordChar")));
this.dtmDate.PostValidation.CaseSensitive = ((bool)(resources.GetObject("dtmDate.PostValidation.CaseSensitive")));
this.dtmDate.PostValidation.ErrorMessage = resources.GetString("dtmDate.PostValidation.ErrorMessage");
this.dtmDate.PostValidation.Inherit = ((C1.Win.C1Input.PostValidationInheritFlags)(resources.GetObject("dtmDate.PostValidation.Inherit")));
this.dtmDate.PostValidation.Validation = ((C1.Win.C1Input.PostValidationTypeEnum)(resources.GetObject("dtmDate.PostValidation.Validation")));
this.dtmDate.PostValidation.Values = ((System.Array)(resources.GetObject("dtmDate.PostValidation.Values")));
this.dtmDate.PostValidation.ValuesExcluded = ((System.Array)(resources.GetObject("dtmDate.PostValidation.ValuesExcluded")));
this.dtmDate.PreValidation.CaseSensitive = ((bool)(resources.GetObject("dtmDate.PreValidation.CaseSensitive")));
this.dtmDate.PreValidation.ErrorMessage = resources.GetString("dtmDate.PreValidation.ErrorMessage");
this.dtmDate.PreValidation.Inherit = ((C1.Win.C1Input.PreValidationInheritFlags)(resources.GetObject("dtmDate.PreValidation.Inherit")));
this.dtmDate.PreValidation.ItemSeparator = resources.GetString("dtmDate.PreValidation.ItemSeparator");
this.dtmDate.PreValidation.PatternString = resources.GetString("dtmDate.PreValidation.PatternString");
this.dtmDate.PreValidation.RegexOptions = ((C1.Win.C1Input.RegexOptionFlags)(resources.GetObject("dtmDate.PreValidation.RegexOptions")));
this.dtmDate.PreValidation.TrimEnd = ((bool)(resources.GetObject("dtmDate.PreValidation.TrimEnd")));
this.dtmDate.PreValidation.TrimStart = ((bool)(resources.GetObject("dtmDate.PreValidation.TrimStart")));
this.dtmDate.PreValidation.Validation = ((C1.Win.C1Input.PreValidationTypeEnum)(resources.GetObject("dtmDate.PreValidation.Validation")));
this.dtmDate.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("dtmDate.RightToLeft")));
this.dtmDate.ShowFocusRectangle = ((bool)(resources.GetObject("dtmDate.ShowFocusRectangle")));
this.dtmDate.Size = ((System.Drawing.Size)(resources.GetObject("dtmDate.Size")));
this.dtmDate.TabIndex = ((int)(resources.GetObject("dtmDate.TabIndex")));
this.dtmDate.Tag = ((object)(resources.GetObject("dtmDate.Tag")));
this.dtmDate.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("dtmDate.TextAlign")));
this.dtmDate.TrimEnd = ((bool)(resources.GetObject("dtmDate.TrimEnd")));
this.dtmDate.TrimStart = ((bool)(resources.GetObject("dtmDate.TrimStart")));
this.dtmDate.UserCultureOverride = ((bool)(resources.GetObject("dtmDate.UserCultureOverride")));
this.dtmDate.Value = ((object)(resources.GetObject("dtmDate.Value")));
this.dtmDate.VerticalAlign = ((C1.Win.C1Input.VerticalAlignEnum)(resources.GetObject("dtmDate.VerticalAlign")));
this.dtmDate.Visible = ((bool)(resources.GetObject("dtmDate.Visible")));
this.dtmDate.VisibleButtons = ((C1.Win.C1Input.DropDownControlButtonFlags)(resources.GetObject("dtmDate.VisibleButtons")));
//
// cboCCN
//
this.cboCCN.AccessibleDescription = resources.GetString("cboCCN.AccessibleDescription");
this.cboCCN.AccessibleName = resources.GetString("cboCCN.AccessibleName");
this.cboCCN.AddItemSeparator = ';';
this.cboCCN.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("cboCCN.Anchor")));
this.cboCCN.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("cboCCN.BackgroundImage")));
this.cboCCN.Caption = "";
this.cboCCN.CaptionHeight = 17;
this.cboCCN.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal;
this.cboCCN.ColumnCaptionHeight = 17;
this.cboCCN.ColumnFooterHeight = 17;
this.cboCCN.ComboStyle = C1.Win.C1List.ComboStyleEnum.DropdownList;
this.cboCCN.ContentHeight = 15;
this.cboCCN.DeadAreaBackColor = System.Drawing.Color.Empty;
this.cboCCN.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("cboCCN.Dock")));
this.cboCCN.EditorBackColor = System.Drawing.SystemColors.Window;
this.cboCCN.EditorFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.cboCCN.EditorForeColor = System.Drawing.SystemColors.WindowText;
this.cboCCN.EditorHeight = 15;
this.cboCCN.Enabled = ((bool)(resources.GetObject("cboCCN.Enabled")));
this.cboCCN.FlatStyle = C1.Win.C1List.FlatModeEnum.System;
this.cboCCN.Font = ((System.Drawing.Font)(resources.GetObject("cboCCN.Font")));
this.cboCCN.GapHeight = 2;
this.cboCCN.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("cboCCN.ImeMode")));
this.cboCCN.ItemHeight = 15;
this.cboCCN.Location = ((System.Drawing.Point)(resources.GetObject("cboCCN.Location")));
this.cboCCN.MatchEntryTimeout = ((long)(2000));
this.cboCCN.MaxDropDownItems = ((short)(5));
this.cboCCN.MaxLength = 32767;
this.cboCCN.MouseCursor = System.Windows.Forms.Cursors.Default;
this.cboCCN.Name = "cboCCN";
this.cboCCN.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("cboCCN.RightToLeft")));
this.cboCCN.RowDivider.Color = System.Drawing.Color.DarkGray;
this.cboCCN.RowDivider.Style = C1.Win.C1List.LineStyleEnum.None;
this.cboCCN.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.cboCCN.Size = ((System.Drawing.Size)(resources.GetObject("cboCCN.Size")));
this.cboCCN.TabIndex = ((int)(resources.GetObject("cboCCN.TabIndex")));
this.cboCCN.Text = resources.GetString("cboCCN.Text");
this.cboCCN.Visible = ((bool)(resources.GetObject("cboCCN.Visible")));
this.cboCCN.PropBag = "<?xml version=\"1.0\"?><Blob><Styles type=\"C1.Win.C1List.Design.ContextWrapper\"><Da" +
"ta>Group{BackColor:ControlDark;Border:None,,0, 0, 0, 0;AlignVert:Center;}Style2{" +
"}Style5{}Style4{}Style7{}Style6{}EvenRow{BackColor:Aqua;}Selected{ForeColor:High" +
"lightText;BackColor:Highlight;}Style3{}Inactive{ForeColor:InactiveCaptionText;Ba" +
"ckColor:InactiveCaption;}Footer{}Caption{AlignHorz:Center;}Normal{BackColor:Wind" +
"ow;}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}Style9{AlignHorz:N" +
"ear;}OddRow{}RecordSelector{AlignImage:Center;}Heading{Wrap:True;AlignVert:Cente" +
"r;Border:Raised,,1, 1, 1, 1;ForeColor:ControlText;BackColor:Control;}Style8{}Sty" +
"le10{}Style11{}Style1{}</Data></Styles><Splits><C1.Win.C1List.ListBoxView AllowC" +
"olSelect=\"False\" Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\" ColumnFoote" +
"rHeight=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><ClientRect>0, 0," +
" 118, 158</ClientRect><VScrollBar><Width>17</Width></VScrollBar><HScrollBar><Hei" +
"ght>17</Height></HScrollBar><CaptionStyle parent=\"Style2\" me=\"Style9\" /><EvenRow" +
"Style parent=\"EvenRow\" me=\"Style7\" /><FooterStyle parent=\"Footer\" me=\"Style3\" />" +
"<GroupStyle parent=\"Group\" me=\"Style11\" /><HeadingStyle parent=\"Heading\" me=\"Sty" +
"le2\" /><HighLightRowStyle parent=\"HighlightRow\" me=\"Style6\" /><InactiveStyle par" +
"ent=\"Inactive\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style8\" /><RecordS" +
"electorStyle parent=\"RecordSelector\" me=\"Style10\" /><SelectedStyle parent=\"Selec" +
"ted\" me=\"Style5\" /><Style parent=\"Normal\" me=\"Style1\" /></C1.Win.C1List.ListBoxV" +
"iew></Splits><NamedStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" " +
"me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=" +
"\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"S" +
"elected\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=" +
"\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"Rec" +
"ordSelector\" /><Style parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1<" +
"/vertSplits><horzSplits>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWid" +
"th>17</DefaultRecSelWidth></Blob>";
//
// lblDate
//
this.lblDate.AccessibleDescription = resources.GetString("lblDate.AccessibleDescription");
this.lblDate.AccessibleName = resources.GetString("lblDate.AccessibleName");
this.lblDate.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblDate.Anchor")));
this.lblDate.AutoSize = ((bool)(resources.GetObject("lblDate.AutoSize")));
this.lblDate.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblDate.Dock")));
this.lblDate.Enabled = ((bool)(resources.GetObject("lblDate.Enabled")));
this.lblDate.Font = ((System.Drawing.Font)(resources.GetObject("lblDate.Font")));
this.lblDate.ForeColor = System.Drawing.Color.Maroon;
this.lblDate.Image = ((System.Drawing.Image)(resources.GetObject("lblDate.Image")));
this.lblDate.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblDate.ImageAlign")));
this.lblDate.ImageIndex = ((int)(resources.GetObject("lblDate.ImageIndex")));
this.lblDate.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblDate.ImeMode")));
this.lblDate.Location = ((System.Drawing.Point)(resources.GetObject("lblDate.Location")));
this.lblDate.Name = "lblDate";
this.lblDate.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblDate.RightToLeft")));
this.lblDate.Size = ((System.Drawing.Size)(resources.GetObject("lblDate.Size")));
this.lblDate.TabIndex = ((int)(resources.GetObject("lblDate.TabIndex")));
this.lblDate.Text = resources.GetString("lblDate.Text");
this.lblDate.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblDate.TextAlign")));
this.lblDate.Visible = ((bool)(resources.GetObject("lblDate.Visible")));
//
// lblCCN
//
this.lblCCN.AccessibleDescription = resources.GetString("lblCCN.AccessibleDescription");
this.lblCCN.AccessibleName = resources.GetString("lblCCN.AccessibleName");
this.lblCCN.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lblCCN.Anchor")));
this.lblCCN.AutoSize = ((bool)(resources.GetObject("lblCCN.AutoSize")));
this.lblCCN.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lblCCN.Dock")));
this.lblCCN.Enabled = ((bool)(resources.GetObject("lblCCN.Enabled")));
this.lblCCN.Font = ((System.Drawing.Font)(resources.GetObject("lblCCN.Font")));
this.lblCCN.ForeColor = System.Drawing.Color.Maroon;
this.lblCCN.Image = ((System.Drawing.Image)(resources.GetObject("lblCCN.Image")));
this.lblCCN.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblCCN.ImageAlign")));
this.lblCCN.ImageIndex = ((int)(resources.GetObject("lblCCN.ImageIndex")));
this.lblCCN.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lblCCN.ImeMode")));
this.lblCCN.Location = ((System.Drawing.Point)(resources.GetObject("lblCCN.Location")));
this.lblCCN.Name = "lblCCN";
this.lblCCN.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lblCCN.RightToLeft")));
this.lblCCN.Size = ((System.Drawing.Size)(resources.GetObject("lblCCN.Size")));
this.lblCCN.TabIndex = ((int)(resources.GetObject("lblCCN.TabIndex")));
this.lblCCN.Text = resources.GetString("lblCCN.Text");
this.lblCCN.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("lblCCN.TextAlign")));
this.lblCCN.Visible = ((bool)(resources.GetObject("lblCCN.Visible")));
//
// btnHelp
//
this.btnHelp.AccessibleDescription = resources.GetString("btnHelp.AccessibleDescription");
this.btnHelp.AccessibleName = resources.GetString("btnHelp.AccessibleName");
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnHelp.Anchor")));
this.btnHelp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnHelp.BackgroundImage")));
this.btnHelp.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnHelp.Dock")));
this.btnHelp.Enabled = ((bool)(resources.GetObject("btnHelp.Enabled")));
this.btnHelp.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnHelp.FlatStyle")));
this.btnHelp.Font = ((System.Drawing.Font)(resources.GetObject("btnHelp.Font")));
this.btnHelp.Image = ((System.Drawing.Image)(resources.GetObject("btnHelp.Image")));
this.btnHelp.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.ImageAlign")));
this.btnHelp.ImageIndex = ((int)(resources.GetObject("btnHelp.ImageIndex")));
this.btnHelp.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnHelp.ImeMode")));
this.btnHelp.Location = ((System.Drawing.Point)(resources.GetObject("btnHelp.Location")));
this.btnHelp.Name = "btnHelp";
this.btnHelp.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnHelp.RightToLeft")));
this.btnHelp.Size = ((System.Drawing.Size)(resources.GetObject("btnHelp.Size")));
this.btnHelp.TabIndex = ((int)(resources.GetObject("btnHelp.TabIndex")));
this.btnHelp.Text = resources.GetString("btnHelp.Text");
this.btnHelp.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnHelp.TextAlign")));
this.btnHelp.Visible = ((bool)(resources.GetObject("btnHelp.Visible")));
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnClose
//
this.btnClose.AccessibleDescription = resources.GetString("btnClose.AccessibleDescription");
this.btnClose.AccessibleName = resources.GetString("btnClose.AccessibleName");
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnClose.Anchor")));
this.btnClose.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnClose.BackgroundImage")));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnClose.Dock")));
this.btnClose.Enabled = ((bool)(resources.GetObject("btnClose.Enabled")));
this.btnClose.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnClose.FlatStyle")));
this.btnClose.Font = ((System.Drawing.Font)(resources.GetObject("btnClose.Font")));
this.btnClose.Image = ((System.Drawing.Image)(resources.GetObject("btnClose.Image")));
this.btnClose.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.ImageAlign")));
this.btnClose.ImageIndex = ((int)(resources.GetObject("btnClose.ImageIndex")));
this.btnClose.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnClose.ImeMode")));
this.btnClose.Location = ((System.Drawing.Point)(resources.GetObject("btnClose.Location")));
this.btnClose.Name = "btnClose";
this.btnClose.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnClose.RightToLeft")));
this.btnClose.Size = ((System.Drawing.Size)(resources.GetObject("btnClose.Size")));
this.btnClose.TabIndex = ((int)(resources.GetObject("btnClose.TabIndex")));
this.btnClose.Text = resources.GetString("btnClose.Text");
this.btnClose.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnClose.TextAlign")));
this.btnClose.Visible = ((bool)(resources.GetObject("btnClose.Visible")));
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnRollUp
//
this.btnRollUp.AccessibleDescription = resources.GetString("btnRollUp.AccessibleDescription");
this.btnRollUp.AccessibleName = resources.GetString("btnRollUp.AccessibleName");
this.btnRollUp.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("btnRollUp.Anchor")));
this.btnRollUp.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnRollUp.BackgroundImage")));
this.btnRollUp.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("btnRollUp.Dock")));
this.btnRollUp.Enabled = ((bool)(resources.GetObject("btnRollUp.Enabled")));
this.btnRollUp.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("btnRollUp.FlatStyle")));
this.btnRollUp.Font = ((System.Drawing.Font)(resources.GetObject("btnRollUp.Font")));
this.btnRollUp.Image = ((System.Drawing.Image)(resources.GetObject("btnRollUp.Image")));
this.btnRollUp.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnRollUp.ImageAlign")));
this.btnRollUp.ImageIndex = ((int)(resources.GetObject("btnRollUp.ImageIndex")));
this.btnRollUp.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("btnRollUp.ImeMode")));
this.btnRollUp.Location = ((System.Drawing.Point)(resources.GetObject("btnRollUp.Location")));
this.btnRollUp.Name = "btnRollUp";
this.btnRollUp.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("btnRollUp.RightToLeft")));
this.btnRollUp.Size = ((System.Drawing.Size)(resources.GetObject("btnRollUp.Size")));
this.btnRollUp.TabIndex = ((int)(resources.GetObject("btnRollUp.TabIndex")));
this.btnRollUp.Text = resources.GetString("btnRollUp.Text");
this.btnRollUp.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("btnRollUp.TextAlign")));
this.btnRollUp.Visible = ((bool)(resources.GetObject("btnRollUp.Visible")));
this.btnRollUp.Click += new System.EventHandler(this.btnRollUp_Click);
//
// CostRollup
//
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.lblProcessing);
this.Controls.Add(this.picProcessing);
this.Controls.Add(this.dtmDate);
this.Controls.Add(this.cboCCN);
this.Controls.Add(this.lblDate);
this.Controls.Add(this.lblCCN);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnRollUp);
this.Controls.Add(this.lblStandardCost);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode")));
this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
this.MaximizeBox = false;
this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "CostRollup";
this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.Closing += new System.ComponentModel.CancelEventHandler(this.CostRollup_Closing);
this.Load += new System.EventHandler(this.CostRollup_Load);
((System.ComponentModel.ISupportInitialize)(this.dtmDate)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cboCCN)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// List CCN, fill default CCN
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CostRollup_Load(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".CostRollup_Load()";
try
{
Security objSecurity = new Security();
this.Name = THIS;
if (objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return;
}
this.MaximizeBox = false;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
lblProcessing.Visible = false;
picProcessing.Visible = false;
UtilsBO boUtils = new UtilsBO();
// put data into CCN combo
FormControlComponents.PutDataIntoC1ComboBox(cboCCN, boUtils.ListCCN().Tables[0], MST_CCNTable.CODE_FLD, MST_CCNTable.CCNID_FLD, MST_CCNTable.TABLE_NAME);
// set default CCN
cboCCN.SelectedValue = SystemProperty.CCNID;
// get current server date
dtmDate.Value = boUtils.GetDBDate();
OriginalMessage = this.Text;
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
/// <summary>
/// Rollup cost for all items in system
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRollUp_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnRollUp_Click()";
try
{
if (FormControlComponents.CheckMandatory(cboCCN))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error);
cboCCN.Focus();
cboCCN.Select();
return;
}
if (FormControlComponents.CheckMandatory(dtmDate))
{
PCSMessageBox.Show(ErrorCode.MANDATORY_INVALID, MessageBoxButtons.OK, MessageBoxIcon.Error);
dtmDate.Focus();
dtmDate.Select();
return;
}
lblCCN.Enabled = false;
lblDate.Enabled = false;
cboCCN.ReadOnly = true;
dtmDate.ReadOnly = true;
lblProcessing.Visible = true;
lblProcessing.Text = string.Format("{0} - {1}", lblProcessing.Text, this.Text);
picProcessing.Visible = true;
btnRollUp.Enabled = false;
thrProcess = new Thread(new ThreadStart(RollUp));
thrProcess.Start();
if (thrProcess.ThreadState == ThreadState.Stopped || !thrProcess.IsAlive)
{
thrProcess = null;
}
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
}
private void btnHelp_Click(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
// close the form
this.Close();
}
private void CostRollup_Closing(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".CostRollup_Closing()";
try
{
// ask user to stop the thread
if (thrProcess != null)
{
if (thrProcess.IsAlive || thrProcess.ThreadState == ThreadState.Running)
{
string[] strMsg = {this.Text};
DialogResult dlgResult = PCSMessageBox.Show(ErrorCode.MESSAGE_PROCESS_IS_RUNNING, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, strMsg);
switch (dlgResult)
{
case DialogResult.OK:
// try to stop the thread
try
{
thrProcess.Abort();
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex.Message, METHOD_NAME, Level.DEBUG);
e.Cancel = false;
}
break;
case DialogResult.Cancel:
e.Cancel = true;
break;
}
}
}
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex.Message, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Main function of roll up thread
/// </summary>
private void RollUp()
{
const string METHOD_NAME = THIS + ".RollUp()";
try
{
CostRollupBO boCostRollUp = new CostRollupBO();
DateTime dtmRollupDate = (DateTime)dtmDate.Value;
int intCCNID = int.Parse(cboCCN.SelectedValue.ToString());
boCostRollUp.RollUp(dtmRollupDate, intCCNID);
string[] strMsg = new string[]{this.Text};
PCSMessageBox.Show(ErrorCode.MESSAGE_TASK_COMPLETED, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, strMsg);
}
catch (ThreadAbortException ex)
{
Logger.LogMessage(ex, METHOD_NAME, Level.DEBUG);
}
catch (PCSException ex)
{
if (ex.mCode == ErrorCode.MESSAGE_CAN_NOT_DELETE)
{
string[] strMsg = new string[]{lblStandardCost.Text};
PCSMessageBox.Show(ErrorCode.MESSAGE_CAN_NOT_DELETE, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, strMsg);
}
else
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
catch (Exception ex)
{
PCSMessageBox.Show(ErrorCode.OTHER_ERROR);
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION);
}
}
finally
{
lblCCN.Enabled = true;
lblDate.Enabled = true;
cboCCN.ReadOnly = false;
dtmDate.ReadOnly = false;
lblProcessing.Visible = false;
lblProcessing.Text = OriginalMessage;
picProcessing.Visible = false;
btnRollUp.Enabled = true;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLMcode = Interop.Http.CURLMcode;
using CURLoption = Interop.Http.CURLoption;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE";
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int RequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes
private readonly static CURLAUTH[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic };
private readonly static bool s_supportsAutomaticDecompression;
private readonly static bool s_supportsSSL;
private readonly MultiAgent _agent = new MultiAgent();
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = new CookieContainer();
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption;
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.LibCurl's cctor
int age;
if (!Interop.Http.GetCurlVersionInfo(out age, out s_supportsSSL, out s_supportsAutomaticDecompression))
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_no_versioninfo);
}
// Verify the version of curl we're using is new enough
if (age < MinCurlAge)
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old);
}
}
#region Properties
internal bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy
{
get
{
return true;
}
}
internal bool SupportsRedirectConfiguration
{
get
{
return true;
}
}
internal bool UseProxy
{
get
{
return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy;
}
set
{
CheckDisposedOrStarted();
_proxyPolicy = value ?
ProxyUsePolicy.UseCustomProxy :
ProxyUsePolicy.DoNotUseProxy;
}
}
internal IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials Credentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
internal ClientCertificateOption ClientCertificateOptions
{
get
{
return _clientCertificateOption;
}
set
{
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
internal bool SupportsAutomaticDecompression
{
get
{
return s_supportsAutomaticDecompression;
}
}
internal DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get
{
return _useCookie;
}
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
/// <summary>
/// <b> UseDefaultCredentials is a no op on Unix </b>
/// </summary>
internal bool UseDefaultCredentials
{
get
{
return false;
}
set
{
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
if (request.RequestUri.Scheme == UriSchemeHttps)
{
if (!s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
}
else
{
Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https.");
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
try
{
easy.InitializeCurl();
if (easy._requestContentStream != null)
{
easy._requestContentStream.Run();
}
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
return easy.Task;
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private KeyValuePair<NetworkCredential, CURLAUTH> GetNetworkCredentials(ICredentials credentials, Uri requestUri)
{
if (_preAuthenticate)
{
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
ncAndScheme = GetCredentials(_credentialCache, requestUri);
}
if (ncAndScheme.Key != null)
{
return ncAndScheme;
}
}
return GetCredentials(credentials, requestUri);
}
private void AddCredentialToCache(Uri serverUri, CURLAUTH authAvail, NetworkCredential nc)
{
lock (LockObject)
{
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
if ((authAvail & s_authSchemePriorityOrder[i]) != 0)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
try
{
_credentialCache.Add(serverUri, s_authenticationSchemes[i], nc);
}
catch(ArgumentException)
{
//Ignore the case of key already present
}
}
}
}
}
private void AddResponseCookies(Uri serverUri, HttpResponseMessage response)
{
if (!_useCookie)
{
return;
}
if (response.Headers.Contains(HttpKnownHeaderNames.SetCookie))
{
IEnumerable<string> cookieHeaders = response.Headers.GetValues(HttpKnownHeaderNames.SetCookie);
foreach (var cookieHeader in cookieHeaders)
{
try
{
_cookieContainer.SetCookies(serverUri, cookieHeader);
}
catch (CookieException e)
{
string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}",
e.Message,
serverUri.OriginalString,
cookieHeader);
VerboseTrace(msg);
}
}
}
}
private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(ICredentials credentials, Uri requestUri)
{
NetworkCredential nc = null;
CURLAUTH curlAuthScheme = CURLAUTH.None;
if (credentials != null)
{
// we collect all the schemes that are accepted by libcurl for which there is a non-null network credential.
// But CurlHandler works under following assumption:
// for a given server, the credentials do not vary across authentication schemes.
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, s_authenticationSchemes[i]);
if (networkCredential != null)
{
curlAuthScheme |= s_authSchemePriorityOrder[i];
if (nc == null)
{
nc = networkCredential;
}
else if(!AreEqualNetworkCredentials(nc, networkCredential))
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential);
}
}
}
}
VerboseTrace("curlAuthScheme = " + curlAuthScheme);
return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(CURLcode error)
{
if (error != CURLcode.CURLE_OK)
{
var inner = new CurlException((int)error, isMulti: false);
VerboseTrace(inner.Message);
throw inner;
}
}
private static void ThrowIfCURLMError(CURLMcode error)
{
if (error != CURLMcode.CURLM_OK)
{
string msg = CurlException.GetCurlErrorString((int)error, true);
VerboseTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw new CurlException((int)error, msg);
}
}
}
private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2)
{
Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check");
return credential1.UserName == credential2.UserName &&
credential1.Domain == credential2.Domain &&
string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null && easy._associatedMultiAgent != null)
{
agent = easy._associatedMultiAgent;
}
int? agentId = agent != null ? agent.RunningWorkerId : null;
// Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about
string ids = "";
if (agentId != null || easy != null)
{
ids = "(" +
(agentId != null ? "M#" + agentId : "") +
(agentId != null && easy != null ? ", " : "") +
(easy != null ? "E#" + easy.Task.Id : "") +
")";
}
// Create the message and trace it out
string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text);
Interop.Sys.PrintF("%s\n", msg);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
VerboseTrace(text, memberName, easy, agent: null);
}
}
private static Exception CreateHttpRequestException(Exception inner = null)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
{
if (!responseHeader.StartsWith(CurlResponseParseUtils.HttpPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
CurlResponseParseUtils.ReadStatusLine(response, responseHeader);
state._isRedirect = state._handler.AutomaticRedirection &&
(response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.RedirectKeepVerb ||
response.StatusCode == HttpStatusCode.RedirectMethod) ;
return true;
}
private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue)
{
Debug.Assert(state._isRedirect);
Debug.Assert(state._handler.AutomaticRedirection);
string location = locationValue.Trim();
//only for absolute redirects
Uri forwardUri;
if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri)
{
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri);
if (ncAndScheme.Key != null)
{
state.SetCredentialsOptions(ncAndScheme);
}
else
{
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
}
// reset proxy - it is possible that the proxy has different credentials for the new URI
state.SetProxyOptions(forwardUri);
if (state._handler._useCookie)
{
// reset cookies.
state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
// set cookies again
state.SetCookieOption(forwardUri);
}
}
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Tranfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
private enum ProxyUsePolicy
{
DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment.
UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any.
UseCustomProxy = 2 // Use The proxy specified by the user.
}
}
}
| |
// 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 System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientHandler_ResponseDrain_Test : HttpClientTestBase
{
public enum ContentMode
{
ContentLength,
SingleChunk,
BytePerChunk
}
private static string GetResponseForContentMode(string content, ContentMode mode)
{
switch (mode)
{
case ContentMode.ContentLength:
return LoopbackServer.GetHttpResponse(content: content);
case ContentMode.SingleChunk:
return LoopbackServer.GetSingleChunkHttpResponse(content: content);
case ContentMode.BytePerChunk:
return LoopbackServer.GetBytePerChunkHttpResponse(content: content);
default:
Assert.True(false);
return null;
}
}
[OuterLoop]
[Theory]
[InlineData(ContentMode.ContentLength)]
[InlineData(ContentMode.SingleChunk)]
[InlineData(ContentMode.BytePerChunk)]
public async Task GetAsync_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(ContentMode mode)
{
if (IsWinHttpHandler && mode == ContentMode.BytePerChunk)
{
// WinHttpHandler seems to only do a limited amount of draining when chunking is used;
// I *think* it's not draining anything beyond the current chunk being processed.
// So, these cases won't pass.
return;
}
const string simpleContent = "Hello world!";
await LoopbackServer.CreateClientAndServerAsync(
async url =>
{
using (var client = CreateHttpClient())
{
HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
ValidateResponseHeaders(response1, simpleContent.Length, mode);
// Read up to exactly 1 byte before the end of the response
Stream responseStream = await response1.Content.ReadAsStreamAsync();
byte[] bytes = await ReadToByteCount(responseStream, simpleContent.Length - 1);
Assert.Equal(simpleContent.Substring(0, simpleContent.Length - 1), Encoding.ASCII.GetString(bytes));
// Introduce a short delay to try to ensure that when we dispose the response,
// all response data is available and we can drain synchronously and reuse the connection.
await Task.Delay(100);
response1.Dispose();
// Issue another request. We'll confirm that it comes on the same connection.
HttpResponseMessage response2 = await client.GetAsync(url);
ValidateResponseHeaders(response2, simpleContent.Length, mode);
Assert.Equal(simpleContent, await response2.Content.ReadAsStringAsync());
}
},
async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
string response = GetResponseForContentMode(simpleContent, mode);
await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
});
});
}
// The actual amount of drain that's supported is handler and timing dependent, apparently.
// These cases are an attempt to provide a "min bar" for draining behavior.
[OuterLoop]
[Theory]
[InlineData(0, 0, ContentMode.ContentLength)]
[InlineData(0, 0, ContentMode.SingleChunk)]
[InlineData(1, 0, ContentMode.ContentLength)]
[InlineData(1, 0, ContentMode.SingleChunk)]
[InlineData(1, 0, ContentMode.BytePerChunk)]
[InlineData(2, 1, ContentMode.ContentLength)]
[InlineData(2, 1, ContentMode.SingleChunk)]
[InlineData(2, 1, ContentMode.BytePerChunk)]
[InlineData(10, 1, ContentMode.ContentLength)]
[InlineData(10, 1, ContentMode.SingleChunk)]
[InlineData(10, 1, ContentMode.BytePerChunk)]
[InlineData(100, 10, ContentMode.ContentLength)]
[InlineData(100, 10, ContentMode.SingleChunk)]
[InlineData(100, 10, ContentMode.BytePerChunk)]
[InlineData(1000, 950, ContentMode.ContentLength)]
[InlineData(1000, 950, ContentMode.SingleChunk)]
[InlineData(1000, 950, ContentMode.BytePerChunk)]
[InlineData(10000, 9500, ContentMode.ContentLength)]
[InlineData(10000, 9500, ContentMode.SingleChunk)]
[InlineData(10000, 9500, ContentMode.BytePerChunk)]
public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(int totalSize, int readSize, ContentMode mode)
{
if (IsWinHttpHandler &&
((mode == ContentMode.SingleChunk && readSize == 0) ||
(mode == ContentMode.BytePerChunk)))
{
// WinHttpHandler seems to only do a limited amount of draining when TE is used;
// I *think* it's not draining anything beyond the current chunk being processed.
// So, these cases won't pass.
return;
}
if (IsCurlHandler)
{
// CurlHandler drain behavior is very inconsistent, so just skip these tests.
return;
}
await LoopbackServer.CreateClientAndServerAsync(
async url =>
{
HttpClientHandler handler = CreateHttpClientHandler();
// Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to)
handler.MaxConnectionsPerServer = 1;
using (var client = new HttpClient(handler))
{
HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
ValidateResponseHeaders(response1, totalSize, mode);
// Read part but not all of response
Stream responseStream = await response1.Content.ReadAsStreamAsync();
await ReadToByteCount(responseStream, readSize);
response1.Dispose();
// Issue another request. We'll confirm that it comes on the same connection.
HttpResponseMessage response2 = await client.GetAsync(url);
ValidateResponseHeaders(response2, totalSize, mode);
Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
}
},
async server =>
{
string content = new string('a', totalSize);
string response = GetResponseForContentMode(content, mode);
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
await connection.ReadRequestHeaderAndSendCustomResponseAsync(response);
});
});
}
[OuterLoop]
[Theory]
[InlineData(100000, 1, ContentMode.ContentLength)]
[InlineData(100000, 1, ContentMode.SingleChunk)]
[InlineData(100000, 1, ContentMode.BytePerChunk)]
[InlineData(800000, 1, ContentMode.ContentLength)]
[InlineData(800000, 1, ContentMode.SingleChunk)]
[InlineData(1024 * 1024, 1, ContentMode.ContentLength)]
public async Task GetAsyncLargeRequestWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(int totalSize, int readSize, ContentMode mode)
{
// SocketsHttpHandler will reliably drain up to 1MB; other handlers don't.
if (!UseSocketsHttpHandler)
{
return;
}
await GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_DrainsRequestsAndReusesConnection(totalSize, readSize, mode);
return;
}
// Similar to above, these are semi-extreme cases where the response should never drain for any handler.
[OuterLoop]
[Theory]
[InlineData(2000000, 0, ContentMode.ContentLength)]
[InlineData(2000000, 0, ContentMode.SingleChunk)]
[InlineData(2000000, 0, ContentMode.BytePerChunk)]
[InlineData(4000000, 1000000, ContentMode.ContentLength)]
[InlineData(4000000, 1000000, ContentMode.SingleChunk)]
[InlineData(4000000, 1000000, ContentMode.BytePerChunk)]
public async Task GetAsyncWithMaxConnections_DisposeBeforeReadingToEnd_KillsConnection(int totalSize, int readSize, ContentMode mode)
{
await LoopbackServer.CreateClientAndServerAsync(
async url =>
{
HttpClientHandler handler = CreateHttpClientHandler();
// Set MaxConnectionsPerServer to 1. This will ensure we will wait for the previous request to drain (or fail to)
handler.MaxConnectionsPerServer = 1;
using (var client = new HttpClient(handler))
{
HttpResponseMessage response1 = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
ValidateResponseHeaders(response1, totalSize, mode);
// Read part but not all of response
Stream responseStream = await response1.Content.ReadAsStreamAsync();
await ReadToByteCount(responseStream, readSize);
response1.Dispose();
// Issue another request. We'll confirm that it comes on a new connection.
HttpResponseMessage response2 = await client.GetAsync(url);
ValidateResponseHeaders(response2, totalSize, mode);
Assert.Equal(totalSize, (await response2.Content.ReadAsStringAsync()).Length);
}
},
async server =>
{
string content = new string('a', totalSize);
string response = GetResponseForContentMode(content, mode);
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAsync();
try
{
await connection.Writer.WriteAsync(response);
}
catch (Exception) { } // Eat errors from client disconnect.
await server.AcceptConnectionSendCustomResponseAndCloseAsync(response);
});
});
}
private static void ValidateResponseHeaders(HttpResponseMessage response, int contentLength, ContentMode mode)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
switch (mode)
{
case ContentMode.ContentLength:
Assert.Equal(contentLength, response.Content.Headers.ContentLength);
break;
case ContentMode.SingleChunk:
case ContentMode.BytePerChunk:
Assert.True(response.Headers.TransferEncodingChunked);
break;
}
}
private static async Task<byte[]> ReadToByteCount(Stream stream, int byteCount)
{
byte[] buffer = new byte[byteCount];
int totalBytesRead = 0;
while (totalBytesRead < byteCount)
{
int bytesRead = await stream.ReadAsync(buffer, totalBytesRead, (byteCount - totalBytesRead));
if (bytesRead == 0)
{
throw new Exception("Unexpected EOF");
}
totalBytesRead += bytesRead;
if (totalBytesRead > byteCount)
{
throw new Exception("Read more bytes than requested???");
}
}
return buffer;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Compat;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// A Commit
/// </summary>
public class Commit : GitObject
{
private readonly GitObjectLazyGroup group;
private readonly ILazy<Tree> lazyTree;
private readonly ILazy<Signature> lazyAuthor;
private readonly ILazy<Signature> lazyCommitter;
private readonly ILazy<string> lazyMessage;
private readonly ILazy<string> lazyEncoding;
private readonly ParentsCollection parents;
private readonly Lazy<string> lazyShortMessage;
private readonly Lazy<IEnumerable<Note>> lazyNotes;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Commit()
{ }
internal Commit(Repository repo, ObjectId id)
: base(repo, id)
{
lazyTree = GitObjectLazyGroup.Singleton(this.repo, id, obj => new Tree(this.repo, Proxy.git_commit_tree_oid(obj), null));
group = new GitObjectLazyGroup(this.repo, id);
lazyAuthor = group.AddLazy(Proxy.git_commit_author);
lazyCommitter = group.AddLazy(Proxy.git_commit_committer);
lazyMessage = group.AddLazy(Proxy.git_commit_message);
lazyEncoding = group.AddLazy(RetrieveEncodingOf);
lazyShortMessage = new Lazy<string>(ExtractShortMessage);
lazyNotes = new Lazy<IEnumerable<Note>>(() => RetrieveNotesOfCommit(id).ToList());
parents = new ParentsCollection(repo, id);
}
/// <summary>
/// Gets the <see cref = "TreeEntry" /> pointed at by the <paramref name = "relativePath" /> in the <see cref = "Tree" />.
/// </summary>
/// <param name = "relativePath">The relative path to the <see cref = "TreeEntry" /> from the <see cref = "Commit" /> working directory.</param>
/// <returns><c>null</c> if nothing has been found, the <see cref = "TreeEntry" /> otherwise.</returns>
public virtual TreeEntry this[string relativePath]
{
get { return Tree[relativePath]; }
}
/// <summary>
/// Gets the commit message.
/// </summary>
public virtual string Message { get { return lazyMessage.Value; } }
/// <summary>
/// Gets the short commit message which is usually the first line of the commit.
/// </summary>
public virtual string MessageShort { get { return lazyShortMessage.Value; } }
/// <summary>
/// Gets the encoding of the message.
/// </summary>
public virtual string Encoding { get { return lazyEncoding.Value; } }
/// <summary>
/// Gets the author of this commit.
/// </summary>
public virtual Signature Author { get { return lazyAuthor.Value; } }
/// <summary>
/// Gets the committer.
/// </summary>
public virtual Signature Committer { get { return lazyCommitter.Value; } }
/// <summary>
/// Gets the Tree associated to this commit.
/// </summary>
public virtual Tree Tree { get { return lazyTree.Value; } }
/// <summary>
/// Gets the parents of this commit. This property is lazy loaded and can throw an exception if the commit no longer exists in the repo.
/// </summary>
public virtual IEnumerable<Commit> Parents { get { return parents; } }
/// <summary>
/// Gets The count of parent commits.
/// </summary>
[Obsolete("This property will be removed in the next release. Please use Parents.Count() instead.")]
public virtual int ParentsCount { get { return Parents.Count(); } }
/// <summary>
/// Gets the notes of this commit.
/// </summary>
public virtual IEnumerable<Note> Notes { get { return lazyNotes.Value; } }
private string ExtractShortMessage()
{
if (Message == null)
{
return string.Empty; //TODO: Add some test coverage
}
return Message.Split('\n')[0];
}
private IEnumerable<Note> RetrieveNotesOfCommit(ObjectId oid)
{
return repo.Notes[oid];
}
private static string RetrieveEncodingOf(GitObjectSafeHandle obj)
{
string encoding = Proxy.git_commit_message_encoding(obj);
return encoding ?? "UTF-8";
}
private class ParentsCollection : ICollection<Commit>
{
private readonly Lazy<ICollection<Commit>> _parents;
private readonly Lazy<int> _count;
public ParentsCollection(Repository repo, ObjectId commitId)
{
_count = new Lazy<int>(() => Proxy.git_commit_parentcount(repo.Handle, commitId));
_parents = new Lazy<ICollection<Commit>>(() => RetrieveParentsOfCommit(repo, commitId));
}
private ICollection<Commit> RetrieveParentsOfCommit(Repository repo, ObjectId commitId)
{
using (var obj = new ObjectSafeWrapper(commitId, repo.Handle))
{
int parentsCount = _count.Value;
var parents = new List<Commit>(parentsCount);
for (uint i = 0; i < parentsCount; i++)
{
ObjectId parentCommitId = Proxy.git_commit_parent_oid(obj.ObjectPtr, i);
parents.Add(new Commit(repo, parentCommitId));
}
return parents;
}
}
public IEnumerator<Commit> GetEnumerator()
{
return _parents.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(Commit item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(Commit item)
{
return _parents.Value.Contains(item);
}
public void CopyTo(Commit[] array, int arrayIndex)
{
_parents.Value.CopyTo(array, arrayIndex);
}
public bool Remove(Commit item)
{
throw new NotSupportedException();
}
public int Count
{
get { return _count.Value; }
}
public bool IsReadOnly
{
get { return true; }
}
}
}
}
| |
/*
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
This is sample code and is freely distributable.
*/
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
namespace ImageManipulation
{
/// <summary>
/// Quantize using an Octree
/// </summary>
public unsafe class OctreeQuantizer : Quantizer
{
/// <summary>
/// Construct the octree quantizer
/// </summary>
/// <remarks>
/// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
/// the second pass quantizes a color based on the nodes in the tree
/// </remarks>
/// <param name="maxColors">The maximum number of colors to return</param>
/// <param name="maxColorBits">The number of significant bits</param>
public OctreeQuantizer(int maxColors, int maxColorBits) : base(false)
{
if (maxColors > 255)
throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256");
if ((maxColorBits < 1) | (maxColorBits > 8))
throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8");
// Construct the octree
_octree = new Octree(maxColorBits);
_maxColors = maxColors;
}
/// <summary>
/// Process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected override void InitialQuantizePixel(Color32* pixel)
{
// Add the color to the octree
_octree.AddColor(pixel);
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <returns>The quantized value</returns>
protected override byte QuantizePixel(Color32* pixel)
{
byte paletteIndex = (byte)_maxColors; // The color at [_maxColors] is set to transparent
// Get the palette index if this non-transparent
if (pixel->Alpha > 0)
paletteIndex = (byte)_octree.GetPaletteIndex(pixel);
return paletteIndex;
}
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <param name="original">Any old palette, this is overrwritten</param>
/// <returns>The new color palette</returns>
protected override ColorPalette GetPalette(ColorPalette original)
{
// First off convert the octree to _maxColors colors
ArrayList palette = _octree.Palletize(_maxColors - 1);
// Then convert the palette based on those colors
for (int index = 0; index < palette.Count; index++)
original.Entries[index] = (Color)palette[index];
// Add the transparent color
original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0);
return original;
}
/// <summary>
/// Stores the tree
/// </summary>
readonly Octree _octree;
/// <summary>
/// Maximum allowed color depth
/// </summary>
readonly int _maxColors;
/// <summary>
/// Class which does the actual quantization
/// </summary>
class Octree
{
/// <summary>
/// Construct the octree
/// </summary>
/// <param name="maxColorBits">The maximum number of significant bits in the image</param>
public Octree(int maxColorBits)
{
_maxColorBits = maxColorBits;
_leafCount = 0;
_reducibleNodes = new OctreeNode[9];
_root = new OctreeNode(0, _maxColorBits, this);
_previousColor = 0;
_previousNode = null;
}
/// <summary>
/// Add a given color value to the octree
/// </summary>
/// <param name="pixel"></param>
public void AddColor(Color32* pixel)
{
// Check if this request is for the same color as the last
if (_previousColor == pixel->ARGB)
{
// If so, check if I have a previous node setup. This will only ocurr if the first color in the image
// happens to be black, with an alpha component of zero.
if (null == _previousNode)
{
_previousColor = pixel->ARGB;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
else
// Just update the previous node
_previousNode.Increment(pixel);
}
else
{
_previousColor = pixel->ARGB;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
}
/// <summary>
/// Reduce the depth of the tree
/// </summary>
public void Reduce()
{
int index;
// Find the deepest level containing at least one reducible node
for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--)
{
}
// Reduce the node most recently added to the list at level 'index'
OctreeNode node = _reducibleNodes[index];
_reducibleNodes[index] = node.NextReducible;
// Decrement the leaf count after reducing the node
_leafCount -= node.Reduce();
// And just in case I've reduced the last color to be added, and the next color to
// be added is the same, invalidate the previousNode...
_previousNode = null;
}
/// <summary>
/// Get/Set the number of leaves in the tree
/// </summary>
public int Leaves
{
get { return _leafCount; }
set { _leafCount = value; }
}
/// <summary>
/// Return the array of reducible nodes
/// </summary>
protected OctreeNode[] ReducibleNodes
{
get { return _reducibleNodes; }
}
/// <summary>
/// Keep track of the previous node that was quantized
/// </summary>
/// <param name="node">The node last quantized</param>
protected void TrackPrevious(OctreeNode node)
{
_previousNode = node;
}
/// <summary>
/// Convert the nodes in the octree to a palette with a maximum of colorCount colors
/// </summary>
/// <param name="colorCount">The maximum number of colors</param>
/// <returns>An arraylist with the palettized colors</returns>
public ArrayList Palletize(int colorCount)
{
while (Leaves > colorCount)
Reduce();
// Now palettize the nodes
var palette = new ArrayList(Leaves);
int paletteIndex = 0;
_root.ConstructPalette(palette, ref paletteIndex);
// And return the palette
return palette;
}
/// <summary>
/// Get the palette index for the passed color
/// </summary>
/// <param name="pixel"></param>
/// <returns></returns>
public int GetPaletteIndex(Color32* pixel)
{
return _root.GetPaletteIndex(pixel, 0);
}
/// <summary>
/// Mask used when getting the appropriate pixels for a given node
/// </summary>
static readonly int[] mask = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
/// <summary>
/// The root of the octree
/// </summary>
readonly OctreeNode _root;
/// <summary>
/// Number of leaves in the tree
/// </summary>
int _leafCount;
/// <summary>
/// Array of reducible nodes
/// </summary>
readonly OctreeNode[] _reducibleNodes;
/// <summary>
/// Maximum number of significant bits in the image
/// </summary>
readonly int _maxColorBits;
/// <summary>
/// Store the last node quantized
/// </summary>
OctreeNode _previousNode;
/// <summary>
/// Cache the previous color quantized
/// </summary>
int _previousColor;
/// <summary>
/// Class which encapsulates each node in the tree
/// </summary>
protected class OctreeNode
{
/// <summary>
/// Construct the node
/// </summary>
/// <param name="level">The level in the tree = 0 - 7</param>
/// <param name="colorBits">The number of significant color bits in the image</param>
/// <param name="octree">The tree to which this node belongs</param>
public OctreeNode(int level, int colorBits, Octree octree)
{
// Construct the new node
_leaf = (level == colorBits);
_red = _green = _blue = 0;
_pixelCount = 0;
// If a leaf, increment the leaf count
if (_leaf)
{
octree.Leaves++;
_nextReducible = null;
_children = null;
}
else
{
// Otherwise add this to the reducible nodes
_nextReducible = octree.ReducibleNodes[level];
octree.ReducibleNodes[level] = this;
_children = new OctreeNode[8];
}
}
/// <summary>
/// Add a color into the tree
/// </summary>
/// <param name="pixel">The color</param>
/// <param name="colorBits">The number of significant color bits</param>
/// <param name="level">The level in the tree</param>
/// <param name="octree">The tree to which this node belongs</param>
public void AddColor(Color32* pixel, int colorBits, int level, Octree octree)
{
// Update the color information if this is a leaf
if (_leaf)
{
Increment(pixel);
// Setup the previous node
octree.TrackPrevious(this);
}
else
{
// Go to the next level down in the tree
int shift = 7 - level;
int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
((pixel->Green & mask[level]) >> (shift - 1)) |
((pixel->Blue & mask[level]) >> (shift));
OctreeNode child = _children[index];
if (null == child)
{
// Create a new child node & store in the array
child = new OctreeNode(level + 1, colorBits, octree);
_children[index] = child;
}
// Add the color to the child node
child.AddColor(pixel, colorBits, level + 1, octree);
}
}
/// <summary>
/// Get/Set the next reducible node
/// </summary>
public OctreeNode NextReducible
{
get { return _nextReducible; }
set { _nextReducible = value; }
}
/// <summary>
/// Return the child nodes
/// </summary>
public OctreeNode[] Children
{
get { return _children; }
}
/// <summary>
/// Reduce this node by removing all of its children
/// </summary>
/// <returns>The number of leaves removed</returns>
public int Reduce()
{
_red = _green = _blue = 0;
int children = 0;
// Loop through all children and add their information to this node
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
{
_red += _children[index]._red;
_green += _children[index]._green;
_blue += _children[index]._blue;
_pixelCount += _children[index]._pixelCount;
++children;
_children[index] = null;
}
}
// Now change this to a leaf node
_leaf = true;
// Return the number of nodes to decrement the leaf count by
return (children - 1);
}
/// <summary>
/// Traverse the tree, building up the color palette
/// </summary>
/// <param name="palette">The palette</param>
/// <param name="paletteIndex">The current palette index</param>
public void ConstructPalette(ArrayList palette, ref int paletteIndex)
{
if (_leaf)
{
// Consume the next palette index
_paletteIndex = paletteIndex++;
// And set the color of the palette entry
palette.Add(Color.FromArgb(_red / _pixelCount, _green / _pixelCount, _blue / _pixelCount));
}
else
{
// Loop through children looking for leaves
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
_children[index].ConstructPalette(palette, ref paletteIndex);
}
}
}
/// <summary>
/// Return the palette index for the passed color
/// </summary>
public int GetPaletteIndex(Color32* pixel, int level)
{
int paletteIndex = _paletteIndex;
if (!_leaf)
{
int shift = 7 - level;
int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
((pixel->Green & mask[level]) >> (shift - 1)) |
((pixel->Blue & mask[level]) >> (shift));
if (null != _children[index])
paletteIndex = _children[index].GetPaletteIndex(pixel, level + 1);
else
throw new ArgumentNullException(string.Format(CultureInfo.CurrentCulture, "Didn't expect this!"));
}
return paletteIndex;
}
/// <summary>
/// Increment the pixel count and add to the color information
/// </summary>
public void Increment(Color32* pixel)
{
_pixelCount++;
_red += pixel->Red;
_green += pixel->Green;
_blue += pixel->Blue;
}
/// <summary>
/// Flag indicating that this is a leaf node
/// </summary>
bool _leaf;
/// <summary>
/// Number of pixels in this node
/// </summary>
int _pixelCount;
/// <summary>
/// Red component
/// </summary>
int _red;
/// <summary>
/// Green Component
/// </summary>
int _green;
/// <summary>
/// Blue component
/// </summary>
int _blue;
/// <summary>
/// Pointers to any child nodes
/// </summary>
readonly OctreeNode[] _children;
/// <summary>
/// Pointer to next reducible node
/// </summary>
OctreeNode _nextReducible;
/// <summary>
/// The index of this node in the palette
/// </summary>
int _paletteIndex;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace List_List_RemoveReverseTests
{
public class Driver<T>
{
#region Remove
public void BasicRemove(T[] items)
{
List<T> list = new List<T>(new TestCollection<T>(items));
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(true, list.Remove(items[i])); //String.Format("Err_12702ahpba Expected Remove to return true with item={0}", items[i])
}
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(list.Contains(items[i]), false); //String.Format("Err_1707ahspb!!! Expected item={0} not to exist in the collection", items[i])
}
Assert.Equal(list.Count, 0); //"Err_21181ahied Expected Count=0 after removing all items actual:{1}" + list.Count
}
public void ExtendedRemove(T[] itemsX, T[] itemsY)
{
List<T> list = new List<T>(new TestCollection<T>(itemsX));
list.AddRange(new TestCollection<T>(itemsY));
for (int i = 0; i < itemsX.Length; i++)
{
Assert.Equal(true, list.Remove(itemsX[i])); //String.Format("Err_586123ahpba Expected Remove to return true with item={0}", itemsX[i])
}
Assert.Equal(list.Count, itemsY.Length); //"Expect to be same."
for (int i = 0; i < itemsY.Length; i++)
{
Assert.Equal(list[i], itemsY[i]); //"Err_485585ahied Expected at index:" + i
}
}
public void RemoveMultipleExistingValue(T[] items, int sameFactor, int sameIndex)
{
List<T> list = new List<T>(new TestCollection<T>(items));
int sameCountExpected = (sameFactor * 2) + 1;
T sameVal = items[sameIndex];
for (int i = 0; i < sameFactor; i++)
{
list.AddRange(new TestCollection<T>(items));
list.Add(sameVal);
}
for (int i = 0; i < sameCountExpected; i++)
{
Assert.Equal(true, list.Remove(sameVal)); //String.Format("Err_181585aeahp Expected Remove to return true with item={0}", sameVal)
}
Assert.Equal(list.Contains(sameVal), false); //"Expect to be same."
for (int i = 0; i < 100; i++)
{
Assert.Equal(false, list.Remove(sameVal)); //String.Format("Err_55861anhpba Expected Remove to return false with item={0}", sameVal)
}
Assert.Equal(list.Contains(sameVal), false); //"Expect to be same."
Assert.Equal(list.Count, (items.Length - 1) * (sameFactor + 1)); //"Expect to be same."
}
public void RemoveEmptyCollection(T item)
{
List<T> list = new List<T>();
Assert.Equal(false, list.Remove(item)); //String.Format("Err_44896!!! Expected Remove to return false with item={0}", item)
Assert.Equal(list.Count, 0); //"Expect to be same."
}
public void RemoveNullValueWhenReference(T value)
{
if ((object)value != null)
{
throw new ArgumentException("invalid argument passed to testcase");
}
List<T> list = new List<T>();
list.Add(value);
Assert.Equal(true, list.Remove(value)); //String.Format("Err_55861anhpba Expected Remove to return true with item={0}", value)
Assert.Equal(false, list.Remove(value)); //String.Format("Err_88484ahbpz Expected Remove to return false with item={0}", value)
Assert.Equal(list.Contains(value), false); //"Expect to be same."
}
public void NonGenericIListBasicRemove(T[] items)
{
List<T> list = new List<T>(new TestCollection<T>(items));
IList _ilist = list;
for (int i = 0; i < items.Length; i++)
{
_ilist.Remove(items[i]);
}
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(list.Contains(items[i]), false); //"Expect to be same."
}
Assert.Equal(list.Count, 0); //"Expect to be same."
}
public void NonGenericIListExtendedRemove(T[] itemsX, T[] itemsY)
{
List<T> list = new List<T>(new TestCollection<T>(itemsX));
IList _ilist = list;
list.AddRange(new TestCollection<T>(itemsY));
for (int i = 0; i < itemsX.Length; i++)
{
_ilist.Remove(itemsX[i]);
}
Assert.Equal(list.Count, itemsY.Length); //"Expect to be same."
for (int i = 0; i < itemsY.Length; i++)
{
Assert.Equal(list[i], itemsY[i]); //"Expect to be same."
}
}
public void NonGenericIListRemoveMultipleExistingValue(T[] items, int sameFactor, int sameIndex)
{
List<T> list = new List<T>(new TestCollection<T>(items));
IList _ilist = list;
int sameCountExpected = (sameFactor * 2) + 1;
T sameVal = items[sameIndex];
for (int i = 0; i < sameFactor; i++)
{
list.AddRange(new TestCollection<T>(items));
list.Add(sameVal);
}
for (int i = 0; i < sameCountExpected; i++)
{
_ilist.Remove(sameVal);
}
Assert.Equal(list.Contains(sameVal), false); //"Expect to be same."
for (int i = 0; i < 100; i++)
{
_ilist.Remove(sameVal);
}
Assert.Equal(list.Contains(sameVal), false); //"Expect to be same."
Assert.Equal(list.Count, (items.Length - 1) * (sameFactor + 1)); //"Expect to be same."
}
public void NonGenericIListRemoveNullValueWhenReference(T value)
{
if ((object)value != null)
{
throw new ArgumentException("invalid argument passed to testcase");
}
List<T> list = new List<T>();
IList _ilist = list;
list.Add(value);
_ilist.Remove(value);
Assert.Equal(list.Contains(value), false); //"Expect to be same."
}
public void NonGenericIListRemoveTestParams()
{
List<T> list = new List<T>();
IList _ilist = list;
list.Add(default(T));
_ilist.Remove(new LinkedListNode<string>("item"));
Assert.Equal(1, list.Count); //"Expect to be same."
}
#endregion
#region RemoveAll(Pred<T>)
public void RemoveAll_VerifyVanilla(T[] items)
{
T expectedItem = default(T);
List<T> list = new List<T>();
Predicate<T> expectedItemDelegate = delegate (T item) { return expectedItem == null ? item == null : expectedItem.Equals(item); };
bool typeNullable = default(T) == null;
T[] expectedItems, matchingItems;
int removeAllReturnValue;
//[] Verify RemoveAll works correcty when removing every item
list.Clear();
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
for (int i = 0; i < items.Length; ++i)
{
expectedItem = items[i];
Assert.Equal(1, (removeAllReturnValue = list.RemoveAll(expectedItemDelegate))); //"Err_56488ajodoe Expected RemoveAll"
expectedItems = new T[items.Length - 1 - i];
Array.Copy(items, i + 1, expectedItems, 0, expectedItems.Length);
VerifyList(list, expectedItems);
}
//[] Verify RemoveAll removes every item when the match returns true on every item
list.Clear();
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
Assert.Equal(items.Length, (removeAllReturnValue = list.RemoveAll(delegate (T item) { return true; }))); //"Err_2988092jaid Expected RemoveAll"
VerifyList(list, new T[0]);
//[] Verify RemoveAll removes no items when the match returns false on every item
list.Clear();
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
Assert.Equal(0, (removeAllReturnValue = list.RemoveAll(delegate (T item) { return false; }))); //"Err_4848ajod Expected RemoveAll"
VerifyList(list, items);
//[] Verify RemoveAll that removes every other item
list.Clear();
matchingItems = new T[items.Length - (items.Length / 2)];
expectedItems = new T[items.Length - matchingItems.Length];
for (int i = 0; i < items.Length; ++i)
{
list.Add(items[i]);
if ((i & 1) == 0)
matchingItems[i / 2] = items[i];
else
expectedItems[i / 2] = items[i];
}
Assert.Equal(matchingItems.Length, (removeAllReturnValue = list.RemoveAll(delegate (T item) { return -1 != Array.IndexOf(matchingItems, item); }))); //"Err_50898ajhoid Expected RemoveAll"
VerifyList(list, expectedItems);
}
public void RemoveAll_VerifyExceptions(T[] items)
{
List<T> list = new List<T>();
Predicate<T> predicate = delegate (T item) { return true; };
for (int i = 0; i < items.Length; ++i)
list.Add(items[i]);
//[] Verify Null match
Assert.Throws<ArgumentNullException>(() => list.RemoveAll(null)); //"Err_858ahia Expected null match to throw ArgumentNullException"
}
private void VerifyList(List<T> list, T[] expectedItems)
{
Assert.Equal(list.Count, expectedItems.Length); //"Err_2828ahid Expected the same"
//Only verify the indexer. List should be in a good enough state that we
//do not have to verify consistancy with any other method.
for (int i = 0; i < list.Count; ++i)
{
Assert.Equal(expectedItems[i], list[i]); //"Err_19818ayiadb Expceted same stuff in list."
}
}
#endregion
#region RemoveAT
public void BasicRemoveAt(T[] items, int startindex)
{
List<T> list = new List<T>(new TestCollection<T>(items));
for (int i = items.Length - 1; i >= startindex; i--)
{
list.RemoveAt(i);
}
Assert.Equal(list.Count, items.Length - (items.Length - startindex)); //"Expect to be the same."
for (int i = 0; i < startindex; i++)
{
Assert.Equal(list[i], items[i]); //"Expect to be the same."
}
list = new List<T>(new TestCollection<T>(items));
for (int i = 0; i < items.Length - startindex; i++)
{
list.RemoveAt(startindex);
}
Assert.Equal(list.Count, items.Length - (items.Length - startindex)); //"Expect to be the same."
for (int i = 0; i < startindex; i++)
{
Assert.Equal(list[i], items[i]); //"Expect to be the same."
}
list = new List<T>(new TestCollection<T>(items));
for (int i = 0; i < startindex; i++)
{
list.RemoveAt(0);
}
Assert.Equal(list.Count, items.Length - startindex); //"Expect to be the same."
for (int i = 0; i < items.Length - startindex; i++)
{
Assert.Equal(list[i], items[i + startindex]); //"Expect to be the same."
}
list = new List<T>(new TestCollection<T>(items));
for (int i = startindex - 1; i >= 0; i--)
{
list.RemoveAt(i);
}
Assert.Equal(list.Count, items.Length - startindex); //"Expect to be the same."
for (int i = 0; i < items.Length - startindex; i++)
{
Assert.Equal(list[i], items[i + startindex]); //"Expect to be the same."
}
}
public void RemoveAtValidations(T[] items)
{
List<T> list = new List<T>(new TestCollection<T>(items));
int[] bad = new int[] { items.Length, items.Length + 1, int.MaxValue, -1, -2, int.MinValue };
for (int i = 0; i < bad.Length; i++)
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(bad[i])); //"ArgumentOutOfRangeException expected."
}
}
public void RemoveAtNullValueWhenReference(T value)
{
if ((object)value != null)
{
throw new ArgumentException("invalid argument passed to testcase");
}
List<T> list = new List<T>();
list.Add(value);
list.RemoveAt(0);
Assert.Equal(list.Contains(value), false); //"Expected to be the same."
}
public void NonGenericIListBasicRemoveAt(T[] items, int startindex)
{
List<T> list = new List<T>(new TestCollection<T>(items));
IList _ilist = list;
for (int i = items.Length - 1; i >= startindex; i--)
{
_ilist.RemoveAt(i);
}
Assert.Equal(list.Count, items.Length - (items.Length - startindex)); //"Expected to be the same."
for (int i = 0; i < startindex; i++)
{
Assert.Equal(list[i], items[i]); //"Expected to be the same."
}
list = new List<T>(new TestCollection<T>(items));
_ilist = list;
for (int i = 0; i < items.Length - startindex; i++)
{
_ilist.RemoveAt(startindex);
}
Assert.Equal(list.Count, items.Length - (items.Length - startindex)); //"Expected to be the same."
for (int i = 0; i < startindex; i++)
{
Assert.Equal(list[i], items[i]); //"Expected to be the same."
}
list = new List<T>(new TestCollection<T>(items));
_ilist = list;
for (int i = 0; i < startindex; i++)
{
_ilist.RemoveAt(0);
}
Assert.Equal(list.Count, items.Length - startindex); //"Expected to be the same."
for (int i = 0; i < items.Length - startindex; i++)
{
Assert.Equal(list[i], items[i + startindex]); //"Expected to be the same."
}
list = new List<T>(new TestCollection<T>(items));
_ilist = list;
for (int i = startindex - 1; i >= 0; i--)
{
_ilist.RemoveAt(i);
}
Assert.Equal(list.Count, items.Length - startindex); //"Expected to be the same."
for (int i = 0; i < items.Length - startindex; i++)
{
Assert.Equal(list[i], items[i + startindex]); //"Expected to be the same."
}
}
public void NonGenericIListRemoveAtValidations(T[] items)
{
List<T> list = new List<T>(new TestCollection<T>(items));
IList _ilist = list;
int[] bad = new int[] { items.Length, items.Length + 1, int.MaxValue, -1, -2, int.MinValue };
for (int i = 0; i < bad.Length; i++)
{
Assert.Throws<ArgumentOutOfRangeException>(() => _ilist.RemoveAt(bad[i])); //"ArgumentOutOfRangeException expected."
}
}
public void NonGenericIListRemoveAtNullValueWhenReference(T value)
{
if ((object)value != null)
{
throw new ArgumentException("invalid argument passed to testcase");
}
List<T> list = new List<T>();
IList _ilist = list;
list.Add(value);
_ilist.RemoveAt(0);
Assert.Equal(list.Contains(value), false); //"Expected to be the same."
}
#endregion
#region RemoveRange
public void BasicRemoveRange(T[] items, int index, int count)
{
List<T> list = new List<T>(new TestCollection<T>(items));
list.RemoveRange(index, count);
Assert.Equal(list.Count, items.Length - count); //"Expected them to be the same."
for (int i = 0; i < index; i++)
{
Assert.Equal(list[i], items[i]); //"Expected them to be the same."
}
for (int i = index; i < items.Length - (index + count); i++)
{
Assert.Equal(list[i], items[i + count]); //"Expected them to be the same."
}
}
public void RemoveRangeValidations(T[] items)
{
//
//Always send items.Length is even
//
List<T> list = new List<T>(new TestCollection<T>(items));
int[] bad = new int[]
{
items.Length,1,
items.Length+1,0,
items.Length+1,1,
items.Length,2,
items.Length/2,items.Length/2+1,
items.Length-1,2,
items.Length-2,3,
1,items.Length,
0,items.Length+1,
1,items.Length+1,
2,items.Length,
items.Length/2+1,items.Length/2,
2,items.Length-1,
3,items.Length-2,
};
int[] negBad = new int[]
{
-1,-1,
-1,0,
-1,1,
-1,2,
0,-1,
1,-1,
2,-1
};
for (int i = 0; i < bad.Length; i++)
{
Assert.Throws<ArgumentException>(() => list.RemoveRange(bad[i], bad[++i])); //"Expect ArgumentException."
}
for (int i = 0; i < negBad.Length; i++)
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(negBad[i], negBad[++i])); //"Expect ArgumentOutOfRangeException"
}
}
#endregion
#region Reverse
public void Reverse(T[] items)
{
List<T> list = new List<T>(new TestCollection<T>(items));
list.Reverse();
for (int i = 0; i < items.Length; i++)
{
Assert.Equal(list[i], items[items.Length - (i + 1)]); //"Expect them to be teh same."
}
}
public void Reverse(T item, int repeat)
{
List<T> list = new List<T>();
for (int i = 0; i < repeat; i++)
list.Add(item);
list.Reverse();
for (int i = 0; i < repeat; i++)
{
Assert.Equal(list[i], item); //"Expect them to be teh same."
}
}
#endregion
#region Reverse(int, int)
public void Reverse(T[] items, int index, int count)
{
List<T> list = new List<T>(new TestCollection<T>(items));
list.Reverse(index, count);
for (int i = 0; i < index; i++)
{
Assert.Equal(list[i], items[i]); //"Expect them to be the same."
}
int j = 0;
for (int i = index; i < index + count; i++)
{
Assert.Equal(list[i], items[index + count - (j + 1)]); //"Expect them to be the same."
j++;
}
for (int i = index + count; i < items.Length; i++)
{
Assert.Equal(list[i], items[i]); //"Expect them to be the same."
}
}
public void ReverseValidations(T[] items)
{
//
//Always send items.Length is even
//
List<T> list = new List<T>(new TestCollection<T>(items));
int[] bad = new int[]
{
items.Length,1,
items.Length+1,0,
items.Length+1,1,
items.Length,2,
items.Length/2,items.Length/2+1,
items.Length-1,2,
items.Length-2,3,
1,items.Length,
0,items.Length+1,
1,items.Length+1,
2,items.Length,
items.Length/2+1,items.Length/2,
2,items.Length-1,
3,items.Length-2,
};
int[] negBad = new int[]
{
-1,-1,
-1,0,
-1,1,
-1,2,
0,-1,
1,-1,
2,-1
};
for (int i = 0; i < bad.Length; i++)
{
Assert.Throws<ArgumentException>(() => list.Reverse(bad[i], bad[++i])); //"Expect ArgumentException."
}
for (int i = 0; i < negBad.Length; i++)
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.Reverse(negBad[i], negBad[++i])); //"Expect ArgumentOutOfRangeException"
}
}
#endregion
}
public class List_RemoveReverse
{
[Fact]
public static void RemoveTests()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr1 = new int[100];
for (int i = 0; i < 100; i++)
{
intArr1[i] = i;
}
int[] intArr2 = new int[100];
for (int i = 0; i < 100; i++)
{
intArr2[i] = i + 100;
}
IntDriver.BasicRemove(intArr1);
IntDriver.ExtendedRemove(intArr1, intArr2);
IntDriver.RemoveMultipleExistingValue(intArr1, 3, 5);
IntDriver.RemoveMultipleExistingValue(intArr1, 17, 99);
IntDriver.RemoveMultipleExistingValue(intArr1, 7, 0);
IntDriver.RemoveEmptyCollection(0);
IntDriver.NonGenericIListBasicRemove(intArr1);
IntDriver.NonGenericIListExtendedRemove(intArr1, intArr2);
IntDriver.NonGenericIListRemoveMultipleExistingValue(intArr1, 3, 5);
IntDriver.NonGenericIListRemoveMultipleExistingValue(intArr1, 17, 99);
IntDriver.NonGenericIListRemoveMultipleExistingValue(intArr1, 7, 0);
IntDriver.NonGenericIListRemoveTestParams();
Driver<string> StringDriver = new Driver<string>();
string[] stringArr1 = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr1[i] = "SomeTestString" + i.ToString();
}
string[] stringArr2 = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr2[i] = "SomeTestString" + (i + 100).ToString();
}
StringDriver.BasicRemove(stringArr1);
StringDriver.ExtendedRemove(stringArr1, stringArr2);
StringDriver.RemoveMultipleExistingValue(stringArr1, 3, 5);
StringDriver.RemoveMultipleExistingValue(stringArr1, 17, 99);
StringDriver.RemoveMultipleExistingValue(stringArr1, 7, 0);
StringDriver.RemoveNullValueWhenReference(null);
StringDriver.RemoveEmptyCollection(null);
StringDriver.RemoveEmptyCollection(String.Empty);
StringDriver.NonGenericIListBasicRemove(stringArr1);
StringDriver.NonGenericIListExtendedRemove(stringArr1, stringArr2);
StringDriver.NonGenericIListRemoveMultipleExistingValue(stringArr1, 3, 5);
StringDriver.NonGenericIListRemoveMultipleExistingValue(stringArr1, 17, 99);
StringDriver.NonGenericIListRemoveMultipleExistingValue(stringArr1, 7, 0);
StringDriver.NonGenericIListRemoveNullValueWhenReference(null);
StringDriver.NonGenericIListRemoveTestParams();
}
[Fact]
public static void RemoveAllTests()
{
Driver<int> intDriver = new Driver<int>();
Driver<string> stringDriver = new Driver<string>();
int[] intArray;
string[] stringArray;
int arraySize = 16;
intArray = new int[arraySize];
stringArray = new string[arraySize];
for (int i = 0; i < arraySize; ++i)
{
intArray[i] = i + 1;
stringArray[i] = (i + 1).ToString();
}
intDriver.RemoveAll_VerifyVanilla(new int[0]);
intDriver.RemoveAll_VerifyVanilla(new int[] { 1 });
intDriver.RemoveAll_VerifyVanilla(intArray);
stringDriver.RemoveAll_VerifyVanilla(new string[0]);
stringDriver.RemoveAll_VerifyVanilla(new string[] { "1" });
stringDriver.RemoveAll_VerifyVanilla(stringArray);
}
[Fact]
public static void RemoveAtTests()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr1 = new int[100];
for (int i = 0; i < 100; i++)
{
intArr1[i] = i;
}
int[] intArr2 = new int[100];
for (int i = 0; i < 100; i++)
{
intArr2[i] = i + 100;
}
IntDriver.BasicRemoveAt(intArr1, 50);
IntDriver.BasicRemoveAt(intArr1, 0);
IntDriver.BasicRemoveAt(intArr1, 99);
IntDriver.NonGenericIListBasicRemoveAt(intArr1, 50);
IntDriver.NonGenericIListBasicRemoveAt(intArr1, 0);
IntDriver.NonGenericIListBasicRemoveAt(intArr1, 99);
Driver<string> StringDriver = new Driver<string>();
string[] stringArr1 = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr1[i] = "SomeTestString" + i.ToString();
}
string[] stringArr2 = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr2[i] = "SomeTestString" + (i + 100).ToString();
}
StringDriver.BasicRemoveAt(stringArr1, 50);
StringDriver.BasicRemoveAt(stringArr1, 0);
StringDriver.BasicRemoveAt(stringArr1, 99);
StringDriver.RemoveAtNullValueWhenReference(null);
StringDriver.NonGenericIListBasicRemoveAt(stringArr1, 50);
StringDriver.NonGenericIListBasicRemoveAt(stringArr1, 0);
StringDriver.NonGenericIListBasicRemoveAt(stringArr1, 99);
StringDriver.NonGenericIListRemoveAtNullValueWhenReference(null);
}
[Fact]
public static void RemoveAtTests_Negative()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr1 = new int[100];
for (int i = 0; i < 100; i++)
{
intArr1[i] = i;
}
Driver<string> StringDriver = new Driver<string>();
string[] stringArr1 = new string[100];
for (int i = 0; i < 100; i++)
{
stringArr1[i] = "SomeTestString" + i.ToString();
}
IntDriver.NonGenericIListRemoveAtValidations(intArr1);
IntDriver.RemoveAtValidations(intArr1);
StringDriver.RemoveAtValidations(stringArr1);
StringDriver.NonGenericIListRemoveAtValidations(stringArr1);
}
[Fact]
public static void RemoveRangeTests()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr1 = new int[100];
for (int i = 0; i < 100; i++)
intArr1[i] = i;
IntDriver.BasicRemoveRange(intArr1, 50, 50);
IntDriver.BasicRemoveRange(intArr1, 0, 50);
IntDriver.BasicRemoveRange(intArr1, 50, 25);
IntDriver.BasicRemoveRange(intArr1, 0, 25);
IntDriver.BasicRemoveRange(intArr1, 75, 25);
IntDriver.BasicRemoveRange(intArr1, 0, 100);
IntDriver.BasicRemoveRange(intArr1, 0, 99);
IntDriver.BasicRemoveRange(intArr1, 1, 1);
IntDriver.BasicRemoveRange(intArr1, 99, 1);
Driver<string> StringDriver = new Driver<string>();
string[] stringArr1 = new string[100];
for (int i = 0; i < 100; i++)
stringArr1[i] = "SomeTestString" + i.ToString();
StringDriver.BasicRemoveRange(stringArr1, 50, 50);
StringDriver.BasicRemoveRange(stringArr1, 0, 50);
StringDriver.BasicRemoveRange(stringArr1, 50, 25);
StringDriver.BasicRemoveRange(stringArr1, 0, 25);
StringDriver.BasicRemoveRange(stringArr1, 75, 25);
StringDriver.BasicRemoveRange(stringArr1, 0, 100);
StringDriver.BasicRemoveRange(stringArr1, 0, 99);
StringDriver.BasicRemoveRange(stringArr1, 1, 1);
StringDriver.BasicRemoveRange(stringArr1, 99, 1);
}
[Fact]
public static void RemoveRangeTests_Negative()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr1 = new int[100];
for (int i = 0; i < 100; i++)
intArr1[i] = i;
Driver<string> StringDriver = new Driver<string>();
string[] stringArr1 = new string[100];
for (int i = 0; i < 100; i++)
stringArr1[i] = "SomeTestString" + i.ToString();
IntDriver.RemoveRangeValidations(intArr1);
StringDriver.RemoveRangeValidations(stringArr1);
}
[Fact]
public static void ReverseTests()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr = new int[10];
for (int i = 0; i < 10; i++)
intArr[i] = i;
IntDriver.Reverse(intArr);
IntDriver.Reverse(intArr[0], 5);
IntDriver.Reverse(new int[] { });
IntDriver.Reverse(new int[] { 1 });
Driver<string> StringDriver = new Driver<string>();
string[] stringArr = new string[10];
for (int i = 0; i < 10; i++)
stringArr[i] = "SomeTestString" + i.ToString();
StringDriver.Reverse(stringArr);
StringDriver.Reverse(stringArr[0], 5);
StringDriver.Reverse(new string[] { });
StringDriver.Reverse(new string[] { "string" });
StringDriver.Reverse(new string[] { (string)null });
StringDriver.Reverse(null, 5);
}
[Fact]
public static void ReverseIntIntTests()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr = new int[10];
for (int i = 0; i < 10; i++)
intArr[i] = i;
IntDriver.Reverse(intArr, 3, 3);
IntDriver.Reverse(intArr, 0, 10);
IntDriver.Reverse(intArr, 10, 0);
IntDriver.Reverse(intArr, 5, 5);
IntDriver.Reverse(intArr, 0, 5);
IntDriver.Reverse(intArr, 1, 9);
IntDriver.Reverse(intArr, 9, 1);
IntDriver.Reverse(intArr, 2, 8);
IntDriver.Reverse(intArr, 8, 2);
Driver<string> StringDriver = new Driver<string>();
string[] stringArr = new string[10];
for (int i = 0; i < 10; i++)
stringArr[i] = "SomeTestString" + i.ToString();
StringDriver.Reverse(stringArr, 3, 3);
StringDriver.Reverse(stringArr, 0, 10);
StringDriver.Reverse(stringArr, 10, 0);
StringDriver.Reverse(stringArr, 5, 5);
StringDriver.Reverse(stringArr, 0, 5);
StringDriver.Reverse(stringArr, 1, 9);
StringDriver.Reverse(stringArr, 9, 1);
StringDriver.Reverse(stringArr, 2, 8);
StringDriver.Reverse(stringArr, 8, 2);
StringDriver.Reverse(new string[] { "str1", null, "str2", }, 1, 2);
StringDriver.Reverse(new string[] { "str1", null, "str2", }, 1, 1);
StringDriver.Reverse(new string[] { null, null, "str2", null, null }, 1, 4);
}
[Fact]
public static void ReverseIntIntTests_Negative()
{
Driver<int> IntDriver = new Driver<int>();
int[] intArr = new int[10];
for (int i = 0; i < 10; i++)
intArr[i] = i;
IntDriver.ReverseValidations(intArr);
Driver<string> StringDriver = new Driver<string>();
string[] stringArr = new string[10];
for (int i = 0; i < 10; i++)
stringArr[i] = "SomeTestString" + i.ToString();
StringDriver.ReverseValidations(stringArr);
}
}
#region Helper Classes
/// <summary>
/// Helper class that implements ICollection.
/// </summary>
public class TestCollection<T> : ICollection<T>
{
/// <summary>
/// Expose the Items in Array to give more test flexibility...
/// </summary>
public readonly T[] m_items;
public TestCollection(T[] items)
{
m_items = items;
}
public void CopyTo(T[] array, int index)
{
Array.Copy(m_items, 0, array, index, m_items.Length);
}
public int Count
{
get
{
if (m_items == null)
return 0;
else
return m_items.Length;
}
}
public Object SyncRoot { get { return this; } }
public bool IsSynchronized { get { return false; } }
public IEnumerator<T> GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
private class TestCollectionEnumerator<T1> : IEnumerator<T1>
{
private TestCollection<T1> _col;
private int _index;
public void Dispose() { }
public TestCollectionEnumerator(TestCollection<T1> col)
{
_col = col;
_index = -1;
}
public bool MoveNext()
{
return (++_index < _col.m_items.Length);
}
public T1 Current
{
get { return _col.m_items[_index]; }
}
Object System.Collections.IEnumerator.Current
{
get { return _col.m_items[_index]; }
}
public void Reset()
{
_index = -1;
}
}
#region Non Implemented methods
public void Add(T item) { throw new NotSupportedException(); }
public void Clear() { throw new NotSupportedException(); }
public bool Contains(T item) { throw new NotSupportedException(); }
public bool Remove(T item) { throw new NotSupportedException(); }
public bool IsReadOnly { get { throw new NotSupportedException(); } }
#endregion
}
#endregion
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/folio_charge_posted_notification.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 HOLMS.Types.Booking {
/// <summary>Holder for reflection information generated from booking/folio_charge_posted_notification.proto</summary>
public static partial class FolioChargePostedNotificationReflection {
#region Descriptor
/// <summary>File descriptor for booking/folio_charge_posted_notification.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FolioChargePostedNotificationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci5ib29raW5nL2ZvbGlvX2NoYXJnZV9wb3N0ZWRfbm90aWZpY2F0aW9uLnBy",
"b3RvEhNob2xtcy50eXBlcy5ib29raW5nGh9wcmltaXRpdmUvbW9uZXRhcnlf",
"YW1vdW50LnByb3RvGh1wcmltaXRpdmUvcGJfbG9jYWxfZGF0ZS5wcm90bxou",
"Ym9va2luZy9pbmRpY2F0b3JzL3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90",
"bxogY3JtL2d1ZXN0cy9ndWVzdF9pbmRpY2F0b3IucHJvdG8aK3N1cHBseS9y",
"b29tX3R5cGVzL3Jvb21fdHlwZV9pbmRpY2F0b3IucHJvdG8i/QIKHUZvbGlv",
"Q2hhcmdlUG9zdGVkTm90aWZpY2F0aW9uEhEKCWpfd190b2tlbhgBIAEoCRIz",
"CgdvcHNkYXRlGAIgASgLMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlBiTG9j",
"YWxEYXRlEkQKFXByZXRheF9sb2RnaW5nX2NoYXJnZRgDIAEoCzIlLmhvbG1z",
"LnR5cGVzLnByaW1pdGl2ZS5Nb25ldGFyeUFtb3VudBJGCgxyb29tX3R5cGVf",
"aWQYBCABKAsyMC5ob2xtcy50eXBlcy5zdXBwbHkucm9vbV90eXBlcy5Sb29t",
"VHlwZUluZGljYXRvchI4CghndWVzdF9pZBgFIAEoCzImLmhvbG1zLnR5cGVz",
"LmNybS5ndWVzdHMuR3Vlc3RJbmRpY2F0b3ISTAoOcmVzZXJ2YXRpb25faWQY",
"BiABKAsyNC5ob2xtcy50eXBlcy5ib29raW5nLmluZGljYXRvcnMuUmVzZXJ2",
"YXRpb25JbmRpY2F0b3JCH1oHYm9va2luZ6oCE0hPTE1TLlR5cGVzLkJvb2tp",
"bmdiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.CRM.Guests.GuestIndicatorReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.FolioChargePostedNotification), global::HOLMS.Types.Booking.FolioChargePostedNotification.Parser, new[]{ "JWToken", "Opsdate", "PretaxLodgingCharge", "RoomTypeId", "GuestId", "ReservationId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class FolioChargePostedNotification : pb::IMessage<FolioChargePostedNotification> {
private static readonly pb::MessageParser<FolioChargePostedNotification> _parser = new pb::MessageParser<FolioChargePostedNotification>(() => new FolioChargePostedNotification());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FolioChargePostedNotification> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.FolioChargePostedNotificationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FolioChargePostedNotification() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FolioChargePostedNotification(FolioChargePostedNotification other) : this() {
jWToken_ = other.jWToken_;
Opsdate = other.opsdate_ != null ? other.Opsdate.Clone() : null;
PretaxLodgingCharge = other.pretaxLodgingCharge_ != null ? other.PretaxLodgingCharge.Clone() : null;
RoomTypeId = other.roomTypeId_ != null ? other.RoomTypeId.Clone() : null;
GuestId = other.guestId_ != null ? other.GuestId.Clone() : null;
ReservationId = other.reservationId_ != null ? other.ReservationId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FolioChargePostedNotification Clone() {
return new FolioChargePostedNotification(this);
}
/// <summary>Field number for the "j_w_token" field.</summary>
public const int JWTokenFieldNumber = 1;
private string jWToken_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JWToken {
get { return jWToken_; }
set {
jWToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "opsdate" field.</summary>
public const int OpsdateFieldNumber = 2;
private global::HOLMS.Types.Primitive.PbLocalDate opsdate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbLocalDate Opsdate {
get { return opsdate_; }
set {
opsdate_ = value;
}
}
/// <summary>Field number for the "pretax_lodging_charge" field.</summary>
public const int PretaxLodgingChargeFieldNumber = 3;
private global::HOLMS.Types.Primitive.MonetaryAmount pretaxLodgingCharge_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.MonetaryAmount PretaxLodgingCharge {
get { return pretaxLodgingCharge_; }
set {
pretaxLodgingCharge_ = value;
}
}
/// <summary>Field number for the "room_type_id" field.</summary>
public const int RoomTypeIdFieldNumber = 4;
private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomTypeId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomTypeId {
get { return roomTypeId_; }
set {
roomTypeId_ = value;
}
}
/// <summary>Field number for the "guest_id" field.</summary>
public const int GuestIdFieldNumber = 5;
private global::HOLMS.Types.CRM.Guests.GuestIndicator guestId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.CRM.Guests.GuestIndicator GuestId {
get { return guestId_; }
set {
guestId_ = value;
}
}
/// <summary>Field number for the "reservation_id" field.</summary>
public const int ReservationIdFieldNumber = 6;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservationId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator ReservationId {
get { return reservationId_; }
set {
reservationId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FolioChargePostedNotification);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FolioChargePostedNotification other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JWToken != other.JWToken) return false;
if (!object.Equals(Opsdate, other.Opsdate)) return false;
if (!object.Equals(PretaxLodgingCharge, other.PretaxLodgingCharge)) return false;
if (!object.Equals(RoomTypeId, other.RoomTypeId)) return false;
if (!object.Equals(GuestId, other.GuestId)) return false;
if (!object.Equals(ReservationId, other.ReservationId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JWToken.Length != 0) hash ^= JWToken.GetHashCode();
if (opsdate_ != null) hash ^= Opsdate.GetHashCode();
if (pretaxLodgingCharge_ != null) hash ^= PretaxLodgingCharge.GetHashCode();
if (roomTypeId_ != null) hash ^= RoomTypeId.GetHashCode();
if (guestId_ != null) hash ^= GuestId.GetHashCode();
if (reservationId_ != null) hash ^= ReservationId.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 (JWToken.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JWToken);
}
if (opsdate_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Opsdate);
}
if (pretaxLodgingCharge_ != null) {
output.WriteRawTag(26);
output.WriteMessage(PretaxLodgingCharge);
}
if (roomTypeId_ != null) {
output.WriteRawTag(34);
output.WriteMessage(RoomTypeId);
}
if (guestId_ != null) {
output.WriteRawTag(42);
output.WriteMessage(GuestId);
}
if (reservationId_ != null) {
output.WriteRawTag(50);
output.WriteMessage(ReservationId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JWToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JWToken);
}
if (opsdate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Opsdate);
}
if (pretaxLodgingCharge_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PretaxLodgingCharge);
}
if (roomTypeId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomTypeId);
}
if (guestId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(GuestId);
}
if (reservationId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FolioChargePostedNotification other) {
if (other == null) {
return;
}
if (other.JWToken.Length != 0) {
JWToken = other.JWToken;
}
if (other.opsdate_ != null) {
if (opsdate_ == null) {
opsdate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
Opsdate.MergeFrom(other.Opsdate);
}
if (other.pretaxLodgingCharge_ != null) {
if (pretaxLodgingCharge_ == null) {
pretaxLodgingCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
PretaxLodgingCharge.MergeFrom(other.PretaxLodgingCharge);
}
if (other.roomTypeId_ != null) {
if (roomTypeId_ == null) {
roomTypeId_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
RoomTypeId.MergeFrom(other.RoomTypeId);
}
if (other.guestId_ != null) {
if (guestId_ == null) {
guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator();
}
GuestId.MergeFrom(other.GuestId);
}
if (other.reservationId_ != null) {
if (reservationId_ == null) {
reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
ReservationId.MergeFrom(other.ReservationId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
JWToken = input.ReadString();
break;
}
case 18: {
if (opsdate_ == null) {
opsdate_ = new global::HOLMS.Types.Primitive.PbLocalDate();
}
input.ReadMessage(opsdate_);
break;
}
case 26: {
if (pretaxLodgingCharge_ == null) {
pretaxLodgingCharge_ = new global::HOLMS.Types.Primitive.MonetaryAmount();
}
input.ReadMessage(pretaxLodgingCharge_);
break;
}
case 34: {
if (roomTypeId_ == null) {
roomTypeId_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
input.ReadMessage(roomTypeId_);
break;
}
case 42: {
if (guestId_ == null) {
guestId_ = new global::HOLMS.Types.CRM.Guests.GuestIndicator();
}
input.ReadMessage(guestId_);
break;
}
case 50: {
if (reservationId_ == null) {
reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservationId_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region License
//
// OutputDocument.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using System;
#endregion
namespace SimpleFramework.Xml.Stream {
/// <summary>
/// The <c>OutputDocument</c> object is used to represent the
/// root of an XML document. This does not actually represent anything
/// that will be written to the generated document. It is used as a
/// way to create the root document element. Once the root element has
/// been created it can be committed by using this object.
/// </summary>
class OutputDocument : OutputNode {
/// <summary>
/// Represents a dummy output node map for the attributes.
/// </summary>
private OutputNodeMap table;
/// <summary>
/// Represents the writer that is used to create the element.
/// </summary>
private NodeWriter writer;
/// <summary>
/// This is the output stack used by the node writer object.
/// </summary>
private OutputStack stack;
/// <summary>
/// This represents the namespace reference used by this.
/// </summary>
private String reference;
/// <summary>
/// This is the comment that is to be written for the node.
/// </summary>
private String comment;
/// <summary>
/// Represents the value that has been set on this document.
/// </summary>
private String value;
/// <summary>
/// This is the output mode of this output document object.
/// </summary>
private Mode mode;
/// <summary>
/// Constructor for the <c>OutputDocument</c> object. This
/// is used to create an empty output node object that can be
/// used to create a root element for the generated document.
/// </summary>
/// <param name="writer">
/// this is the node writer to write the node to
/// </param>
/// <param name="stack">
/// this is the stack that contains the open nodes
/// </param>
public OutputDocument(NodeWriter writer, OutputStack stack) {
this.table = new OutputNodeMap(this);
this.mode = Mode.INHERIT;
this.writer = writer;
this.stack = stack;
}
/// <summary>
/// The default for the <c>OutputDocument</c> is null as it
/// does not require a namespace. A null prefix is always used by
/// the document as it represents a virtual node that does not
/// exist and will not form any part of the resulting XML.
/// </summary>
/// <returns>
/// this returns a null prefix for the output document
/// </returns>
public String Prefix {
get {
return null;
}
}
//public String GetPrefix() {
// return null;
//}
/// The default for the <c>OutputDocument</c> is null as it
/// does not require a namespace. A null prefix is always used by
/// the document as it represents a virtual node that does not
/// exist and will not form any part of the resulting XML.
/// </summary>
/// <param name="inherit">
/// if there is no explicit prefix then inherit
/// </param>
/// <returns>
/// this returns a null prefix for the output document
/// </returns>
public String GetPrefix(bool inherit) {
return null;
}
/// <summary>
/// This is used to acquire the reference that has been set on
/// this output node. Typically this should be null as this node
/// does not represent anything that actually exists. However
/// if a namespace reference is set it can be acquired.
/// </summary>
/// <returns>
/// this returns the namespace reference for this node
/// </returns>
public String Reference {
get {
return reference;
}
set {
this.reference = value;
}
}
//public String GetReference() {
// return reference;
//}
/// This is used to set the namespace reference for the document.
/// Setting a reference for the document node has no real effect
/// as the document node is virtual and is not written to the
/// resulting XML document that is generated.
/// </summary>
/// <param name="reference">
/// this is the namespace reference added
/// </param>
//public void SetReference(String reference) {
// this.reference = reference;
//}
/// This returns the <c>NamespaceMap</c> for the document.
/// The namespace map for the document must be null as this will
/// signify the end of the resolution process for a prefix if
/// given a namespace reference.
/// </summary>
/// <returns>
/// this will return a null namespace map object
/// </returns>
public NamespaceMap Namespaces {
get {
return null;
}
}
//public NamespaceMap GetNamespaces() {
// return null;
//}
/// This is used to acquire the <c>Node</c> that is the
/// parent of this node. This will return the node that is
/// the direct parent of this node and allows for siblings to
/// make use of nodes with their parents if required.
/// </summary>
/// <returns>
/// this will always return null for this output
/// </returns>
public OutputNode Parent {
get {
return null;
}
}
//public OutputNode GetParent() {
// return null;
//}
/// To signify that this is the document element this method will
/// return null. Any object with a handle on an output node that
/// has been created can check the name to determine its type.
/// </summary>
/// <returns>
/// this returns null for the name of the node
/// </returns>
public String Name {
get {
return null;
}
}
//public String GetName() {
// return null;
//}
/// This returns the value that has been set for this document.
/// The value returned is essentially a dummy value as this node
/// is never written to the resulting XML document.
/// </summary>
/// <returns>
/// the value that has been set with this document
/// </returns>
public String Value {
get {
return value;
}
set {
this.value = _value;
}
}
//public String GetValue() {
// return value;
//}
/// This is used to get the text comment for the element. This can
/// be null if no comment has been set. If no comment is set on
/// the node then no comment will be written to the resulting XML.
/// </summary>
/// <returns>
/// this is the comment associated with this element
/// </returns>
public String Comment {
get {
return comment;
}
set {
this.comment = value;
}
}
//public String GetComment() {
// return comment;
//}
/// This method is used to determine if this node is the root
/// node for the XML document. The root node is the first node
/// in the document and has no sibling nodes. This will return
/// true although the document node is not strictly the root.
/// </summary>
/// <returns>
/// returns true although this is not really a root
/// </returns>
public bool IsRoot() {
return true;
}
/// <summary>
/// The <c>Mode</c> is used to indicate the output mode
/// of this node. Three modes are possible, each determines
/// how a value, if specified, is written to the resulting XML
/// document. This is determined by the <c>setData</c>
/// method which will set the output to be CDATA or escaped,
/// if neither is specified the mode is inherited.
/// </summary>
/// <returns>
/// this returns the mode of this output node object
/// </returns>
public Mode Mode {
get {
return mode;
}
set {
this.mode = value;
}
}
//public Mode GetMode() {
// return mode;
//}
/// This is used to set the output mode of this node to either
/// be CDATA, escaped, or inherited. If the mode is set to data
/// then any value specified will be written in a CDATA block,
/// if this is set to escaped values are escaped. If however
/// this method is set to inherited then the mode is inherited
/// from the parent node.
/// </summary>
/// <param name="mode">
/// this is the output mode to set the node to
/// </param>
//public void SetMode(Mode mode) {
// this.mode = mode;
//}
/// This method is used for convenience to add an attribute node
/// to the attribute <c>NodeMap</c>. The attribute added
/// can be removed from the element by using the node map.
/// </summary>
/// <param name="name">
/// this is the name of the attribute to be added
/// </param>
/// <param name="value">
/// this is the value of the node to be added
/// </param>
/// <returns>
/// this returns the node that has just been added
/// </returns>
public OutputNode SetAttribute(String name, String value) {
return table.Put(name, value);
}
/// <summary>
/// This returns a <c>NodeMap</c> which can be used to add
/// nodes to this node. The node map returned by this is a dummy
/// map, as this output node is never written to the XML document.
/// </summary>
/// <returns>
/// returns the node map used to manipulate attributes
/// </returns>
public NodeMap<OutputNode> Attributes {
get {
return table;
}
}
//public NodeMap<OutputNode> GetAttributes() {
// return table;
//}
/// This is used to set a text value to the element. This effect
/// of adding this to the document node will not change what
/// is actually written to the generated XML document.
/// </summary>
/// <param name="value">
/// this is the text value to add to this element
/// </param>
//public void SetValue(String value) {
// this.value = value;
//}
/// This is used to set a text comment to the element. This will
/// be written just before the actual element is written. Only a
/// single comment can be set for each output node written.
/// </summary>
/// <param name="comment">
/// this is the comment to set on the node
/// </param>
//public void SetComment(String comment) {
// this.comment = comment;
//}
/// This is used to set the output mode of this node to either
/// be CDATA or escaped. If this is set to true the any value
/// specified will be written in a CDATA block, if this is set
/// to false the values is escaped. If however this method is
/// never invoked then the mode is inherited from the parent.
/// </summary>
/// <param name="data">
/// if true the value is written as a CDATA block
/// </param>
public bool Data {
set {
if(value) {
mode = Mode.DATA;
} else {
mode = Mode.ESCAPE;
}
}
}
//public void SetData(bool data) {
// if(data) {
// mode = Mode.DATA;
// } else {
// mode = Mode.ESCAPE;
// }
//}
/// This is used to create a child element within the element that
/// this object represents. When a new child is created with this
/// method then the previous child is committed to the document.
/// The created <c>OutputNode</c> object can be used to add
/// attributes to the child element as well as other elements.
/// </summary>
/// <param name="name">
/// this is the name of the child element to create
/// </param>
public OutputNode GetChild(String name) {
return writer.WriteElement(this, name);
}
/// <summary>
/// This is used to remove any uncommitted changes. Removal of an
/// output node can only be done if it has no siblings and has
/// not yet been committed. If the node is committed then this
/// will throw an exception to indicate that it cannot be removed.
/// </summary>
public void Remove() {
if(stack.isEmpty()) {
throw new NodeException("No root node");
}
stack.Bottom().Remove();
}
/// <summary>
/// This will commit this element and any uncommitted elements
/// elements that are decendents of this node. For instance if
/// any child or grand child remains open under this element
/// then those elements will be closed before this is closed.
/// </summary>
/// or if a root element has not yet been created
public void Commit() {
if(stack.isEmpty()) {
throw new NodeException("No root node");
}
stack.Bottom().Commit();
}
/// <summary>
/// This is used to determine whether this node has been committed.
/// This will return true if no root element has been created or
/// if the root element for the document has already been commited.
/// </summary>
/// <returns>
/// true if the node is committed or has not been created
/// </returns>
public bool IsCommitted() {
return stack.isEmpty();
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
namespace Net.Pkcs11Interop.HighLevelAPI.MechanismParams
{
/// <summary>
/// Parameters for the CKM_WTLS_MASTER_KEY_DERIVE and CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC mechanisms
/// </summary>
public class CkWtlsMasterKeyDeriveParams : IMechanismParams, IDisposable
{
/// <summary>
/// Flag indicating whether instance has been disposed
/// </summary>
private bool _disposed = false;
/// <summary>
/// Platform specific CkWtlsMasterKeyDeriveParams
/// </summary>
private HighLevelAPI40.MechanismParams.CkWtlsMasterKeyDeriveParams _params40 = null;
/// <summary>
/// Platform specific CkWtlsMasterKeyDeriveParams
/// </summary>
private HighLevelAPI41.MechanismParams.CkWtlsMasterKeyDeriveParams _params41 = null;
/// <summary>
/// Platform specific CkSsl3MasterKeyDeriveParams
/// </summary>
private HighLevelAPI80.MechanismParams.CkWtlsMasterKeyDeriveParams _params80 = null;
/// <summary>
/// Platform specific CkSsl3MasterKeyDeriveParams
/// </summary>
private HighLevelAPI81.MechanismParams.CkWtlsMasterKeyDeriveParams _params81 = null;
/// <summary>
/// WTLS protocol version information
/// </summary>
public CkVersion Version
{
get
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (Platform.UnmanagedLongSize == 4)
{
if (Platform.StructPackingSize == 0)
return (_params40.Version == null) ? null : new CkVersion(_params40.Version);
else
return (_params41.Version == null) ? null : new CkVersion(_params41.Version);
}
else
{
if (Platform.StructPackingSize == 0)
return (_params80.Version == null) ? null : new CkVersion(_params80.Version);
else
return (_params81.Version == null) ? null : new CkVersion(_params81.Version);
}
}
}
/// <summary>
/// Client's and server's random data information
/// </summary>
private CkWtlsRandomData _randomInfo = null;
/// <summary>
/// Initializes a new instance of the CkWtlsMasterKeyDeriveParams class.
/// </summary>
/// <param name='digestMechanism'>Digest mechanism to be used (CKM)</param>
/// <param name='randomInfo'>Client's and server's random data information</param>
/// <param name='dh'>Set to false for CKM_WTLS_MASTER_KEY_DERIVE mechanism and to true for CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC mechanism</param>
public CkWtlsMasterKeyDeriveParams(ulong digestMechanism, CkWtlsRandomData randomInfo, bool dh)
{
if (randomInfo == null)
throw new ArgumentNullException("randomInfo");
// Keep reference to randomInfo so GC will not free it while this object exists
_randomInfo = randomInfo;
if (Platform.UnmanagedLongSize == 4)
{
if (Platform.StructPackingSize == 0)
_params40 = new HighLevelAPI40.MechanismParams.CkWtlsMasterKeyDeriveParams(Convert.ToUInt32(digestMechanism), _randomInfo._params40, dh);
else
_params41 = new HighLevelAPI41.MechanismParams.CkWtlsMasterKeyDeriveParams(Convert.ToUInt32(digestMechanism), _randomInfo._params41, dh);
}
else
{
if (Platform.StructPackingSize == 0)
_params80 = new HighLevelAPI80.MechanismParams.CkWtlsMasterKeyDeriveParams(digestMechanism, _randomInfo._params80, dh);
else
_params81 = new HighLevelAPI81.MechanismParams.CkWtlsMasterKeyDeriveParams(digestMechanism, _randomInfo._params81, dh);
}
}
#region IMechanismParams
/// <summary>
/// Returns managed object that can be marshaled to an unmanaged block of memory
/// </summary>
/// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns>
public object ToMarshalableStructure()
{
if (this._disposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (Platform.UnmanagedLongSize == 4)
return (Platform.StructPackingSize == 0) ? _params40.ToMarshalableStructure() : _params41.ToMarshalableStructure();
else
return (Platform.StructPackingSize == 0) ? _params80.ToMarshalableStructure() : _params81.ToMarshalableStructure();
}
#endregion
#region IDisposable
/// <summary>
/// Disposes object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes object
/// </summary>
/// <param name="disposing">Flag indicating whether managed resources should be disposed</param>
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
// Dispose managed objects
if (_params40 != null)
{
_params40.Dispose();
_params40 = null;
}
if (_params41 != null)
{
_params41.Dispose();
_params41 = null;
}
if (_params80 != null)
{
_params80.Dispose();
_params80 = null;
}
if (_params81 != null)
{
_params81.Dispose();
_params81 = null;
}
}
// Dispose unmanaged objects
_disposed = true;
}
}
/// <summary>
/// Class destructor that disposes object if caller forgot to do so
/// </summary>
~CkWtlsMasterKeyDeriveParams()
{
Dispose(false);
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V10.Resources
{
/// <summary>Resource name for the <c>SharedCriterion</c> resource.</summary>
public sealed partial class SharedCriterionName : gax::IResourceName, sys::IEquatable<SharedCriterionName>
{
/// <summary>The possible contents of <see cref="SharedCriterionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>
/// .
/// </summary>
CustomerSharedSetCriterion = 1,
}
private static gax::PathTemplate s_customerSharedSetCriterion = new gax::PathTemplate("customers/{customer_id}/sharedCriteria/{shared_set_id_criterion_id}");
/// <summary>Creates a <see cref="SharedCriterionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SharedCriterionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SharedCriterionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SharedCriterionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SharedCriterionName"/> with the pattern
/// <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SharedCriterionName"/> constructed from the provided ids.</returns>
public static SharedCriterionName FromCustomerSharedSetCriterion(string customerId, string sharedSetId, string criterionId) =>
new SharedCriterionName(ResourceNameType.CustomerSharedSetCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SharedCriterionName"/> with pattern
/// <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SharedCriterionName"/> with pattern
/// <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string sharedSetId, string criterionId) =>
FormatCustomerSharedSetCriterion(customerId, sharedSetId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SharedCriterionName"/> with pattern
/// <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SharedCriterionName"/> with pattern
/// <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerSharedSetCriterion(string customerId, string sharedSetId, string criterionId) =>
s_customerSharedSetCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="SharedCriterionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sharedCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SharedCriterionName"/> if successful.</returns>
public static SharedCriterionName Parse(string sharedCriterionName) => Parse(sharedCriterionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SharedCriterionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sharedCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SharedCriterionName"/> if successful.</returns>
public static SharedCriterionName Parse(string sharedCriterionName, bool allowUnparsed) =>
TryParse(sharedCriterionName, allowUnparsed, out SharedCriterionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SharedCriterionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sharedCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SharedCriterionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sharedCriterionName, out SharedCriterionName result) =>
TryParse(sharedCriterionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SharedCriterionName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sharedCriterionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SharedCriterionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sharedCriterionName, bool allowUnparsed, out SharedCriterionName result)
{
gax::GaxPreconditions.CheckNotNull(sharedCriterionName, nameof(sharedCriterionName));
gax::TemplatedResourceName resourceName;
if (s_customerSharedSetCriterion.TryParseName(sharedCriterionName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerSharedSetCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sharedCriterionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private SharedCriterionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null, string customerId = null, string sharedSetId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CriterionId = criterionId;
CustomerId = customerId;
SharedSetId = sharedSetId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SharedCriterionName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public SharedCriterionName(string customerId, string sharedSetId, string criterionId) : this(ResourceNameType.CustomerSharedSetCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>SharedSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SharedSetId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerSharedSetCriterion: return s_customerSharedSetCriterion.Expand(CustomerId, $"{SharedSetId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SharedCriterionName);
/// <inheritdoc/>
public bool Equals(SharedCriterionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SharedCriterionName a, SharedCriterionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SharedCriterionName a, SharedCriterionName b) => !(a == b);
}
public partial class SharedCriterion
{
/// <summary>
/// <see cref="SharedCriterionName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal SharedCriterionName ResourceNameAsSharedCriterionName
{
get => string.IsNullOrEmpty(ResourceName) ? null : SharedCriterionName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="SharedSetName"/>-typed view over the <see cref="SharedSet"/> resource name property.
/// </summary>
internal SharedSetName SharedSetAsSharedSetName
{
get => string.IsNullOrEmpty(SharedSet) ? null : SharedSetName.Parse(SharedSet, allowUnparsed: true);
set => SharedSet = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
internal static class SocketPal
{
public const bool SupportsMultipleConnectAttempts = true;
private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime)
{
const int microcnv = 1000000;
socketTime.Seconds = (int)(microseconds / microcnv);
socketTime.Microseconds = (int)(microseconds % microcnv);
}
public static void Initialize()
{
// Ensure that WSAStartup has been called once per process.
// The System.Net.NameResolution contract is responsible for the initialization.
Dns.GetHostName();
}
public static SocketError GetLastSocketError()
{
int win32Error = Marshal.GetLastWin32Error();
Debug.Assert(win32Error != 0, "Expected non-0 error");
return (SocketError)win32Error;
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
socket = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetBlocking(SafeCloseSocket handle, bool shouldBlock, out bool willBlock)
{
int intBlocking = shouldBlock ? 0 : -1;
SocketError errorCode;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref intBlocking);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
willBlock = intBlocking == 0;
return errorCode;
}
public static SocketError GetSockName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetAvailable(SafeCloseSocket handle, out int available)
{
int value = 0;
SocketError errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONREAD,
ref value);
available = value;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetPeerName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Bind(SafeCloseSocket handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen)
{
SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Listen(SafeCloseSocket handle, int backlog)
{
SocketError errorCode = Interop.Winsock.listen(handle, backlog);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Accept(SafeCloseSocket handle, byte[] buffer, ref int nameLen, out SafeCloseSocket socket)
{
socket = SafeCloseSocket.Accept(handle, buffer, ref nameLen);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Connect(SafeCloseSocket handle, byte[] peerAddress, int peerAddressLen)
{
SocketError errorCode = Interop.Winsock.WSAConnect(
handle.DangerousGetHandle(),
peerAddress,
peerAddressLen,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[] leasedWSA = null;
GCHandle[] leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
ArrayPool<GCHandle>.Shared.Return(leasedGC);
}
}
}
public static unsafe SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Send(handle, new ReadOnlySpan<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Send(SafeCloseSocket handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesSent;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesSent = Interop.Winsock.send(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static unsafe SocketError SendFile(SafeCloseSocket handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
fixed (byte* prePinnedBuffer = preBuffer)
fixed (byte* postPinnedBuffer = postBuffer)
{
bool success = TransmitFileHelper(handle, fileHandle, null, preBuffer, postBuffer, flags);
return (success ? SocketError.Success : SocketPal.GetLastSocketError());
}
}
public static unsafe SocketError SendTo(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
{
int bytesSent;
if (buffer.Length == 0)
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
null,
0,
socketFlags,
peerAddress,
peerAddressSize);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
pinnedBuffer + offset,
size,
socketFlags,
peerAddress,
peerAddressSize);
}
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[] leasedWSA = null;
GCHandle[] leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
ref socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
ArrayPool<GCHandle>.Shared.Return(leasedGC);
}
}
}
public static unsafe SocketError Receive(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Receive(handle, new Span<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Receive(SafeCloseSocket handle, Span<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesReceived;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlData* controlBuffer)
{
IPAddress address = controlBuffer->length == UIntPtr.Zero ? IPAddress.None : new IPAddress((long)controlBuffer->address);
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlDataIPv6* controlBuffer)
{
IPAddress address = controlBuffer->length != UIntPtr.Zero ?
new IPAddress(new Span<byte>(controlBuffer->address, Interop.Winsock.IPv6AddressLength)) :
IPAddress.IPv6None;
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
bool ipv4, ipv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6);
bytesTransferred = 0;
receiveAddress = socketAddress;
ipPacketInformation = default(IPPacketInformation);
fixed (byte* ptrBuffer = buffer)
fixed (byte* ptrSocketAddress = socketAddress.Buffer)
{
Interop.Winsock.WSAMsg wsaMsg;
wsaMsg.socketAddress = (IntPtr)ptrSocketAddress;
wsaMsg.addressLength = (uint)socketAddress.Size;
wsaMsg.flags = socketFlags;
WSABuffer wsaBuffer;
wsaBuffer.Length = size;
wsaBuffer.Pointer = (IntPtr)(ptrBuffer + offset);
wsaMsg.buffers = (IntPtr)(&wsaBuffer);
wsaMsg.count = 1;
if (ipv4)
{
Interop.Winsock.ControlData controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlData);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else if (ipv6)
{
Interop.Winsock.ControlDataIPv6 controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlDataIPv6);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else
{
wsaMsg.controlBuffer.Pointer = IntPtr.Zero;
wsaMsg.controlBuffer.Length = 0;
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
}
socketFlags = wsaMsg.flags;
}
return SocketError.Success;
}
public static unsafe SocketError ReceiveFrom(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
{
int bytesReceived;
if (buffer.Length == 0)
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress, ref addressLength);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength);
}
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError WindowsIoctl(SafeCloseSocket handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
handle.DangerousGetHandle(),
ioControlCode,
optionInValue,
optionInValue != null ? optionInValue.Length : 0,
optionOutValue,
optionOutValue != null ? optionOutValue.Length : 0,
out optionLength,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
public static SocketError SetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address);
#pragma warning restore CS0618
if (optionValue.LocalAddress != null)
{
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address);
#pragma warning restore CS0618
}
else
{ //this structure works w/ interfaces as well
int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex);
ipmr.InterfaceAddress = unchecked((int)ifIndex);
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
}
#endif
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IP,
optionName,
ref ipmr,
Interop.Winsock.IPMulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IPv6,
optionName,
ref ipmr,
Interop.Winsock.IPv6MulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lngopt,
4);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel)
{
socket.SetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel, protectionLevel);
}
public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
out optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(MulticastOption);
return GetLastSocketError();
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
#endif // BIGENDIAN
IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress);
IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress);
optionValue = new MulticastOption(multicastAddr, multicastIntr);
return SocketError.Success;
}
public static SocketError GetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(IPv6MulticastOption);
return GetLastSocketError();
}
optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
return SocketError.Success;
}
public static SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
int optlen = 4;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
out lngopt,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(LingerOption);
return GetLastSocketError();
}
optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
return SocketError.Success;
}
public static unsafe SocketError Poll(SafeCloseSocket handle, int microseconds, SelectMode mode, out bool status)
{
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr* fileDescriptorSet = stackalloc IntPtr[2] { (IntPtr)1, rawHandle };
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
// A negative timeout value implies an indefinite wait.
int socketCount;
if (microseconds != -1)
{
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
IntPtr.Zero);
}
if ((SocketError)socketCount == SocketError.SocketError)
{
status = false;
return GetLastSocketError();
}
status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
return SocketError.Success;
}
public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack
bool ShouldStackAlloc(IList list, ref IntPtr[] lease, out Span<IntPtr> span)
{
int count;
if (list == null || (count = list.Count) == 0)
{
span = default;
return false;
}
if (count >= StackThreshold) // note on >= : the first element is reserved for internal length
{
span = lease = ArrayPool<IntPtr>.Shared.Rent(count + 1);
return false;
}
span = default;
return true;
}
IntPtr[] leaseRead = null, leaseWrite = null, leaseError = null;
try
{
Span<IntPtr> readfileDescriptorSet = ShouldStackAlloc(checkRead, ref leaseRead, out var tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkRead, readfileDescriptorSet);
Span<IntPtr> writefileDescriptorSet = ShouldStackAlloc(checkWrite, ref leaseWrite, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkWrite, writefileDescriptorSet);
Span<IntPtr> errfileDescriptorSet = ShouldStackAlloc(checkError, ref leaseError, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkError, errfileDescriptorSet);
// This code used to erroneously pass a non-null timeval structure containing zeroes
// to select() when the caller specified (-1) for the microseconds parameter. That
// caused select to actually have a *zero* timeout instead of an infinite timeout
// turning the operation into a non-blocking poll.
//
// Now we pass a null timeval struct when microseconds is (-1).
//
// Negative microsecond values that weren't exactly (-1) were originally successfully
// converted to a timeval struct containing unsigned non-zero integers. This code
// retains that behavior so that any app working around the original bug with,
// for example, (-2) specified for microseconds, will continue to get the same behavior.
int socketCount;
fixed (IntPtr* readPtr = &MemoryMarshal.GetReference(readfileDescriptorSet))
fixed (IntPtr* writePtr = &MemoryMarshal.GetReference(writefileDescriptorSet))
fixed (IntPtr* errPtr = &MemoryMarshal.GetReference(errfileDescriptorSet))
{
if (microseconds != -1)
{
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
IntPtr.Zero);
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}");
if ((SocketError)socketCount == SocketError.SocketError)
{
return GetLastSocketError();
}
Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet);
Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet);
Socket.SelectFileDescriptor(checkError, errfileDescriptorSet);
return SocketError.Success;
}
finally
{
if (leaseRead != null) ArrayPool<IntPtr>.Shared.Return(leaseRead);
if (leaseWrite != null) ArrayPool<IntPtr>.Shared.Return(leaseWrite);
if (leaseError != null) ArrayPool<IntPtr>.Shared.Return(leaseError);
}
}
public static SocketError Shutdown(SafeCloseSocket handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
SocketError err = Interop.Winsock.shutdown(handle, (int)how);
if (err != SocketError.SocketError)
{
return SocketError.Success;
}
err = GetLastSocketError();
Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected));
return err;
}
public static unsafe SocketError ConnectAsync(Socket socket, SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
// This will pin the socketAddress buffer.
asyncResult.SetUnmanagedStructures(socketAddress);
try
{
int ignoreBytesSent;
bool success = socket.ConnectEx(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0),
socketAddressLen,
IntPtr.Zero,
0,
out ignoreBytesSent,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up unmanaged structures for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
// This assumes preBuffer/postBuffer are pinned already
private static unsafe bool TransmitFileHelper(
SafeHandle socket,
SafeHandle fileHandle,
NativeOverlapped* overlapped,
byte[] preBuffer,
byte[] postBuffer,
TransmitFileOptions flags)
{
bool needTransmitFileBuffers = false;
Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers);
if (preBuffer != null && preBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
transmitFileBuffers.HeadLength = preBuffer.Length;
}
if (postBuffer != null && postBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
transmitFileBuffers.TailLength = postBuffer.Length;
}
bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped,
needTransmitFileBuffers ? &transmitFileBuffers : null, flags);
return success;
}
public static unsafe SocketError SendFileAsync(SafeCloseSocket handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
try
{
bool success = TransmitFileHelper(
handle,
fileStream?.SafeFileHandle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
preBuffer,
postBuffer,
flags);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendToAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASendTo.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASendTo(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.SocketAddress.Size,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecv.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveFromAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecvFrom.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecvFrom(
handle.DangerousGetHandle(), // to minimize chances of handle recycling from misuse, this should use DangerousAddRef/Release, but it adds too much overhead
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.GetSocketAddressSizePtr(),
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
GC.KeepAlive(handle); // small extra safe guard against handle getting collected/finalized while P/Invoke in progress
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);
try
{
int bytesTransfered;
SocketError errorCode = (SocketError)socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
out bytesTransfered,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransfered);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError AcceptAsync(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
// The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes
// of associated data for each.
int addressBufferSize = socketAddressSize + 16;
byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)];
// Set up asyncResult for overlapped AcceptEx.
// This call will use completion ports on WinNT.
asyncResult.SetUnmanagedStructures(buffer, addressBufferSize);
try
{
// This can throw ObjectDisposedException.
int bytesTransferred;
bool success = socket.AcceptEx(
handle,
acceptHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
receiveSize,
addressBufferSize,
addressBufferSize,
out bytesTransferred,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static void CheckDualModeReceiveSupport(Socket socket)
{
// Dual-mode sockets support received packet info on Windows.
}
internal static unsafe SocketError DisconnectAsync(Socket socket, SafeCloseSocket handle, bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(null);
try
{
// This can throw ObjectDisposedException
bool success = socket.DisconnectEx(
handle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
(int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
internal static SocketError Disconnect(Socket socket, SafeCloseSocket handle, bool reuseSocket)
{
SocketError errorCode = SocketError.Success;
// This can throw ObjectDisposedException (handle, and retrieving the delegate).
if (!socket.DisconnectExBlocking(handle, IntPtr.Zero, (int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0))
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
}
| |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* This class was altered and provided by jkealey - thanks!
*
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using SubSonic.Utilities;
namespace SubSonic
{
/// <summary>
///
/// </summary>
public class LavaBlastManyManyList : ManyManyList
{
private string _foreignOrderBy = String.Empty;
private string _foreignTextColumnName = String.Empty;
private string _foreignValueColumnName = String.Empty;
private string _foreignWhere = String.Empty;
private string _mapTableFkToForeignTable = String.Empty;
private string _mapTableFkToPrimaryTable = String.Empty;
private string _primaryKeyName = String.Empty;
/// <summary>
/// Gets or sets the name of the primary key.
/// </summary>
/// <value>The name of the primary key.</value>
public string PrimaryKeyName
{
get { return _primaryKeyName; }
set { _primaryKeyName = value; }
}
/// <summary>
/// Gets or sets the name of the foreign value column.
/// </summary>
/// <value>The name of the foreign value column.</value>
public string ForeignValueColumnName
{
get { return _foreignValueColumnName; }
set { _foreignValueColumnName = value; }
}
/// <summary>
/// Gets or sets the name of the foreign text column.
/// </summary>
/// <value>The name of the foreign text column.</value>
public string ForeignTextColumnName
{
get { return _foreignTextColumnName; }
set { _foreignTextColumnName = value; }
}
/// <summary>
/// Gets or sets the foreign order by.
/// </summary>
/// <value>The foreign order by.</value>
public string ForeignOrderBy
{
get { return _foreignOrderBy; }
set { _foreignOrderBy = value; }
}
/// <summary>
/// Gets or sets the foreign where.
/// </summary>
/// <value>The foreign where.</value>
public string ForeignWhere
{
get { return _foreignWhere; }
set { _foreignWhere = value; }
}
/// <summary>
/// Gets or sets the map table fk to primary table.
/// </summary>
/// <value>The map table fk to primary table.</value>
public string MapTableFkToPrimaryTable
{
get { return _mapTableFkToPrimaryTable; }
set { _mapTableFkToPrimaryTable = value; }
}
/// <summary>
/// Gets or sets the map table fk to foreign table.
/// </summary>
/// <value>The map table fk to foreign table.</value>
public string MapTableFkToForeignTable
{
get { return _mapTableFkToForeignTable; }
set { _mapTableFkToForeignTable = value; }
}
/// <summary>
/// If the user does not specify any column names, they are inferred from the schema.
///
/// </summary>
protected virtual void LoadColumnNames()
{
// we don't have a user-defined key
if(String.IsNullOrEmpty(PrimaryKeyName))
{
// load primary table
TableSchema.Table pkTable = DataService.GetSchema(PrimaryTableName, ProviderName);
PrimaryKeyName = pkTable.PrimaryKey == null ? pkTable.Columns[0].ColumnName : pkTable.PrimaryKey.ColumnName;
}
// we don't have a user-defined key
if(String.IsNullOrEmpty(ForeignValueColumnName) || String.IsNullOrEmpty(ForeignTextColumnName))
{
TableSchema.Table fkTable = DataService.GetSchema(ForeignTableName, ProviderName);
// we don't have a user-defined key
if(String.IsNullOrEmpty(ForeignValueColumnName))
ForeignValueColumnName = fkTable.PrimaryKey == null ? fkTable.Columns[0].ColumnName : fkTable.PrimaryKey.ColumnName;
// use another column for the name if it is available
if(String.IsNullOrEmpty(ForeignTextColumnName))
ForeignTextColumnName = fkTable.Columns[fkTable.Columns.Count >= 1 ? 1 : 0].ColumnName;
}
/* detect the mapping table column names */
if(String.IsNullOrEmpty(_mapTableFkToPrimaryTable) || String.IsNullOrEmpty(_mapTableFkToForeignTable))
{
// load mapping table
TableSchema.Table mapTable = DataService.GetSchema(MapTableName, ProviderName);
foreach(TableSchema.ForeignKeyTable fkt in mapTable.ForeignKeys)
{
if(String.IsNullOrEmpty(_mapTableFkToPrimaryTable) && fkt.TableName.ToLower() == PrimaryTableName.ToLower())
_mapTableFkToPrimaryTable = fkt.ColumnName;
else if(String.IsNullOrEmpty(_mapTableFkToForeignTable) && fkt.TableName.ToLower() == ForeignTableName.ToLower())
_mapTableFkToForeignTable = fkt.ColumnName;
}
}
}
/// <summary>
/// Selects the elements from the mapped table which are also in the filtered foreign query
///
/// </summary>
/// <param name="provider">the provider</param>
/// <param name="cmd">The command to which the select from the mapped table will be appended</param>
protected virtual void BuildMappedElementCommand(DataProvider provider, QueryCommand cmd)
{
string userFilter = String.Empty;
string idParam = provider.FormatParameterNameForSQL("id");
if (!String.IsNullOrEmpty(ForeignWhere))
{
userFilter +=
String.Format("INNER JOIN {0} ON {0}.{1}={2}.{1} WHERE {2}.{3}={4} AND {5}", ForeignTableName, ForeignValueColumnName, MapTableName, MapTableFkToPrimaryTable,
idParam, ForeignWhere);
}
else
userFilter += String.Format("WHERE {0}={1}", MapTableFkToPrimaryTable, idParam);
cmd.CommandSql += String.Format("SELECT {1}.{0} FROM {1} {2}", MapTableFkToForeignTable, MapTableName, userFilter);
cmd.Parameters.Add(idParam, PrimaryKeyValue, DataService.GetSchema(PrimaryTableName, ProviderName).PrimaryKey.DataType);
}
/// <summary>
/// Builds a filtered and sorted list of elements to be put in the checkboxlist
/// </summary>
/// <returns></returns>
protected virtual QueryCommand BuildForeignQueryCommand()
{
// filter and sort according to user preferences.
string userFilterAndSort = String.Empty;
if(!String.IsNullOrEmpty(ForeignWhere))
userFilterAndSort += SqlFragment.WHERE + ForeignWhere;
if(!String.IsNullOrEmpty(ForeignOrderBy))
userFilterAndSort += SqlFragment.ORDER_BY + ForeignOrderBy;
QueryCommand cmd =
new QueryCommand(String.Format("SELECT {0},{1} FROM {2} {3};", ForeignValueColumnName, ForeignTextColumnName, ForeignTableName, userFilterAndSort), ProviderName);
return cmd;
}
/// <summary>
/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
/// </summary>
protected override void CreateChildControls()
{
base.CreateChildControls();
Items.Clear();
// make sure the default props are set
if(String.IsNullOrEmpty(PrimaryKeyValue) || String.IsNullOrEmpty(PrimaryTableName) || String.IsNullOrEmpty(ProviderName) || String.IsNullOrEmpty(MapTableName))
{
throw new Exception(
"Missing a setting. Please be sure to set the PrimaryKeyValue (e.g. 'ProductID', PrimaryTableName (e.g. 'Products'), ProviderName (e.g. 'Northwind'), and MapTableName (e.g. Product_Category_Map)");
}
DataProvider provider = DataService.GetInstance(ProviderName);
// load column names
LoadColumnNames();
QueryCommand cmd = BuildForeignQueryCommand();
BuildMappedElementCommand(provider, cmd);
//load the list items
using(IDataReader rdr = DataService.GetReader(cmd))
{
while(rdr.Read())
{
ListItem item = new ListItem(rdr[ForeignTextColumnName].ToString(), rdr[ForeignValueColumnName].ToString());
Items.Add(item);
}
rdr.NextResult();
while(rdr.Read())
{
string thisVal = rdr[MapTableFkToForeignTable].ToString().ToLower();
foreach(ListItem loopItem in Items)
{
if(loopItem.Value.ToLower() == thisVal)
loopItem.Selected = true;
}
}
rdr.Close();
}
}
/// <summary>
/// Saves this instance.
/// </summary>
public new virtual void Save()
{
DataProvider provider = DataService.GetInstance(ProviderName);
LoadColumnNames();
// read the current state of the checkboxes
Dictionary<string, bool> newState = new Dictionary<string, bool>();
foreach(ListItem l in Items)
newState.Add(l.Value, l.Selected);
// read what is in the database
List<string> pastState = new List<string>();
QueryCommand lookupCmd = new QueryCommand(String.Empty, ProviderName); // quick hack to re-use BuildMappedElementCommand
BuildMappedElementCommand(provider, lookupCmd);
using(IDataReader rdr = DataService.GetReader(lookupCmd))
{
while(rdr.Read())
pastState.Add(rdr[MapTableFkToForeignTable].ToString());
rdr.Close();
}
// build the commands to be executed.
QueryCommandCollection coll = new QueryCommandCollection();
string fkParam = provider.FormatParameterNameForSQL("fkID");
string pkParam = provider.FormatParameterNameForSQL("pkID");
foreach(KeyValuePair<string, bool> kvp in newState)
{
string sql;
// if we have it now but did not before
if(kvp.Value && !pastState.Contains(kvp.Key))
sql = String.Format("INSERT INTO {0} ({1},{2}) VALUES ({3},{4})", MapTableName, MapTableFkToForeignTable, MapTableFkToPrimaryTable, fkParam, pkParam);
else if(!kvp.Value && pastState.Contains(kvp.Key)) // we don't have it now but had it before
sql = String.Format("DELETE FROM {0} WHERE {1} = {2} AND {3} = {4}", MapTableName, MapTableFkToPrimaryTable, pkParam, MapTableFkToForeignTable, fkParam);
else
continue; // nothing changed.
QueryCommand cmd = new QueryCommand(sql, ProviderName);
cmd.Parameters.Add(fkParam, kvp.Key, DataService.GetSchema(ForeignTableName, ProviderName).PrimaryKey.DataType);
cmd.Parameters.Add(pkParam, PrimaryKeyValue, DataService.GetSchema(PrimaryTableName, ProviderName).PrimaryKey.DataType);
coll.Add(cmd);
}
//execute
if(coll.Count > 0)
DataService.ExecuteTransaction(coll);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectEqualityComparer`1")]
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
static readonly EqualityComparer<T> defaultComparer = CreateComparer();
public static EqualityComparer<T> Default {
get {
Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
return defaultComparer;
}
}
//
// Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
// saves the right instantiations
//
[System.Security.SecuritySafeCritical] // auto-generated
private static EqualityComparer<T> CreateComparer()
{
Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
object result = null;
RuntimeType t = (RuntimeType)typeof(T);
// Specialize type byte for performance reasons
if (t == typeof(byte)) {
result = new ByteEqualityComparer();
}
// If T implements IEquatable<T> return a GenericEqualityComparer<T>
else if (typeof(IEquatable<T>).IsAssignableFrom(t))
{
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer<int>), t);
}
else if (default(T) == null) // Reference type/Nullable
{
// If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U>
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
if (typeof(IEquatable<>).MakeGenericType(u).IsAssignableFrom(u)) {
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer<int>), u);
}
}
}
// See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation
else if (t.IsEnum) {
TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t));
// Depending on the enum type, we need to special case the comparers so that we avoid boxing
// Note: We have different comparers for Short and SByte because for those types we need to make sure we call GetHashCode on the actual underlying type as the
// implementation of GetHashCode is more complex than for the other types.
switch (underlyingTypeCode) {
case TypeCode.Int16: // short
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ShortEnumEqualityComparer<short>), t);
break;
case TypeCode.SByte:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(SByteEnumEqualityComparer<sbyte>), t);
break;
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Byte:
case TypeCode.UInt16: //ushort
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<int>), t);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(LongEnumEqualityComparer<long>), t);
break;
}
}
return result != null ?
(EqualityComparer<T>)result :
new ObjectEqualityComparer<T>(); // Fallback to ObjectEqualityComparer, which uses boxing
}
[Pure]
public abstract bool Equals(T x, T y);
[Pure]
public abstract int GetHashCode(T obj);
internal virtual int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++) {
if (Equals(array[i], value)) return i;
}
return -1;
}
internal virtual int LastIndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
for (int i = startIndex; i >= endIndex; i--) {
if (Equals(array[i], value)) return i;
}
return -1;
}
int IEqualityComparer.GetHashCode(object obj) {
if (obj == null) return 0;
if (obj is T) return GetHashCode((T)obj);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return 0;
}
bool IEqualityComparer.Equals(object x, object y) {
if (x == y) return true;
if (x == null || y == null) return false;
if ((x is T) && (y is T)) return Equals((T)x, (T)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return false;
}
}
// The methods in this class look identical to the inherited methods, but the calls
// to Equal bind to IEquatable<T>.Equals(T) instead of Object.Equals(Object)
[Serializable]
internal class GenericEqualityComparer<T>: EqualityComparer<T> where T: IEquatable<T>
{
[Pure]
public override bool Equals(T x, T y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
internal override int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
if (value == null) {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
internal override int LastIndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (value == null) {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
// If in the future this type is made sealed, change the is check to obj != null && GetType() == obj.GetType().
public override bool Equals(Object obj) =>
obj is GenericEqualityComparer<T>;
// If in the future this type is made sealed, change typeof(...) to GetType().
public override int GetHashCode() =>
typeof(GenericEqualityComparer<T>).GetHashCode();
}
[Serializable]
internal sealed class NullableEqualityComparer<T> : EqualityComparer<T?> where T : struct, IEquatable<T>
{
[Pure]
public override bool Equals(T? x, T? y) {
if (x.HasValue) {
if (y.HasValue) return x.value.Equals(y.value);
return false;
}
if (y.HasValue) return false;
return true;
}
[Pure]
public override int GetHashCode(T? obj) => obj.GetHashCode();
internal override int IndexOf(T?[] array, T? value, int startIndex, int count) {
int endIndex = startIndex + count;
if (!value.HasValue) {
for (int i = startIndex; i < endIndex; i++) {
if (!array[i].HasValue) return i;
}
}
else {
for (int i = startIndex; i < endIndex; i++) {
if (array[i].HasValue && array[i].value.Equals(value.value)) return i;
}
}
return -1;
}
internal override int LastIndexOf(T?[] array, T? value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (!value.HasValue) {
for (int i = startIndex; i >= endIndex; i--) {
if (!array[i].HasValue) return i;
}
}
else {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i].HasValue && array[i].value.Equals(value.value)) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
internal sealed class ObjectEqualityComparer<T>: EqualityComparer<T>
{
[Pure]
public override bool Equals(T x, T y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
internal override int IndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex + count;
if (value == null) {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i < endIndex; i++) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
internal override int LastIndexOf(T[] array, T value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
if (value == null) {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] == null) return i;
}
}
else {
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
#if FEATURE_CORECLR
// NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...>
// As the randomized string hashing is turned on by default on coreclr, we need to keep the performance not affected
// as much as possible in the main stream scenarios like Dictionary<string,>
// We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which
// keep the perofrmance not affected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing GenericEqualityComparer<string>
internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer<string> {
static IEqualityComparer<string> s_nonRandomizedComparer;
internal static new IEqualityComparer<string> Default {
get {
if (s_nonRandomizedComparer == null) {
s_nonRandomizedComparer = new NonRandomizedStringEqualityComparer();
}
return s_nonRandomizedComparer;
}
}
[Pure]
public override int GetHashCode(string obj) {
if (obj == null) return 0;
return obj.GetLegacyNonRandomizedHashCode();
}
}
#endif // FEATURE_CORECLR
// Performance of IndexOf on byte array is very important for some scenarios.
// We will call the C runtime function memchr, which is optimized.
[Serializable]
internal sealed class ByteEqualityComparer: EqualityComparer<byte>
{
[Pure]
public override bool Equals(byte x, byte y) {
return x == y;
}
[Pure]
public override int GetHashCode(byte b) {
return b.GetHashCode();
}
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count) {
if (array==null)
throw new ArgumentNullException("array");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count"));
if (count > array.Length - startIndex)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (count == 0) return -1;
fixed (byte* pbytes = array) {
return Buffer.IndexOfByte(pbytes, value, startIndex, count);
}
}
internal override int LastIndexOf(byte[] array, byte value, int startIndex, int count) {
int endIndex = startIndex - count + 1;
for (int i = startIndex; i >= endIndex; i--) {
if (array[i] == value) return i;
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
}
[Serializable]
internal class EnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
[Pure]
public override bool Equals(T x, T y) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x);
int y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(y);
return x_final == y_final;
}
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return x_final.GetHashCode();
}
public EnumEqualityComparer() { }
// This is used by the serialization engine.
protected EnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context) {
// For back-compat we need to serialize the comparers for enums with underlying types other than int as ObjectEqualityComparer
if (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(T))) != TypeCode.Int32) {
info.SetType(typeof(ObjectEqualityComparer<T>));
}
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
internal override int IndexOf(T[] array, T value, int startIndex, int count)
{
int toFind = JitHelpers.UnsafeEnumCast(value);
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
int current = JitHelpers.UnsafeEnumCast(array[i]);
if (toFind == current) return i;
}
return -1;
}
internal override int LastIndexOf(T[] array, T value, int startIndex, int count)
{
int toFind = JitHelpers.UnsafeEnumCast(value);
int endIndex = startIndex - count + 1;
for (int i = startIndex; i >= endIndex; i--)
{
int current = JitHelpers.UnsafeEnumCast(array[i]);
if (toFind == current) return i;
}
return -1;
}
}
[Serializable]
internal sealed class SByteEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
{
public SByteEnumEqualityComparer() { }
// This is used by the serialization engine.
public SByteEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return ((sbyte)x_final).GetHashCode();
}
}
[Serializable]
internal sealed class ShortEnumEqualityComparer<T> : EnumEqualityComparer<T>, ISerializable where T : struct
{
public ShortEnumEqualityComparer() { }
// This is used by the serialization engine.
public ShortEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[Pure]
public override int GetHashCode(T obj) {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return ((short)x_final).GetHashCode();
}
}
[Serializable]
internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T>, ISerializable where T : struct
{
[Pure]
public override bool Equals(T x, T y) {
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x);
long y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(y);
return x_final == y_final;
}
[Pure]
public override int GetHashCode(T obj) {
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj);
return x_final.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) =>
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
GetType().GetHashCode();
public LongEnumEqualityComparer() { }
// This is used by the serialization engine.
public LongEnumEqualityComparer(SerializationInfo information, StreamingContext context) { }
[SecurityCritical]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// The LongEnumEqualityComparer does not exist on 4.0 so we need to serialize this comparer as ObjectEqualityComparer
// to allow for roundtrip between 4.0 and 4.5.
info.SetType(typeof(ObjectEqualityComparer<T>));
}
internal override int IndexOf(T[] array, T value, int startIndex, int count)
{
long toFind = JitHelpers.UnsafeEnumCastLong(value);
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
long current = JitHelpers.UnsafeEnumCastLong(array[i]);
if (toFind == current) return i;
}
return -1;
}
internal override int LastIndexOf(T[] array, T value, int startIndex, int count)
{
long toFind = JitHelpers.UnsafeEnumCastLong(value);
int endIndex = startIndex - count + 1;
for (int i = startIndex; i >= endIndex; i--)
{
long current = JitHelpers.UnsafeEnumCastLong(array[i]);
if (toFind == current) return i;
}
return -1;
}
}
#if FEATURE_RANDOMIZED_STRING_HASHING
// This type is not serializeable by design. It does not exist in previous versions and will be removed
// Once we move the framework to using secure hashing by default.
internal sealed class RandomizedStringEqualityComparer : IEqualityComparer<String>, IEqualityComparer, IWellKnownStringEqualityComparer
{
private long _entropy;
public RandomizedStringEqualityComparer() {
_entropy = HashHelpers.GetEntropy();
}
public new bool Equals(object x, object y) {
if (x == y) return true;
if (x == null || y == null) return false;
if ((x is string) && (y is string)) return Equals((string)x, (string)y);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
return false;
}
[Pure]
public bool Equals(string x, string y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
[SecuritySafeCritical]
public int GetHashCode(String obj) {
if(obj == null) return 0;
return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
}
[Pure]
[SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
string sObj = obj as string;
if(sObj != null) return String.InternalMarvin32HashString(sObj, sObj.Length, _entropy);
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj) {
RandomizedStringEqualityComparer comparer = obj as RandomizedStringEqualityComparer;
return (comparer != null) && (this._entropy == comparer._entropy);
}
public override int GetHashCode() {
return (this.GetType().GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new RandomizedStringEqualityComparer();
}
// We want to serialize the old comparer.
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return EqualityComparer<string>.Default;
}
}
// This type is not serializeable by design. It does not exist in previous versions and will be removed
// Once we move the framework to using secure hashing by default.
internal sealed class RandomizedObjectEqualityComparer : IEqualityComparer, IWellKnownStringEqualityComparer
{
private long _entropy;
public RandomizedObjectEqualityComparer() {
_entropy = HashHelpers.GetEntropy();
}
[Pure]
public new bool Equals(Object x, Object y) {
if (x != null) {
if (y != null) return x.Equals(y);
return false;
}
if (y != null) return false;
return true;
}
[Pure]
[SecuritySafeCritical]
public int GetHashCode(Object obj) {
if(obj == null) return 0;
string sObj = obj as string;
if(sObj != null) return String.InternalMarvin32HashString(sObj, sObj.Length, _entropy);
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
RandomizedObjectEqualityComparer comparer = obj as RandomizedObjectEqualityComparer;
return (comparer != null) && (this._entropy == comparer._entropy);
}
public override int GetHashCode() {
return (this.GetType().GetHashCode() ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new RandomizedObjectEqualityComparer();
}
// We want to serialize the old comparer, which in this case was null.
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return null;
}
}
#endif
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
namespace System.Collections.Immutable
{
/// <summary>
/// An interface that describes the methods that the ImmutableList and ImmutableList+Builder types have in common.
/// </summary>
/// <typeparam name="T">The type of element in the collection.</typeparam>
internal interface IImmutableListQueries<T> : IReadOnlyList<T>
{
/// <summary>
/// Converts the elements in the current ImmutableList<T> to
/// another type, and returns a list containing the converted elements.
/// </summary>
/// <param name="converter">
/// A System.Converter<TInput,TOutput> delegate that converts each element from
/// one type to another type.
/// </param>
/// <typeparam name="TOutput">
/// The type of the elements of the target array.
/// </typeparam>
/// <returns>
/// A ImmutableList<T> of the target type containing the converted
/// elements from the current ImmutableList<T>.
/// </returns>
ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter);
/// <summary>
/// Performs the specified action on each element of the list.
/// </summary>
/// <param name="action">The System.Action<T> delegate to perform on each element of the list.</param>
void ForEach(Action<T> action);
/// <summary>
/// Creates a shallow copy of a range of elements in the source ImmutableList<T>.
/// </summary>
/// <param name="index">
/// The zero-based ImmutableList<T> index at which the range
/// starts.
/// </param>
/// <param name="count">
/// The number of elements in the range.
/// </param>
/// <returns>
/// A shallow copy of a range of elements in the source ImmutableList<T>.
/// </returns>
ImmutableList<T> GetRange(int index, int count);
/// <summary>
/// Copies the entire ImmutableList<T> to a compatible one-dimensional
/// array, starting at the beginning of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional System.Array that is the destination of the elements
/// copied from ImmutableList<T>. The System.Array must have
/// zero-based indexing.
/// </param>
void CopyTo(T[] array);
/// <summary>
/// Copies the entire ImmutableList<T> to a compatible one-dimensional
/// array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional System.Array that is the destination of the elements
/// copied from ImmutableList<T>. The System.Array must have
/// zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in array at which copying begins.
/// </param>
void CopyTo(T[] array, int arrayIndex);
/// <summary>
/// Copies a range of elements from the ImmutableList<T> to
/// a compatible one-dimensional array, starting at the specified index of the
/// target array.
/// </summary>
/// <param name="index">
/// The zero-based index in the source ImmutableList<T> at
/// which copying begins.
/// </param>
/// <param name="array">
/// The one-dimensional System.Array that is the destination of the elements
/// copied from ImmutableList<T>. The System.Array must have
/// zero-based indexing.
/// </param>
/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
/// <param name="count">The number of elements to copy.</param>
void CopyTo(int index, T[] array, int arrayIndex, int count);
/// <summary>
/// Determines whether the ImmutableList<T> contains elements
/// that match the conditions defined by the specified predicate.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the elements
/// to search for.
/// </param>
/// <returns>
/// true if the ImmutableList<T> contains one or more elements
/// that match the conditions defined by the specified predicate; otherwise,
/// false.
/// </returns>
bool Exists(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the first occurrence within the entire ImmutableList<T>.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The first element that matches the conditions defined by the specified predicate,
/// if found; otherwise, the default value for type T.
/// </returns>
T Find(Predicate<T> match);
/// <summary>
/// Retrieves all the elements that match the conditions defined by the specified
/// predicate.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the elements
/// to search for.
/// </param>
/// <returns>
/// A ImmutableList<T> containing all the elements that match
/// the conditions defined by the specified predicate, if found; otherwise, an
/// empty ImmutableList<T>.
/// </returns>
ImmutableList<T> FindAll(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the first occurrence within
/// the entire ImmutableList<T>.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the
/// conditions defined by match, if found; otherwise, -1.
/// </returns>
int FindIndex(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the first occurrence within
/// the range of elements in the ImmutableList<T> that extends
/// from the specified index to the last element.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the search.</param>
/// <param name="match">The System.Predicate<T> delegate that defines the conditions of the element to search for.</param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the
/// conditions defined by match, if found; otherwise, -1.
/// </returns>
int FindIndex(int startIndex, Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the first occurrence within
/// the range of elements in the ImmutableList<T> that starts
/// at the specified index and contains the specified number of elements.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the search.</param>
/// <param name="count">The number of elements in the section to search.</param>
/// <param name="match">The System.Predicate<T> delegate that defines the conditions of the element to search for.</param>
/// <returns>
/// The zero-based index of the first occurrence of an element that matches the
/// conditions defined by match, if found; otherwise, -1.
/// </returns>
int FindIndex(int startIndex, int count, Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the last occurrence within the entire ImmutableList<T>.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The last element that matches the conditions defined by the specified predicate,
/// if found; otherwise, the default value for type T.
/// </returns>
T FindLast(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the last occurrence within
/// the entire ImmutableList<T>.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of an element that matches the
/// conditions defined by match, if found; otherwise, -1.
/// </returns>
int FindLastIndex(Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the last occurrence within
/// the range of elements in the ImmutableList<T> that extends
/// from the first element to the specified index.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the backward search.</param>
/// <param name="match">The System.Predicate<T> delegate that defines the conditions of the element
/// to search for.</param>
/// <returns>
/// The zero-based index of the last occurrence of an element that matches the
/// conditions defined by match, if found; otherwise, -1.
/// </returns>
int FindLastIndex(int startIndex, Predicate<T> match);
/// <summary>
/// Searches for an element that matches the conditions defined by the specified
/// predicate, and returns the zero-based index of the last occurrence within
/// the range of elements in the ImmutableList<T> that contains
/// the specified number of elements and ends at the specified index.
/// </summary>
/// <param name="startIndex">The zero-based starting index of the backward search.</param>
/// <param name="count">The number of elements in the section to search.</param>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions of the element
/// to search for.
/// </param>
/// <returns>
/// The zero-based index of the last occurrence of an element that matches the
/// conditions defined by match, if found; otherwise, -1.
/// </returns>
int FindLastIndex(int startIndex, int count, Predicate<T> match);
/// <summary>
/// Determines whether every element in the ImmutableList<T>
/// matches the conditions defined by the specified predicate.
/// </summary>
/// <param name="match">
/// The System.Predicate<T> delegate that defines the conditions to check against
/// the elements.
/// </param>
/// <returns>
/// true if every element in the ImmutableList<T> matches the
/// conditions defined by the specified predicate; otherwise, false. If the list
/// has no elements, the return value is true.
/// </returns>
bool TrueForAll(Predicate<T> match);
/// <summary>
/// Searches the entire sorted System.Collections.Generic.List<T> for an element
/// using the default comparer and returns the zero-based index of the element.
/// </summary>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <returns>
/// The zero-based index of item in the sorted System.Collections.Generic.List<T>,
/// if item is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than item or, if there is
/// no larger element, the bitwise complement of System.Collections.Generic.List<T>.Count.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The default comparer System.Collections.Generic.Comparer<T>.Default cannot
/// find an implementation of the System.IComparable<T> generic interface or
/// the System.IComparable interface for type T.
/// </exception>
int BinarySearch(T item);
/// <summary>
/// Searches the entire sorted System.Collections.Generic.List<T> for an element
/// using the specified comparer and returns the zero-based index of the element.
/// </summary>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">
/// The System.Collections.Generic.IComparer<T> implementation to use when comparing
/// elements.-or-null to use the default comparer System.Collections.Generic.Comparer<T>.Default.
/// </param>
/// <returns>
/// The zero-based index of item in the sorted System.Collections.Generic.List<T>,
/// if item is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than item or, if there is
/// no larger element, the bitwise complement of System.Collections.Generic.List<T>.Count.
/// </returns>
/// <exception cref="InvalidOperationException">
/// comparer is null, and the default comparer System.Collections.Generic.Comparer<T>.Default
/// cannot find an implementation of the System.IComparable<T> generic interface
/// or the System.IComparable interface for type T.
/// </exception>
int BinarySearch(T item, IComparer<T> comparer);
/// <summary>
/// Searches a range of elements in the sorted System.Collections.Generic.List<T>
/// for an element using the specified comparer and returns the zero-based index
/// of the element.
/// </summary>
/// <param name="index">The zero-based starting index of the range to search.</param>
/// <param name="count"> The length of the range to search.</param>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <param name="comparer">
/// The System.Collections.Generic.IComparer<T> implementation to use when comparing
/// elements, or null to use the default comparer System.Collections.Generic.Comparer<T>.Default.
/// </param>
/// <returns>
/// The zero-based index of item in the sorted System.Collections.Generic.List<T>,
/// if item is found; otherwise, a negative number that is the bitwise complement
/// of the index of the next element that is larger than item or, if there is
/// no larger element, the bitwise complement of System.Collections.Generic.List<T>.Count.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// index is less than 0.-or-count is less than 0.
/// </exception>
/// <exception cref="ArgumentException">
/// index and count do not denote a valid range in the System.Collections.Generic.List<T>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// comparer is null, and the default comparer System.Collections.Generic.Comparer<T>.Default
/// cannot find an implementation of the System.IComparable<T> generic interface
/// or the System.IComparable interface for type T.
/// </exception>
int BinarySearch(int index, int count, T item, IComparer<T> comparer);
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDegradedBlobsSpectraS3Request : Ds3Request
{
private string _blobId;
public string BlobId
{
get { return _blobId; }
set { WithBlobId(value); }
}
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _persistenceRuleId;
public string PersistenceRuleId
{
get { return _persistenceRuleId; }
set { WithPersistenceRuleId(value); }
}
private string _replicationRuleId;
public string ReplicationRuleId
{
get { return _replicationRuleId; }
set { WithReplicationRuleId(value); }
}
public GetDegradedBlobsSpectraS3Request WithBlobId(Guid? blobId)
{
this._blobId = blobId.ToString();
if (blobId != null)
{
this.QueryParams.Add("blob_id", blobId.ToString());
}
else
{
this.QueryParams.Remove("blob_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithBlobId(string blobId)
{
this._blobId = blobId;
if (blobId != null)
{
this.QueryParams.Add("blob_id", blobId);
}
else
{
this.QueryParams.Remove("blob_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPersistenceRuleId(Guid? persistenceRuleId)
{
this._persistenceRuleId = persistenceRuleId.ToString();
if (persistenceRuleId != null)
{
this.QueryParams.Add("persistence_rule_id", persistenceRuleId.ToString());
}
else
{
this.QueryParams.Remove("persistence_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithPersistenceRuleId(string persistenceRuleId)
{
this._persistenceRuleId = persistenceRuleId;
if (persistenceRuleId != null)
{
this.QueryParams.Add("persistence_rule_id", persistenceRuleId);
}
else
{
this.QueryParams.Remove("persistence_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithReplicationRuleId(Guid? replicationRuleId)
{
this._replicationRuleId = replicationRuleId.ToString();
if (replicationRuleId != null)
{
this.QueryParams.Add("replication_rule_id", replicationRuleId.ToString());
}
else
{
this.QueryParams.Remove("replication_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request WithReplicationRuleId(string replicationRuleId)
{
this._replicationRuleId = replicationRuleId;
if (replicationRuleId != null)
{
this.QueryParams.Add("replication_rule_id", replicationRuleId);
}
else
{
this.QueryParams.Remove("replication_rule_id");
}
return this;
}
public GetDegradedBlobsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/degraded_blob";
}
}
}
}
| |
/* ****************************************************************************
*
* 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 !CLR2
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation.Language;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Management.Automation.Interpreter
{
internal sealed class InterpretedFrame
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ThreadLocal<InterpretedFrame> CurrentFrame = new ThreadLocal<InterpretedFrame>();
internal readonly Interpreter Interpreter;
internal InterpretedFrame _parent;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
private int[] _continuations;
private int _continuationIndex;
private int _pendingContinuation;
private object _pendingValue;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public readonly object[] Data;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public readonly StrongBox<object>[] Closure;
public int StackIndex;
public int InstructionIndex;
// When a ThreadAbortException is raised from interpreted code this is the first frame that caught it.
// No handlers within this handler re-abort the current thread when left.
public ExceptionHandler CurrentAbortHandler;
internal InterpretedFrame(Interpreter interpreter, StrongBox<object>[] closure)
{
Interpreter = interpreter;
StackIndex = interpreter.LocalCount;
Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth];
int c = interpreter.Instructions.MaxContinuationDepth;
if (c > 0)
{
_continuations = new int[c];
}
Closure = closure;
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
}
public DebugInfo GetDebugInfo(int instructionIndex)
{
return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex);
}
public string Name
{
get { return Interpreter._name; }
}
#region Data Stack Operations
public void Push(object value)
{
Data[StackIndex++] = value;
}
public void Push(bool value)
{
Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public void Push(int value)
{
Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value);
}
public object Pop()
{
return Data[--StackIndex];
}
internal void SetStackDepth(int depth)
{
StackIndex = Interpreter.LocalCount + depth;
}
public object Peek()
{
return Data[StackIndex - 1];
}
public void Dup()
{
int i = StackIndex;
Data[i] = Data[i - 1];
StackIndex = i + 1;
}
public ExecutionContext ExecutionContext
{
get { return (ExecutionContext)Data[1]; }
}
public FunctionContext FunctionContext
{
get { return (FunctionContext)Data[0]; }
}
#endregion
#region Stack Trace
public InterpretedFrame Parent
{
get { return _parent; }
}
public static bool IsInterpretedFrame(MethodBase method)
{
// ContractUtils.RequiresNotNull(method, "method");
return method.DeclaringType == typeof(Interpreter) && method.Name == "Run";
}
/// <summary>
/// A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames.
/// This method filters out the duplicate CLR frames.
/// </summary>
public static IEnumerable<StackFrame> GroupStackFrames(IEnumerable<StackFrame> stackTrace)
{
bool inInterpretedFrame = false;
foreach (StackFrame frame in stackTrace)
{
if (InterpretedFrame.IsInterpretedFrame(frame.GetMethod()))
{
if (inInterpretedFrame)
{
continue;
}
inInterpretedFrame = true;
}
else
{
inInterpretedFrame = false;
}
yield return frame;
}
}
public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo()
{
var frame = this;
do
{
yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex));
frame = frame.Parent;
} while (frame != null);
}
internal void SaveTraceToException(Exception exception)
{
if (exception.Data[typeof(InterpretedFrameInfo)] == null)
{
exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
}
}
public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception)
{
return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[];
}
#if DEBUG
internal string[] Trace
{
get
{
var trace = new List<string>();
var frame = this;
do
{
trace.Add(frame.Name);
frame = frame.Parent;
} while (frame != null);
return trace.ToArray();
}
}
#endif
internal ThreadLocal<InterpretedFrame>.StorageInfo Enter()
{
var currentFrame = InterpretedFrame.CurrentFrame.GetStorageInfo();
_parent = currentFrame.Value;
currentFrame.Value = this;
return currentFrame;
}
internal void Leave(ThreadLocal<InterpretedFrame>.StorageInfo currentFrame)
{
currentFrame.Value = _parent;
}
#endregion
#region Continuations
internal bool IsJumpHappened()
{
return _pendingContinuation >= 0;
}
public void RemoveContinuation()
{
_continuationIndex--;
}
public void PushContinuation(int continuation)
{
_continuations[_continuationIndex++] = continuation;
}
public int YieldToCurrentContinuation()
{
var target = Interpreter._labels[_continuations[_continuationIndex - 1]];
SetStackDepth(target.StackDepth);
return target.Index - InstructionIndex;
}
/// <summary>
/// Get called from the LeaveFinallyInstruction.
/// </summary>
public int YieldToPendingContinuation()
{
Debug.Assert(_pendingContinuation >= 0);
RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation];
// the current continuation might have higher priority (continuationIndex is the depth of the current continuation):
if (pendingTarget.ContinuationStackDepth < _continuationIndex)
{
RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]];
SetStackDepth(currentTarget.StackDepth);
return currentTarget.Index - InstructionIndex;
}
SetStackDepth(pendingTarget.StackDepth);
if (_pendingValue != Interpreter.NoValue)
{
Data[StackIndex - 1] = _pendingValue;
}
// Set the _pendingContinuation and _pendingValue to the default values if we finally gets to the Goto target
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
return pendingTarget.Index - InstructionIndex;
}
internal void PushPendingContinuation()
{
Push(_pendingContinuation);
Push(_pendingValue);
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
}
internal void PopPendingContinuation()
{
_pendingValue = Pop();
_pendingContinuation = (int)Pop();
}
private static MethodInfo s_goto;
private static MethodInfo s_voidGoto;
internal static MethodInfo GotoMethod
{
get { return s_goto ?? (s_goto = typeof(InterpretedFrame).GetMethod("Goto")); }
}
internal static MethodInfo VoidGotoMethod
{
get { return s_voidGoto ?? (s_voidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); }
}
public int VoidGoto(int labelIndex)
{
return Goto(labelIndex, Interpreter.NoValue, gotoExceptionHandler: false);
}
public int Goto(int labelIndex, object value, bool gotoExceptionHandler)
{
// TODO: we know this at compile time (except for compiled loop):
RuntimeLabel target = Interpreter._labels[labelIndex];
Debug.Assert(!gotoExceptionHandler || _continuationIndex == target.ContinuationStackDepth,
"When it's time to jump to the exception handler, all previous finally blocks should already be processed");
if (_continuationIndex == target.ContinuationStackDepth)
{
SetStackDepth(target.StackDepth);
if (value != Interpreter.NoValue)
{
Data[StackIndex - 1] = value;
}
return target.Index - InstructionIndex;
}
// if we are in the middle of executing jump we forget the previous target and replace it by a new one:
_pendingContinuation = labelIndex;
_pendingValue = value;
return YieldToCurrentContinuation();
}
#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.Crypto
{
using System;
using NPOI.HSSF.Record;
/**
* Used for both encrypting and decrypting BIFF8 streams. The internal
* {@link RC4} instance is renewed (re-keyed) every 1024 bytes.
*
* @author Josh Micich
*/
public class Biff8RC4
{
private const int RC4_REKEYING_INTERVAL = 1024;
private RC4 _rc4;
/**
* This field is used to keep track of when to change the {@link RC4}
* instance. The change occurs every 1024 bytes. Every byte passed over is
* counted.
*/
private int _streamPos;
private int _nextRC4BlockStart;
private int _currentKeyIndex;
private bool _shouldSkipEncryptionOnCurrentRecord;
private Biff8EncryptionKey _key;
public Biff8RC4(int InitialOffset, Biff8EncryptionKey key)
{
if (InitialOffset >= RC4_REKEYING_INTERVAL)
{
throw new Exception("InitialOffset (" + InitialOffset + ")>"
+ RC4_REKEYING_INTERVAL + " not supported yet");
}
_key = key;
_streamPos = 0;
RekeyForNextBlock();
_streamPos = InitialOffset;
for (int i = InitialOffset; i > 0; i--)
{
_rc4.Output();
}
_shouldSkipEncryptionOnCurrentRecord = false;
}
private void RekeyForNextBlock()
{
_currentKeyIndex = _streamPos / RC4_REKEYING_INTERVAL;
_rc4 = _key.CreateRC4(_currentKeyIndex);
_nextRC4BlockStart = (_currentKeyIndex + 1) * RC4_REKEYING_INTERVAL;
}
private int GetNextRC4Byte()
{
if (_streamPos >= _nextRC4BlockStart)
{
RekeyForNextBlock();
}
byte mask = _rc4.Output();
_streamPos++;
if (_shouldSkipEncryptionOnCurrentRecord)
{
return 0;
}
return mask & 0xFF;
}
public void StartRecord(int currentSid)
{
_shouldSkipEncryptionOnCurrentRecord = IsNeverEncryptedRecord(currentSid);
}
/**
* TODO: Additionally, the lbPlyPos (position_of_BOF) field of the BoundSheet8 record MUST NOT be encrypted.
*
* @return <c>true</c> if record type specified by <c>sid</c> is never encrypted
*/
private static bool IsNeverEncryptedRecord(int sid)
{
switch (sid)
{
case BOFRecord.sid:
// sheet BOFs for sure
// TODO - find out about chart BOFs
case InterfaceHdrRecord.sid:
// don't know why this record doesn't seem to get encrypted
case FilePassRecord.sid:
// this only really counts when writing because FILEPASS is read early
// UsrExcl(0x0194)
// FileLock
// RRDInfo(0x0196)
// RRDHead(0x0138)
return true;
}
return false;
}
/**
* Used when BIFF header fields (sid, size) are being Read. The internal
* {@link RC4} instance must step even when unencrypted bytes are read
*/
public void SkipTwoBytes()
{
GetNextRC4Byte();
GetNextRC4Byte();
}
public void Xor(byte[] buf, int pOffSet, int pLen)
{
int nLeftInBlock;
nLeftInBlock = _nextRC4BlockStart - _streamPos;
if (pLen <= nLeftInBlock)
{
// simple case - this read does not cross key blocks
_rc4.Encrypt(buf, pOffSet, pLen);
_streamPos += pLen;
return;
}
int offset = pOffSet;
int len = pLen;
// start by using the rest of the current block
if (len > nLeftInBlock)
{
if (nLeftInBlock > 0)
{
_rc4.Encrypt(buf, offset, nLeftInBlock);
_streamPos += nLeftInBlock;
offset += nLeftInBlock;
len -= nLeftInBlock;
}
RekeyForNextBlock();
}
// all full blocks following
while (len > RC4_REKEYING_INTERVAL)
{
_rc4.Encrypt(buf, offset, RC4_REKEYING_INTERVAL);
_streamPos += RC4_REKEYING_INTERVAL;
offset += RC4_REKEYING_INTERVAL;
len -= RC4_REKEYING_INTERVAL;
RekeyForNextBlock();
}
// finish with incomplete block
_rc4.Encrypt(buf, offset, len);
_streamPos += len;
}
public int XorByte(int rawVal)
{
int mask = GetNextRC4Byte();
return (byte)(rawVal ^ mask);
}
public int Xorshort(int rawVal)
{
int b0 = GetNextRC4Byte();
int b1 = GetNextRC4Byte();
int mask = (b1 << 8) + (b0 << 0);
return rawVal ^ mask;
}
public int XorInt(int rawVal)
{
int b0 = GetNextRC4Byte();
int b1 = GetNextRC4Byte();
int b2 = GetNextRC4Byte();
int b3 = GetNextRC4Byte();
int mask = (b3 << 24) + (b2 << 16) + (b1 << 8) + (b0 << 0);
return rawVal ^ mask;
}
public long XorLong(long rawVal)
{
int b0 = GetNextRC4Byte();
int b1 = GetNextRC4Byte();
int b2 = GetNextRC4Byte();
int b3 = GetNextRC4Byte();
int b4 = GetNextRC4Byte();
int b5 = GetNextRC4Byte();
int b6 = GetNextRC4Byte();
int b7 = GetNextRC4Byte();
long mask =
(((long)b7) << 56)
+ (((long)b6) << 48)
+ (((long)b5) << 40)
+ (((long)b4) << 32)
+ (((long)b3) << 24)
+ (b2 << 16)
+ (b1 << 8)
+ (b0 << 0);
return rawVal ^ mask;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
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;
using System.Runtime;
#if OUYA
using Ouya.Console.Api;
#endif
namespace Monocle
{
public enum GameTags { Player = 0, Door, Solid, Item, Enemy, Npc, Heavy, Mechanical, BlockSolid };
public class Engine : Game
{
public const float FRAME_RATE = 60f;
static private readonly TimeSpan SixtyDelta = TimeSpan.FromSeconds(1.0 / FRAME_RATE);
private const float FULL_DELTA = 1f / 60f;
private const float CLAMP_ADD = FULL_DELTA * .25f;
static public Engine Instance { get; private set; }
static internal int TagAmount = Enum.GetNames(typeof(GameTags)).Length;
static public float TimeMult { get; private set; }
static public float LastTimeMult { get; private set; }
static public float DeltaTime { get; private set; }
static public float ActualDeltaTime { get; private set; }
static public float TimeRate = 1f;
#if OUYA
static public OuyaFacade OuyaFacade;
#endif
public GraphicsDeviceManager Graphics { get; private set; }
public Screen Screen { get; private set; }
private Scene scene;
private Scene nextScene;
private string windowTitle;
#if DEBUG
#if DESKTOP
public Commands Commands { get; private set; }
#elif OUYA
public string FrameRateDisplay { get; private set; }
#endif
private TimeSpan counterElapsed = TimeSpan.Zero;
private int counterFrames = 0;
#endif
public Engine(int width, int height, float scale, string windowTitle)
{
this.windowTitle = windowTitle;
Instance = this;
Graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = Calc.LOADPATH + "Content";
IsMouseVisible = false;
Screen = new Screen(this, width, height, scale);
#if DESKTOP
IsFixedTimeStep = false;
#elif OUYA
IsFixedTimeStep = false;
#endif
TargetElapsedTime = TimeSpan.FromSeconds(1.0 / FRAME_RATE);
//GCSettings.LatencyMode = GCLatencyMode.LowLatency;
}
protected override void Initialize()
{
base.Initialize();
#if DEBUG
#if DESKTOP
Commands = new Commands();
#elif OUYA
FrameRateDisplay = "";
#endif
#endif
Music.Initialize();
Input.Initialize();
Screen.Initialize();
Monocle.Draw.Init(GraphicsDevice);
Graphics.DeviceReset += OnGraphicsReset;
#if DESKTOP
Window.Title = windowTitle;
#endif
}
private void OnGraphicsReset(object sender, EventArgs e)
{
if (scene != null)
scene.HandleGraphicsReset();
if (nextScene != null)
nextScene.HandleGraphicsReset();
}
protected override void Update(GameTime gameTime)
{
//Calculate delta time stuff
LastTimeMult = TimeMult;
ActualDeltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds * TimeRate;
if (IsFixedTimeStep)
{
TimeMult = (60f / FRAME_RATE) * TimeRate;
DeltaTime = (1f / FRAME_RATE) * TimeRate;
}
else
{
DeltaTime = MathHelper.Clamp(
ActualDeltaTime,
FULL_DELTA * TimeRate - CLAMP_ADD,
FULL_DELTA * TimeRate + CLAMP_ADD
);
TimeMult = DeltaTime / FULL_DELTA;
}
#if DEBUG && DESKTOP
if (Commands.Open)
Input.UpdateNoKeyboard();
else
Input.Update();
#else
Input.Update();
#endif
Music.Update();
if (scene != null && scene.Active)
scene.Update();
#if DEBUG && DESKTOP
if (Commands.Open)
Commands.UpdateOpen();
else
Commands.UpdateClosed();
#endif
if (scene != nextScene)
{
if (scene != null)
scene.End();
scene = nextScene;
OnSceneTransition();
if (scene != null)
scene.Begin();
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.SetRenderTarget(Screen.RenderTarget);
GraphicsDevice.Clear(Screen.ClearColor);
if (scene != null)
scene.Render();
//if (scene != null)
// scene.PostRender();
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Black);
Screen.Render();
//if (scene != null)
// scene.PostScreen();
base.Draw(gameTime);
#if DEBUG
#if DESKTOP
//Debug console
if (Commands.Open)
Commands.Render();
//Frame counter
counterFrames++;
counterElapsed += gameTime.ElapsedGameTime;
if (counterElapsed > TimeSpan.FromSeconds(1))
{
Window.Title = windowTitle + " " + counterFrames.ToString() + " fps - " + (GC.GetTotalMemory(true) / 1048576f).ToString("F") + " MB";
counterFrames = 0;
counterElapsed -= TimeSpan.FromSeconds(1);
}
#elif OUYA
//Frame counter
counterFrames++;
counterElapsed += gameTime.ElapsedGameTime;
if (counterElapsed > TimeSpan.FromSeconds(1))
{
FrameRateDisplay = counterFrames.ToString() + " fps";
counterFrames = 0;
counterElapsed -= TimeSpan.FromSeconds(1);
}
if (FrameRateDisplay != "")
{
Monocle.Draw.SpriteBatch.Begin();
Monocle.Draw.TextJustify(Monocle.Draw.DefaultFont, FrameRateDisplay, new Vector2(4, 4), Color.White, Vector2.Zero);
Monocle.Draw.SpriteBatch.End();
}
#endif
#endif
}
public Scene Scene
{
get { return scene; }
set { nextScene = value; }
}
protected virtual void OnSceneTransition()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
protected override void OnExiting(object sender, EventArgs args)
{
Audio.Stop();
Music.Stop();
base.OnExiting(sender, args);
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Represents a dynamically loaded unmanaged library in a (partially) platform independent manner.
/// First, the native library is loaded using dlopen (on Unix systems) or using LoadLibrary (on Windows).
/// dlsym or GetProcAddress are then used to obtain symbol addresses. <c>Marshal.GetDelegateForFunctionPointer</c>
/// transforms the addresses into delegates to native methods.
/// See http://stackoverflow.com/questions/13461989/p-invoke-to-dynamically-loaded-library-on-mono.
/// </summary>
internal class UnmanagedLibrary
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<UnmanagedLibrary>();
// flags for dlopen
const int RTLD_LAZY = 1;
const int RTLD_GLOBAL = 8;
readonly string libraryPath;
readonly IntPtr handle;
public UnmanagedLibrary(string[] libraryPathAlternatives)
{
this.libraryPath = FirstValidLibraryPath(libraryPathAlternatives);
Logger.Debug("Attempting to load native library \"{0}\"", this.libraryPath);
this.handle = PlatformSpecificLoadLibrary(this.libraryPath, out string loadLibraryErrorDetail);
if (this.handle == IntPtr.Zero)
{
throw new IOException(string.Format("Error loading native library \"{0}\". {1}",
this.libraryPath, loadLibraryErrorDetail));
}
}
/// <summary>
/// Loads symbol in a platform specific way.
/// </summary>
/// <param name="symbolName"></param>
/// <returns></returns>
private IntPtr LoadSymbol(string symbolName)
{
if (PlatformApis.IsWindows)
{
// See http://stackoverflow.com/questions/10473310 for background on this.
if (PlatformApis.Is64Bit)
{
return Windows.GetProcAddress(this.handle, symbolName);
}
else
{
// Yes, we could potentially predict the size... but it's a lot simpler to just try
// all the candidates. Most functions have a suffix of @0, @4 or @8 so we won't be trying
// many options - and if it takes a little bit longer to fail if we've really got the wrong
// library, that's not a big problem. This is only called once per function in the native library.
symbolName = "_" + symbolName + "@";
for (int stackSize = 0; stackSize < 128; stackSize += 4)
{
IntPtr candidate = Windows.GetProcAddress(this.handle, symbolName + stackSize);
if (candidate != IntPtr.Zero)
{
return candidate;
}
}
// Fail.
return IntPtr.Zero;
}
}
if (PlatformApis.IsLinux)
{
if (PlatformApis.IsMono)
{
return Mono.dlsym(this.handle, symbolName);
}
if (PlatformApis.IsNetCore)
{
return CoreCLR.dlsym(this.handle, symbolName);
}
return Linux.dlsym(this.handle, symbolName);
}
if (PlatformApis.IsMacOSX)
{
return MacOSX.dlsym(this.handle, symbolName);
}
throw new InvalidOperationException("Unsupported platform.");
}
public T GetNativeMethodDelegate<T>(string methodName)
where T : class
{
var ptr = LoadSymbol(methodName);
if (ptr == IntPtr.Zero)
{
throw new MissingMethodException(string.Format("The native method \"{0}\" does not exist", methodName));
}
#if NETSTANDARD1_5
return Marshal.GetDelegateForFunctionPointer<T>(ptr); // non-generic version is obsolete
#else
return Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T; // generic version not available in .NET45
#endif
}
/// <summary>
/// Loads library in a platform specific way.
/// </summary>
private static IntPtr PlatformSpecificLoadLibrary(string libraryPath, out string errorMsg)
{
if (PlatformApis.IsWindows)
{
// TODO(jtattermusch): populate the error on Windows
errorMsg = null;
return Windows.LoadLibrary(libraryPath);
}
if (PlatformApis.IsLinux)
{
if (PlatformApis.IsMono)
{
return LoadLibraryPosix(Mono.dlopen, Mono.dlerror, libraryPath, out errorMsg);
}
if (PlatformApis.IsNetCore)
{
return LoadLibraryPosix(CoreCLR.dlopen, CoreCLR.dlerror, libraryPath, out errorMsg);
}
return LoadLibraryPosix(Linux.dlopen, Linux.dlerror, libraryPath, out errorMsg);
}
if (PlatformApis.IsMacOSX)
{
return LoadLibraryPosix(MacOSX.dlopen, MacOSX.dlerror, libraryPath, out errorMsg);
}
throw new InvalidOperationException("Unsupported platform.");
}
private static IntPtr LoadLibraryPosix(Func<string, int, IntPtr> dlopenFunc, Func<IntPtr> dlerrorFunc, string libraryPath, out string errorMsg)
{
errorMsg = null;
IntPtr ret = dlopenFunc(libraryPath, RTLD_GLOBAL + RTLD_LAZY);
if (ret == IntPtr.Zero)
{
errorMsg = Marshal.PtrToStringAnsi(dlerrorFunc());
}
return ret;
}
private static string FirstValidLibraryPath(string[] libraryPathAlternatives)
{
GrpcPreconditions.CheckArgument(libraryPathAlternatives.Length > 0, "libraryPathAlternatives cannot be empty.");
foreach (var path in libraryPathAlternatives)
{
if (File.Exists(path))
{
return path;
}
}
throw new FileNotFoundException(
String.Format("Error loading native library. Not found in any of the possible locations: {0}",
string.Join(",", libraryPathAlternatives)));
}
private static class Windows
{
[DllImport("kernel32.dll")]
internal static extern IntPtr LoadLibrary(string filename);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
}
private static class Linux
{
[DllImport("libdl.so")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("libdl.so")]
internal static extern IntPtr dlerror();
[DllImport("libdl.so")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
private static class MacOSX
{
[DllImport("libSystem.dylib")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("libSystem.dylib")]
internal static extern IntPtr dlerror();
[DllImport("libSystem.dylib")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
/// <summary>
/// On Linux systems, using using dlopen and dlsym results in
/// DllNotFoundException("libdl.so not found") if libc6-dev
/// is not installed. As a workaround, we load symbols for
/// dlopen and dlsym from the current process as on Linux
/// Mono sure is linked against these symbols.
/// </summary>
private static class Mono
{
[DllImport("__Internal")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("__Internal")]
internal static extern IntPtr dlerror();
[DllImport("__Internal")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
/// <summary>
/// Similarly as for Mono on Linux, we load symbols for
/// dlopen and dlsym from the "libcoreclr.so",
/// to avoid the dependency on libc-dev Linux.
/// </summary>
private static class CoreCLR
{
[DllImport("libcoreclr.so")]
internal static extern IntPtr dlopen(string filename, int flags);
[DllImport("libcoreclr.so")]
internal static extern IntPtr dlerror();
[DllImport("libcoreclr.so")]
internal static extern IntPtr dlsym(IntPtr handle, string symbol);
}
}
}
| |
/* The MIT License
*
* Copyright (c) 2010 Intel Corporation.
* All rights reserved.
*
* Based on the convexdecomposition library from
* <http://codesuppository.googlecode.com> by John W. Ratcliff and Stan Melax.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace OpenSim.Region.Physics.ConvexDecompositionDotNet
{
public class Wpoint
{
public float3 mPoint;
public float mWeight;
public Wpoint(float3 p, float w)
{
mPoint = p;
mWeight = w;
}
}
public class CTri
{
private const int WSCALE = 4;
public float3 mP1;
public float3 mP2;
public float3 mP3;
public float3 mNear1;
public float3 mNear2;
public float3 mNear3;
public float3 mNormal;
public float mPlaneD;
public float mConcavity;
public float mC1;
public float mC2;
public float mC3;
public int mI1;
public int mI2;
public int mI3;
public int mProcessed; // already been added...
public CTri(float3 p1, float3 p2, float3 p3, int i1, int i2, int i3)
{
mProcessed = 0;
mI1 = i1;
mI2 = i2;
mI3 = i3;
mP1 = new float3(p1);
mP2 = new float3(p2);
mP3 = new float3(p3);
mNear1 = new float3();
mNear2 = new float3();
mNear3 = new float3();
mNormal = new float3();
mPlaneD = mNormal.ComputePlane(mP1, mP2, mP3);
}
public float Facing(CTri t)
{
return float3.dot(mNormal, t.mNormal);
}
public bool clip(float3 start, ref float3 end)
{
float3 sect = new float3();
bool hit = lineIntersectsTriangle(start, end, mP1, mP2, mP3, ref sect);
if (hit)
end = sect;
return hit;
}
public bool Concave(float3 p, ref float distance, ref float3 n)
{
n.NearestPointInTriangle(p, mP1, mP2, mP3);
distance = p.Distance(n);
return true;
}
public void addTri(int[] indices, int i1, int i2, int i3, ref int tcount)
{
indices[tcount * 3 + 0] = i1;
indices[tcount * 3 + 1] = i2;
indices[tcount * 3 + 2] = i3;
tcount++;
}
public float getVolume()
{
int[] indices = new int[8 * 3];
int tcount = 0;
addTri(indices, 0, 1, 2, ref tcount);
addTri(indices, 3, 4, 5, ref tcount);
addTri(indices, 0, 3, 4, ref tcount);
addTri(indices, 0, 4, 1, ref tcount);
addTri(indices, 1, 4, 5, ref tcount);
addTri(indices, 1, 5, 2, ref tcount);
addTri(indices, 0, 3, 5, ref tcount);
addTri(indices, 0, 5, 2, ref tcount);
List<float3> vertices = new List<float3> { mP1, mP2, mP3, mNear1, mNear2, mNear3 };
List<int> indexList = new List<int>(indices);
float v = Concavity.computeMeshVolume(vertices, indexList);
return v;
}
public float raySect(float3 p, float3 dir, ref float3 sect)
{
float4 plane = new float4();
plane.x = mNormal.x;
plane.y = mNormal.y;
plane.z = mNormal.z;
plane.w = mPlaneD;
float3 dest = p + dir * 100000f;
intersect(p, dest, ref sect, plane);
return sect.Distance(p); // return the intersection distance
}
public float planeDistance(float3 p)
{
float4 plane = new float4();
plane.x = mNormal.x;
plane.y = mNormal.y;
plane.z = mNormal.z;
plane.w = mPlaneD;
return DistToPt(p, plane);
}
public bool samePlane(CTri t)
{
const float THRESH = 0.001f;
float dd = Math.Abs(t.mPlaneD - mPlaneD);
if (dd > THRESH)
return false;
dd = Math.Abs(t.mNormal.x - mNormal.x);
if (dd > THRESH)
return false;
dd = Math.Abs(t.mNormal.y - mNormal.y);
if (dd > THRESH)
return false;
dd = Math.Abs(t.mNormal.z - mNormal.z);
if (dd > THRESH)
return false;
return true;
}
public bool hasIndex(int i)
{
if (i == mI1 || i == mI2 || i == mI3)
return true;
return false;
}
public bool sharesEdge(CTri t)
{
bool ret = false;
uint count = 0;
if (t.hasIndex(mI1))
count++;
if (t.hasIndex(mI2))
count++;
if (t.hasIndex(mI3))
count++;
if (count >= 2)
ret = true;
return ret;
}
public float area()
{
float a = mConcavity * mP1.Area(mP2, mP3);
return a;
}
public void addWeighted(List<Wpoint> list)
{
Wpoint p1 = new Wpoint(mP1, mC1);
Wpoint p2 = new Wpoint(mP2, mC2);
Wpoint p3 = new Wpoint(mP3, mC3);
float3 d1 = mNear1 - mP1;
float3 d2 = mNear2 - mP2;
float3 d3 = mNear3 - mP3;
d1 *= WSCALE;
d2 *= WSCALE;
d3 *= WSCALE;
d1 = d1 + mP1;
d2 = d2 + mP2;
d3 = d3 + mP3;
Wpoint p4 = new Wpoint(d1, mC1);
Wpoint p5 = new Wpoint(d2, mC2);
Wpoint p6 = new Wpoint(d3, mC3);
list.Add(p1);
list.Add(p2);
list.Add(p3);
list.Add(p4);
list.Add(p5);
list.Add(p6);
}
private static float DistToPt(float3 p, float4 plane)
{
float x = p.x;
float y = p.y;
float z = p.z;
float d = x*plane.x + y*plane.y + z*plane.z + plane.w;
return d;
}
private static void intersect(float3 p1, float3 p2, ref float3 split, float4 plane)
{
float dp1 = DistToPt(p1, plane);
float3 dir = new float3();
dir.x = p2[0] - p1[0];
dir.y = p2[1] - p1[1];
dir.z = p2[2] - p1[2];
float dot1 = dir[0] * plane[0] + dir[1] * plane[1] + dir[2] * plane[2];
float dot2 = dp1 - plane[3];
float t = -(plane[3] + dot2) / dot1;
split.x = (dir[0] * t) + p1[0];
split.y = (dir[1] * t) + p1[1];
split.z = (dir[2] * t) + p1[2];
}
private static bool rayIntersectsTriangle(float3 p, float3 d, float3 v0, float3 v1, float3 v2, out float t)
{
t = 0f;
float3 e1, e2, h, s, q;
float a, f, u, v;
e1 = v1 - v0;
e2 = v2 - v0;
h = float3.cross(d, e2);
a = float3.dot(e1, h);
if (a > -0.00001f && a < 0.00001f)
return false;
f = 1f / a;
s = p - v0;
u = f * float3.dot(s, h);
if (u < 0.0f || u > 1.0f)
return false;
q = float3.cross(s, e1);
v = f * float3.dot(d, q);
if (v < 0.0f || u + v > 1.0f)
return false;
// at this stage we can compute t to find out where
// the intersection point is on the line
t = f * float3.dot(e2, q);
if (t > 0f) // ray intersection
return true;
else // this means that there is a line intersection but not a ray intersection
return false;
}
private static bool lineIntersectsTriangle(float3 rayStart, float3 rayEnd, float3 p1, float3 p2, float3 p3, ref float3 sect)
{
float3 dir = rayEnd - rayStart;
float d = (float)Math.Sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
float r = 1.0f / d;
dir *= r;
float t;
bool ret = rayIntersectsTriangle(rayStart, dir, p1, p2, p3, out t);
if (ret)
{
if (t > d)
{
sect.x = rayStart.x + dir.x * t;
sect.y = rayStart.y + dir.y * t;
sect.z = rayStart.z + dir.z * t;
}
else
{
ret = false;
}
}
return ret;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class VoxelModifyTerrain : MonoBehaviour
{
GameObject cameraGO;
private GameObject player;
private ChunkManager chunkManager;
private Vector3 lastPlayerPosition;
public VoxelWorld world;
public Region myRegion = null;
public int distToLoad = 4;
public int initialDistToLoad = 8;
public bool saveLevel = false;
private bool chunksLoaded = false;
void Awake ()
{
cameraGO = GameObject.FindGameObjectWithTag ("MainCamera");
player = GameObject.FindGameObjectWithTag ("Player");
lastPlayerPosition = player.transform.position;
GameObject chunkManagerGO = GameObject.Find ("Chunk Manager");
chunkManager = chunkManagerGO.GetComponent<ChunkManager> ();
}
public void setStartRegion (Region region)
{
myRegion = region;
}
private void determinePlayerRegion (Vector3 playerPos)
{
if (playerPos.x >= myRegion.getBlockOffsetX () + myRegion.regionXZ &&
playerPos.z < myRegion.getBlockOffsetZ () + myRegion.regionXZ) {
myRegion = world.getRegionAtIndex (myRegion.offsetX + 1, myRegion.offsetY, myRegion.offsetZ);
world.changeFocusRegion (myRegion);
} else if (playerPos.z >= myRegion.getBlockOffsetZ () + myRegion.regionXZ &&
playerPos.x < myRegion.getBlockOffsetX () + myRegion.regionXZ) {
myRegion = world.getRegionAtIndex (myRegion.offsetX, myRegion.offsetY, myRegion.offsetZ + 1);
world.changeFocusRegion (myRegion);
} else if (playerPos.x < myRegion.getBlockOffsetX () &&
playerPos.z >= myRegion.getBlockOffsetZ ()) {
myRegion = world.getRegionAtIndex (myRegion.offsetX - 1, myRegion.offsetY, myRegion.offsetZ);
world.changeFocusRegion (myRegion);
} else if (playerPos.z < myRegion.getBlockOffsetZ () &&
playerPos.x >= myRegion.getBlockOffsetX ()) {
myRegion = world.getRegionAtIndex (myRegion.offsetX, myRegion.offsetY, myRegion.offsetZ - 1);
world.changeFocusRegion (myRegion);
}
}
private void MoveChunks (Vector3 playerPos)
{
int newChunkx = Mathf.FloorToInt (playerPos.x) / Chunk.chunkSize;
int newChunky = Mathf.FloorToInt (playerPos.y) / Chunk.chunkSize;
int newChunkz = Mathf.FloorToInt (playerPos.z) / Chunk.chunkSize;
int oldChunkx = Mathf.FloorToInt (lastPlayerPosition.x) / Chunk.chunkSize;
int oldChunky = Mathf.FloorToInt (lastPlayerPosition.y) / Chunk.chunkSize;
int oldChunkz = Mathf.FloorToInt (lastPlayerPosition.z) / Chunk.chunkSize;
int chunkChangeX = newChunkx - oldChunkx;
int chunkChangeY = newChunky - oldChunky;
int chunkChangeZ = newChunkz - oldChunkz;
if (chunkChangeX == 0 && chunkChangeY == 0 && chunkChangeZ == 0) {
return;
}
int xLoadStart = 0;
int x_end = 0;
if (chunkChangeX == 0) {
xLoadStart = newChunkx - distToLoad;
x_end = newChunkx + distToLoad;
} else if (chunkChangeX > 0) {
xLoadStart = oldChunkx + distToLoad;
x_end = newChunkx + distToLoad;
} else {
xLoadStart = newChunkx - distToLoad;
x_end = oldChunkx - distToLoad;
}
int yLoadStart = 0;
int y_end = 0;
if (chunkChangeY == 0) {
yLoadStart = newChunky - distToLoad;
y_end = newChunky + distToLoad;
} else if (chunkChangeY > 0) {
yLoadStart = oldChunky + distToLoad;
y_end = newChunky + distToLoad;
} else {
yLoadStart = newChunky - distToLoad;
y_end = oldChunky - distToLoad;
}
if (yLoadStart < 0) {
yLoadStart = 0;
}
if (y_end < 0) {
y_end = 0;
}
int zLoadStart = 0;
int z_end = 0;
if (chunkChangeZ == 0) {
zLoadStart = newChunkz - distToLoad;
z_end = newChunkz + distToLoad;
} else if (chunkChangeZ > 0) {
zLoadStart = oldChunkz + distToLoad;
z_end = newChunkz + distToLoad;
} else {
zLoadStart = newChunkz - distToLoad;
z_end = oldChunkz - distToLoad;
}
LinkedList<Region> loadedRegions = new LinkedList<Region> ();
for (int x = xLoadStart; x < x_end; x++) {
for (int z = zLoadStart; z < z_end; z++) {
for (int y = yLoadStart; y < y_end; y++) {
Region region = world.getRegionAtCoords (x * Chunk.chunkSize, y * Chunk.chunkSize, z * Chunk.chunkSize);
int[] localCoords = region.convertWorldChunksToLocal (x, y, z);
region.loadChunk (localCoords [0], localCoords [1], localCoords [2]);
if (!loadedRegions.Contains (region)) {
loadedRegions.AddLast (region);
}
}
}
}
foreach (Region region in loadedRegions) {
world.loadAllNeighbors (region, true);
}
}
private void LoadChunks (Vector3 playerPos)
{
int playerChunkx = (Mathf.FloorToInt (playerPos.x)) / Chunk.chunkSize;
int playerChunky = (Mathf.FloorToInt (playerPos.y)) / Chunk.chunkSize;
int playerChunkz = (Mathf.FloorToInt (playerPos.z)) / Chunk.chunkSize;
int xLoadStart = playerChunkx - initialDistToLoad;
int xLoadFinish = playerChunkx + initialDistToLoad;
int yLoadStart = playerChunky - initialDistToLoad;
int yLoadFinish = playerChunky + initialDistToLoad;
int zLoadStart = playerChunkz - initialDistToLoad;
int zLoadFinish = playerChunkz + initialDistToLoad;
if (yLoadStart < 0) {
yLoadStart = 0;
}
for (int x = xLoadStart; x < xLoadFinish; x++) {
for (int z = zLoadStart; z < zLoadFinish; z++) {
for (int y = yLoadStart; y < yLoadFinish; y++) {
Region region = world.getRegionAtCoords (x * Chunk.chunkSize, y * Chunk.chunkSize, z * Chunk.chunkSize);
if (region == null) {
XYZ coords = world.getIndexFromCoords (x * Chunk.chunkSize, y * Chunk.chunkSize, z * Chunk.chunkSize);
region = world.createRegion (coords.x, coords.y, coords.z, false);
world.loadAllNeighbors (region, true);
}
int[] localCoords = region.convertWorldChunksToLocal (x, y, z);
region.loadChunk (localCoords [0], localCoords [1], localCoords [2]);
}
}
}
}
public void ReplaceBlockCenter (float range, byte block)
{
//Replaces the block directly in front of the player
Ray ray = new Ray (cameraGO.transform.position, cameraGO.transform.forward);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
if (hit.distance < range) {
ReplaceBlockAt (hit, block);
}
}
}
public void AddBlockCenter (float range, byte block)
{
//Adds the block specified directly in front of the player
Ray ray = new Ray (cameraGO.transform.position, cameraGO.transform.forward);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
if (hit.distance < range) {
AddBlockAt (hit, block);
}
Debug.DrawLine (ray.origin, ray.origin + (ray.direction * hit.distance), Color.green, 2);
}
}
public void ReplaceBlockCursor (byte block)
{
//Replaces the block specified where the mouse cursor is pointing
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
ReplaceBlockAt (hit, block);
Debug.DrawLine (ray.origin, ray.origin + (ray.direction * hit.distance),
Color.green, 2);
}
}
public void AddBlockCursor (byte block)
{
//Adds the block specified where the mouse cursor is pointing
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit)) {
AddBlockAt (hit, block);
Debug.DrawLine (ray.origin, ray.origin + (ray.direction * hit.distance),
Color.green, 2);
}
}
public void ReplaceBlockAt (RaycastHit hit, byte block)
{
//removes a block at these impact coordinates, you can raycast against the terrain and call this with the hit.point
Vector3 position = hit.point;
position += (hit.normal * -0.5f);
//Need to reduce this position to a region local position.
SetBlockAt (position, block);
}
public void AddBlockAt (RaycastHit hit, byte block)
{
//adds the specified block at these impact coordinates, you can raycast against the terrain and call this with the hit.point
Vector3 position = hit.point;
position += (hit.normal * 0.5f);
SetBlockAt (position, block);
}
private void SetBlockAt (Vector3 position, byte block)
{
//sets the specified block at these coordinates
int x = Mathf.RoundToInt (position.x);
int y = Mathf.RoundToInt (position.y);
int z = Mathf.RoundToInt (position.z);
SetBlockAt (x, y, z, block);
}
private void SetBlockAt (int x, int y, int z, byte block)
{
//Block could be part of the neighbor region.
//adds the specified block at these coordinates
Region modRegion = world.getRegionAtCoords (x, y, z);
int[] localCoords = modRegion.convertWorldToLocal (x, y, z);
//print ("Set block at world(" + x + "," + y + "," + z + ") local(" + localCoords [0] + "," + localCoords [1] + "," + localCoords [2] + ")");
modRegion.data [localCoords [0], localCoords [1], localCoords [2]] = block;
UpdateChunkAt (modRegion, localCoords [0], localCoords [1], localCoords [2]);
}
private void UpdateChunkAt (Region region, int x, int y, int z)
{
//Updates the chunk containing this block
int updateX = Mathf.FloorToInt (x / Chunk.chunkSize);
int updateY = Mathf.FloorToInt (y / Chunk.chunkSize);
int updateZ = Mathf.FloorToInt (z / Chunk.chunkSize);
//Update the chunk's mesh
chunkManager.flagChunkForUpdate (region.chunks [updateX, updateY, updateZ]);
//region.chunks [updateX, updateY, updateZ].update = true;
//Region has changed state.
region.isDirty = true;
int chunkDim = region.regionXZ / Chunk.chunkSize;
//Neighbor chunks also may need to be re-rendered since their mesh could have
//potentially changed.
int xEdge = x - (Chunk.chunkSize * updateX);
int yEdge = y - (Chunk.chunkSize * updateY);
int zEdge = z - (Chunk.chunkSize * updateZ);
if (xEdge == 0) {
int neighborX = updateX - 1;
if (neighborX < 0) {
Region r = world.getRegionAtCoords (region.offsetX - 1, region.offsetY, region.offsetZ);
chunkManager.flagChunkForUpdate (r.chunks [neighborX + chunkDim, updateY, updateZ]);
} else {
chunkManager.flagChunkForUpdate (region.chunks [neighborX, updateY, updateZ]);
}
}
if (xEdge == Chunk.chunkSize - 1) {
int neighborX = updateX + 1;
if (neighborX >= chunkDim) {
Region r = world.getRegionAtCoords (region.offsetX + 1, region.offsetY, region.offsetZ);
chunkManager.flagChunkForUpdate (r.chunks [neighborX - chunkDim, updateY, updateZ]);
} else {
chunkManager.flagChunkForUpdate (region.chunks [neighborX, updateY, updateZ]);
}
}
if (yEdge == 0) {
int neighborY = updateY - 1;
if (neighborY < 0) {
Region r = world.getRegionAtCoords (region.offsetX, region.offsetY - 1, region.offsetZ);
chunkManager.flagChunkForUpdate (r.chunks [updateX, neighborY + chunkDim, updateZ]);
} else {
chunkManager.flagChunkForUpdate (region.chunks [updateX, neighborY, updateZ]);
}
}
if (yEdge == Chunk.chunkSize - 1) {
int neighborY = updateY + 1;
if (neighborY >= chunkDim) {
Region r = world.getRegionAtCoords (region.offsetX, region.offsetY + 1, region.offsetZ);
chunkManager.flagChunkForUpdate (r.chunks [updateX, neighborY - chunkDim, updateZ]);
} else {
chunkManager.flagChunkForUpdate (region.chunks [updateX, neighborY, updateZ]);
}
}
if (zEdge == 0) {
int neighborZ = updateZ - 1;
if (neighborZ < 0) {
Region r = world.getRegionAtCoords (region.offsetX, region.offsetY, region.offsetZ - 1);
chunkManager.flagChunkForUpdate (r.chunks [updateX, updateY, neighborZ + chunkDim]);
} else {
chunkManager.flagChunkForUpdate (region.chunks [updateX, updateY, neighborZ]);
}
}
if (zEdge == Chunk.chunkSize - 1) {
int neighborZ = updateZ + 1;
if (neighborZ >= chunkDim) {
Region r = world.getRegionAtCoords (region.offsetX, region.offsetY, region.offsetZ + 1);
chunkManager.flagChunkForUpdate (r.chunks [updateX, updateY, neighborZ - chunkDim]);
} else {
chunkManager.flagChunkForUpdate (region.chunks [updateX, updateY, neighborZ]);
}
}
}
// Update is called once per frame
void Update ()
{
if (saveLevel) {
world.saveWorld ();
saveLevel = false;
}
if (myRegion != null) {
if (!chunksLoaded) {
LoadChunks (player.transform.position);
determinePlayerRegion (player.transform.position);
lastPlayerPosition = player.transform.position;
chunksLoaded = true;
} else if (Vector3.Distance (lastPlayerPosition, player.transform.position) > 0.1f) {
determinePlayerRegion (player.transform.position);
MoveChunks (player.transform.position);
lastPlayerPosition = player.transform.position;
}
}
}
}
| |
using System.IO;
using Xunit;
using Semmle.Util.Logging;
using System.Runtime.InteropServices;
namespace Semmle.Extraction.Tests
{
internal struct TransformedPathStub : PathTransformer.ITransformedPath
{
private readonly string value;
public TransformedPathStub(string value) => this.value = value;
public string Value => value;
public string Extension => throw new System.NotImplementedException();
public string NameWithoutExtension => throw new System.NotImplementedException();
public PathTransformer.ITransformedPath ParentDirectory => throw new System.NotImplementedException();
public string DatabaseId => throw new System.NotImplementedException();
public PathTransformer.ITransformedPath WithSuffix(string suffix)
{
throw new System.NotImplementedException();
}
}
public class Layout
{
private readonly ILogger logger = new LoggerMock();
[Fact]
public void TestDefaultLayout()
{
var layout = new Semmle.Extraction.Layout(null, null, null);
var project = layout.LookupProjectOrNull(new TransformedPathStub("foo.cs"));
Assert.NotNull(project);
// All files are mapped when there's no layout file.
Assert.True(layout.FileInLayout(new TransformedPathStub("foo.cs")));
// Test trap filename
var tmpDir = Path.GetTempPath();
Directory.SetCurrentDirectory(tmpDir);
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// `Directory.SetCurrentDirectory()` seems to slightly change the path on macOS,
// so adjusting it:
Assert.NotEqual(Directory.GetCurrentDirectory(), tmpDir);
tmpDir = "/private" + tmpDir;
// Remove trailing slash:
Assert.Equal('/', tmpDir[tmpDir.Length - 1]);
tmpDir = tmpDir.Substring(0, tmpDir.Length - 1);
Assert.Equal(Directory.GetCurrentDirectory(), tmpDir);
}
var f1 = project!.GetTrapPath(logger, new TransformedPathStub("foo.cs"), TrapWriter.CompressionMode.Gzip);
var g1 = TrapWriter.NestPaths(logger, tmpDir, "foo.cs.trap.gz");
Assert.Equal(f1, g1);
// Test trap file generation
var trapwriterFilename = project.GetTrapPath(logger, new TransformedPathStub("foo.cs"), TrapWriter.CompressionMode.Gzip);
using (var trapwriter = project.CreateTrapWriter(logger, new TransformedPathStub("foo.cs"), TrapWriter.CompressionMode.Gzip, discardDuplicates: false))
{
trapwriter.Emit("1=*");
Assert.False(File.Exists(trapwriterFilename));
}
Assert.True(File.Exists(trapwriterFilename));
File.Delete(trapwriterFilename);
}
[Fact]
public void TestLayoutFile()
{
File.WriteAllLines("layout.txt", new string[]
{
"# Section",
"TRAP_FOLDER=" + Path.GetFullPath("snapshot\\trap"),
"ODASA_DB=snapshot\\db-csharp",
"SOURCE_ARCHIVE=" + Path.GetFullPath("snapshot\\archive"),
"ODASA_BUILD_ERROR_DIR=snapshot\build-errors",
"-foo.cs",
"bar.cs",
"-excluded",
"excluded/foo.cs",
"included"
});
var layout = new Semmle.Extraction.Layout(null, null, "layout.txt");
// Test general pattern matching
Assert.True(layout.FileInLayout(new TransformedPathStub("bar.cs")));
Assert.False(layout.FileInLayout(new TransformedPathStub("foo.cs")));
Assert.False(layout.FileInLayout(new TransformedPathStub("goo.cs")));
Assert.False(layout.FileInLayout(new TransformedPathStub("excluded/bar.cs")));
Assert.True(layout.FileInLayout(new TransformedPathStub("excluded/foo.cs")));
Assert.True(layout.FileInLayout(new TransformedPathStub("included/foo.cs")));
// Test the trap file
var project = layout.LookupProjectOrNull(new TransformedPathStub("bar.cs"));
Assert.NotNull(project);
var trapwriterFilename = project!.GetTrapPath(logger, new TransformedPathStub("bar.cs"), TrapWriter.CompressionMode.Gzip);
Assert.Equal(TrapWriter.NestPaths(logger, Path.GetFullPath("snapshot\\trap"), "bar.cs.trap.gz"),
trapwriterFilename);
// Test the source archive
var trapWriter = project.CreateTrapWriter(logger, new TransformedPathStub("bar.cs"), TrapWriter.CompressionMode.Gzip, discardDuplicates: false);
trapWriter.Archive("layout.txt", new TransformedPathStub("layout.txt"), System.Text.Encoding.ASCII);
var writtenFile = TrapWriter.NestPaths(logger, Path.GetFullPath("snapshot\\archive"), "layout.txt");
Assert.True(File.Exists(writtenFile));
File.Delete("layout.txt");
}
[Fact]
public void TestTrapOverridesLayout()
{
// When you specify both a trap file and a layout, use the trap file.
var layout = new Semmle.Extraction.Layout(Path.GetFullPath("snapshot\\trap"), null, "something.txt");
Assert.True(layout.FileInLayout(new TransformedPathStub("bar.cs")));
var subProject = layout.LookupProjectOrNull(new TransformedPathStub("foo.cs"));
Assert.NotNull(subProject);
var f1 = subProject!.GetTrapPath(logger, new TransformedPathStub("foo.cs"), TrapWriter.CompressionMode.Gzip);
var g1 = TrapWriter.NestPaths(logger, Path.GetFullPath("snapshot\\trap"), "foo.cs.trap.gz");
Assert.Equal(f1, g1);
}
[Fact]
public void TestMultipleSections()
{
File.WriteAllLines("layout.txt", new string[]
{
"# Section 1",
"TRAP_FOLDER=" + Path.GetFullPath("snapshot\\trap1"),
"ODASA_DB=snapshot\\db-csharp",
"SOURCE_ARCHIVE=" + Path.GetFullPath("snapshot\\archive1"),
"ODASA_BUILD_ERROR_DIR=snapshot\build-errors",
"foo.cs",
"# Section 2",
"TRAP_FOLDER=" + Path.GetFullPath("snapshot\\trap2"),
"ODASA_DB=snapshot\\db-csharp",
"SOURCE_ARCHIVE=" + Path.GetFullPath("snapshot\\archive2"),
"ODASA_BUILD_ERROR_DIR=snapshot\build-errors",
"bar.cs",
});
var layout = new Semmle.Extraction.Layout(null, null, "layout.txt");
// Use Section 2
Assert.True(layout.FileInLayout(new TransformedPathStub("bar.cs")));
var subProject = layout.LookupProjectOrNull(new TransformedPathStub("bar.cs"));
Assert.NotNull(subProject);
var f1 = subProject!.GetTrapPath(logger, new TransformedPathStub("bar.cs"), TrapWriter.CompressionMode.Gzip);
var g1 = TrapWriter.NestPaths(logger, Path.GetFullPath("snapshot\\trap2"), "bar.cs.trap.gz");
Assert.Equal(f1, g1);
// Use Section 1
Assert.True(layout.FileInLayout(new TransformedPathStub("foo.cs")));
subProject = layout.LookupProjectOrNull(new TransformedPathStub("foo.cs"));
Assert.NotNull(subProject);
var f2 = subProject!.GetTrapPath(logger, new TransformedPathStub("foo.cs"), TrapWriter.CompressionMode.Gzip);
var g2 = TrapWriter.NestPaths(logger, Path.GetFullPath("snapshot\\trap1"), "foo.cs.trap.gz");
Assert.Equal(f2, g2);
// boo.dll is not in the layout, so use layout from first section.
Assert.False(layout.FileInLayout(new TransformedPathStub("boo.dll")));
var f3 = layout.LookupProjectOrDefault(new TransformedPathStub("boo.dll")).GetTrapPath(logger, new TransformedPathStub("boo.dll"), TrapWriter.CompressionMode.Gzip);
var g3 = TrapWriter.NestPaths(logger, Path.GetFullPath("snapshot\\trap1"), "boo.dll.trap.gz");
Assert.Equal(f3, g3);
// boo.cs is not in the layout, so return null
Assert.False(layout.FileInLayout(new TransformedPathStub("boo.cs")));
Assert.Null(layout.LookupProjectOrNull(new TransformedPathStub("boo.cs")));
}
[Fact]
public void MissingLayout()
{
Assert.Throws<Extraction.Layout.InvalidLayoutException>(() =>
new Semmle.Extraction.Layout(null, null, "nosuchfile.txt"));
}
[Fact]
public void EmptyLayout()
{
File.Create("layout.txt").Close();
Assert.Throws<Extraction.Layout.InvalidLayoutException>(() =>
new Semmle.Extraction.Layout(null, null, "layout.txt"));
}
[Fact]
public void InvalidLayout()
{
File.WriteAllLines("layout.txt", new string[]
{
"# Section 1"
});
Assert.Throws<Extraction.Layout.InvalidLayoutException>(() =>
new Semmle.Extraction.Layout(null, null, "layout.txt"));
}
private sealed class LoggerMock : ILogger
{
public void Dispose() { }
public void Log(Severity s, string text) { }
}
}
internal static class TrapWriterTestExtensions
{
public static void Emit(this TrapWriter trapFile, string s)
{
trapFile.Emit(new StringTrapEmitter(s));
}
private class StringTrapEmitter : ITrapEmitter
{
private readonly string content;
public StringTrapEmitter(string content)
{
this.content = content;
}
public void EmitTrap(TextWriter trapFile)
{
trapFile.Write(content);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Common.Logging;
using prov = Candor.Configuration.Provider;
namespace Candor.Security
{
/* Configuration Example (web.config):
Don't delete other configuration, instead just merge this config into your existing configuration.
This sample will not work exactly as shown because you will need to plug in the correct AppFabric cache name, web service url, username, password, and database connection string; but otherwise it should work.
<configuration>
<configSections>
<sectionGroup name="Candor.Security">
<section name="UserManager"
type="Candor.Configuration.Provider.ProviderConfigurationSection, Candor.Configuration" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="MainConnection"
connectionString="[...]"/>
</connectionStrings>
<Candor.Security>
<UserManager defaultProvider="AppFabric" useEnvironmentSwitch="false">
<providers>
<!-- These are just examples: Copy just these provider types that make sense for your project
The type attributes below show the suggested project name and class name for each type of provider for consistency across projects.
-->
<add name="AppFabric"
type="Candor.Security.Caching.AppFabricProvider.AppFabricUserProvider, Candor.Security.Caching.AppFabricProvider"
TargetProviderName="Oracle"
CacheName="[SomeCacheNameHere]" />
<add name="WebService"
type="Candor.Security.WebServiceProvider.WebServiceUserProvider, Candor.Security.WebServiceProvider"
webServiceUrl = "http://test.domain.com/[ProjectName]/[WebServiceName].asmx"
webServiceUserName="[AppSpecificID]"
webServicePassword="[AppSpecificPassword]" />
<add name="SQL"
type="Candor.Security.Data.SQLProvider.SQLUserProvider, Candor.Security.Data.SQLProvider"
connectionName="MainConnection" />
<add name="Dummy"
type="Candor.Security.Tests.MockProviders.MockUserProvider, Candor.Security.Tests" />
</providers>
</UserManager>
</Candor.Security>
</configuration>
The WebService provider is the only one that needs to be transformed per environment. A configuration transform might look like the following, such as Web.Test.config. You should add or change settings to your transform shown here, but do not delete any other sections in your transforms that are not in this example. This sample will not work exactly as shown because you will need to plug in the correct web service url, username, and password, and database connection string; but otherwise it should work.
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="CurrentEnvironment" value="Test" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>
<connectionStrings>
<add name="MainConnection"
connectionString="[...]"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
<Candor.Security>
<UserManager>
<providers>
<add name="WebService"
type="Candor.Security.WebServiceProvider.WebServiceUserProvider, Candor.Security.WebServiceProvider"
webServiceUrl="http://domain.com/[ProjectName]/[WebServiceName].asmx"
webServiceUserName="[AppSpecificID]"
webServicePassword="[AppSpecificPassword]"
xdt:Transform="Replace"
xdt:Locator="Match(name)" />
</providers>
</UserManager>
</Candor.Security>
*/
/// <summary>
/// The user manager is a singleton access point to get to the collection of configured
/// UserProvider. If the providers are already configured via code configuration then
/// this manager class will get the providers from there. If they are not configured
/// by code then the providers must be defined in the configuration file for the AppDomain.
/// </summary>
public static class UserManager
{
private static ILog _logProvider;
/// <summary>
/// Gets or sets the log destination for this type. If not set, it will be automatically loaded when needed.
/// </summary>
public static ILog LogProvider
{
get { return _logProvider ?? (_logProvider = LogManager.GetLogger(typeof(UserManager))); }
set { _logProvider = value; }
}
/// <summary>
/// Gets the default provider instance.
/// </summary>
public static UserProvider Provider
{
get { return Providers.ActiveProvider; }
}
/// <summary>
/// Gets all the configured User providers.
/// </summary>
public static prov.ProviderCollection<UserProvider> Providers
{
get
{
var resolver = prov.ProviderResolver<UserProvider>.Get;
if (resolver.Providers.Count == 0)
resolver.Providers = new prov.ProviderCollection<UserProvider>(typeof(UserManager));
return resolver.Providers;
}
}
/// <summary>
/// Validates that a password meets minimum requirements.
/// </summary>
/// <param name="password"></param>
/// <param name="results"></param>
/// <returns></returns>
public static bool ValidatePassword(string password, ExecutionResults results)
{
return Provider.ValidatePassword(password, results);
}
/// <summary>
/// Validates that a string is a valid email address format.
/// </summary>
/// <returns></returns>
public static bool ValidateEmailAddressFormat(string emailAddress)
{
return Provider.ValidateEmailAddressFormat(emailAddress);
}
/// <summary>
/// Validates that the specified name meets minimum requirements.
/// </summary>
/// <param name="name">The desired name/alias.</param>
/// <param name="result">Any error messages about the desired name.</param>
/// <returns></returns>
public static bool ValidateName(string name, ExecutionResults result)
{
return Provider.ValidateName(name, result);
}
/// <summary>
/// Gets a user by identity.
/// </summary>
/// <param name="userID">The unique identity.</param>
/// <returns></returns>
public static User GetUserByID(Guid userID)
{
return Provider.GetUserByID(userID);
}
/// <summary>
/// Gets a user by name.
/// </summary>
/// <param name="name">The unique sign in name.</param>
/// <returns></returns>
public static User GetUserByName(string name)
{
return Provider.GetUserByName(name);
}
/// <summary>
/// Authenticates against the data store and returns a UserIdentity given
/// a user name, and password.
/// </summary>
/// <param name="name">The unique user name.</param>
/// <param name="password">The matching password.</param>
/// <param name="ipAddress">The internet address where the user is connecting from.</param>
/// <param name="duration">The amount of time that the issued token will be valid.</param>
/// <param name="result">A ExecutionResults instance to add applicable
/// warning and error messages to.</param>
/// <returns>
/// A valid user instance. If the user did not exist or the
/// credentials are incorrect then the IsAuthenticated flag
/// will be false. If the credentials were correct the
/// IsAuthenticated flag will be true.
/// </returns>
public static UserIdentity AuthenticateUser(string name, string password, UserSessionDurationType duration, string ipAddress,
ExecutionResults result)
{
return Provider.AuthenticateUser(name, password, duration, ipAddress, result);
}
/// <summary>
/// Authenticates against the data store and returns a UserIdentity given
/// a token returned from a previous authentication.
/// </summary>
/// <param name="token">The unique token.</param>
/// <param name="duration">The amount of time that the renewed token will be valid.</param>
/// <param name="ipAddress">The internet address where the user is connecting from.</param>
/// <param name="result">A ExecutionResults instance to add applicable
/// warning and error messages to.</param>
/// <returns>
/// A valid user identity instance. If the token is incorrect or expired
/// then the IsAuthenticated flag will be false. Otherwise the identity
/// will be authenticated.
/// </returns>
public static UserIdentity AuthenticateUser(string token, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
{
return Provider.AuthenticateUser(token, duration, ipAddress, result);
}
/// <summary>
/// Invalidates a session token so it can no longer be used.
/// </summary>
/// <param name="token"></param>
/// <param name="ipAddress"></param>
/// <param name="result"></param>
public static void InvalidateSession(string token, String ipAddress, ExecutionResults result)
{
Provider.InvalidateSession(token, ipAddress, result);
}
/// <summary>
/// Registers a new user. The PasswordHash property should be the actual password.
/// </summary>
/// <param name="user">A user with a raw password which is turned into a password hash as part of registration.</param>
/// <param name="duration">The amount of time that the initial session will be valid.</param>
/// <param name="ipAddress">The internet address where the user is connecting from.</param>
/// <param name="result">A ExecutionResults instance to add applicable
/// warning and error messages to.</param>
/// <returns>A boolean indicating success (true) or failure (false).</returns>
public static UserIdentity RegisterUser(User user, UserSessionDurationType duration, String ipAddress, ExecutionResults result)
{
return Provider.RegisterUser(user, duration, ipAddress, result);
}
/// <summary>
/// updates a user's name and/or password.
/// </summary>
/// <param name="item">The user details to be saved. If Password is empty is it not changed. If specified it should be the new raw password (not a hash).</param>
/// <param name="currentPassword">The current raw password for the user used to authenticate that the change can be made.</param>
/// <param name="ipAddress">The internet address where the user is connecting from.</param>
/// <param name="result">A ExecutionResults instance to add applicable
/// warning and error messages to.</param>
/// <returns>A boolean indicating success (true) or failure (false).</returns>
public static bool UpdateUser(User item, String currentPassword, String ipAddress, ExecutionResults result)
{
return Provider.UpdateUser(item, currentPassword, ipAddress, result);
}
/// <summary>
/// Generates a new password reset code for a user and stores that as the current code valid
/// for the next hour.
/// </summary>
/// <param name="name">The user name / email address.</param>
/// <returns>If the user exists, then a reset code string; otherwise null.</returns>
public static String GenerateUserResetCode(String name)
{
return Provider.GenerateUserResetCode(name);
}
/// <summary>
/// Gets the latest session(s) for a given user.
/// </summary>
/// <param name="userId">The unique identity.</param>
/// <param name="take">The maximum number of sessions to retrieve.</param>
/// <returns>A list of sessions; If empty then the user has never logged in (such as a no-show guest).</returns>
public static List<UserSession> GetLatestUserSessions(Guid userId, Int32 take)
{
return Provider.GetLatestUserSessions(userId, take);
}
}
}
| |
using System;
using System.Collections.Generic;
using Foundation;
using UIKit;
namespace UICatalog
{
[Register ("PickerViewController")]
public class PickerViewController : UIViewController
{
private enum ColorComponent {
Red,
Green,
Blue
}
private struct RGB {
public const float max = 255f;
public const float min = 0f;
public const float offset = 5f;
}
private readonly int _numberOfColorValuesPerComponent = (int)RGB.max / (int)RGB.offset + 1;
[Outlet]
UIPickerView PickerView { get; set; }
[Outlet]
UIView ColorSwatchView { get; set; }
float _redColor;
private float RedColor {
get { return _redColor; }
set {
_redColor = value;
UpdateColorSwatchViewBackgroundColor ();
}
}
private float _greenColor;
private float GreenColor {
get {
return _greenColor;
}
set {
_greenColor = value;
UpdateColorSwatchViewBackgroundColor ();
}
}
private float _blueColor;
private float BlueColor {
get {
return _blueColor;
}
set {
_blueColor = value;
UpdateColorSwatchViewBackgroundColor ();
}
}
public PickerViewController (IntPtr handle)
: base (handle)
{
_redColor = RGB.min;
_greenColor = RGB.min;
_blueColor = RGB.min;
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Show that a given row is selected. This is off by default.
PickerView.ShowSelectionIndicator = true;
ConfigurePickerView();
}
private void UpdateColorSwatchViewBackgroundColor()
{
ColorSwatchView.BackgroundColor = new UIColor(RedColor, GreenColor, BlueColor, 1f);
}
private void ConfigurePickerView()
{
// Set the default selected rows (the desired rows to initially select will vary from app to app).
Dictionary<ColorComponent, int> selectedRows = new Dictionary<ColorComponent, int> {
{ ColorComponent.Red, 13 },
{ ColorComponent.Green, 41 },
{ ColorComponent.Blue, 24 }
};
// kvp - means KeyValuePair
foreach (var kvp in selectedRows) {
var selectedRow = kvp.Value;
var colorComponent = kvp.Key;
// Note that the delegate method on UIPickerViewDelegate is not triggered when manually
// calling UIPickerView.selectRow(:inComponent:animated:). To do this, we fire off delegate
// method manually.
PickerView.Select (selectedRow, (int)colorComponent, animated: true);
Selected (PickerView, selectedRow, (int)colorComponent);
}
}
#region UIPickerViewDelegate
[Export ("pickerView:attributedTitleForRow:forComponent:")]
private NSAttributedString GetAttributedTitle (UIPickerView pickerView, int row, int component)
{
float colorValue = row * RGB.offset;
float value = colorValue / RGB.max;
float redColorComponent = RGB.min;
float greenColorComponent = RGB.min;
float blueColorComponent = RGB.min;
switch( (ColorComponent)component)
{
case ColorComponent.Red:
redColorComponent = value;
break;
case ColorComponent.Green:
greenColorComponent = value;
break;
case ColorComponent.Blue:
blueColorComponent = value;
break;
default:
throw new InvalidOperationException ("Invalid row/component combination for picker view.");
}
UIColor foregroundColor = new UIColor (redColorComponent, greenColorComponent, blueColorComponent, alpha: 1f);
// Set the foreground color for the entire attributed string.
UIStringAttributes attributes = new UIStringAttributes {
ForegroundColor = foregroundColor
};
var title = new NSAttributedString (string.Format ("{0}", (int)colorValue), attributes);
return title;
}
[Export ("pickerView:didSelectRow:inComponent:")]
private void Selected (UIPickerView pickerView, int row, int component)
{
float colorComponentValue = RGB.offset * (float)row / RGB.max;
switch ((ColorComponent)component)
{
case ColorComponent.Red:
RedColor = colorComponentValue;
break;
case ColorComponent.Green:
GreenColor = colorComponentValue;
break;
case ColorComponent.Blue:
BlueColor = colorComponentValue;
break;
}
}
#endregion
#region UIPickerViewAccessibilityDelegate
[Export("pickerView:accessibilityLabelForComponent:")]
private string GetAccessibilityLabel(UIPickerView pickerView, int component)
{
switch ((ColorComponent)component)
{
case ColorComponent.Red:
return "Red color component value".Localize ();
case ColorComponent.Green:
return "Green color component value".Localize ();
case ColorComponent.Blue:
return "Blue color component value".Localize ();
default:
throw new InvalidOperationException ();
}
}
#endregion
#region UIPickerViewDataSource
[Export("numberOfComponentsInPickerView:")]
public int GetComponentCount (UIPickerView pickerView)
{
return Enum.GetValues (typeof(ColorComponent)).Length;
}
[Export("pickerView:numberOfRowsInComponent:")]
public int GetRowsInComponent (UIPickerView pickerView, int component)
{
return _numberOfColorValuesPerComponent;
}
#endregion
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using HTTPlease.Testability;
using Xunit;
namespace DD.CloudControl.Client.Tests
{
using Models.Network;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Tests for the client's network domain APIs.
/// </summary>
public class NetworkDomainTests
: ClientTestBase
{
/// <summary>
/// List network domains (successful).
/// </summary>
[Fact]
public async Task ListNetworkDomains_Success()
{
CloudControlClient client = CreateCloudControlClientWithUserAccount(request =>
{
MessageAssert.AcceptsMediaType(request,
"application/json"
);
MessageAssert.HasRequestUri(request,
CreateApiUri($"caas/2.4/{TestOrganizationId}/network/networkDomain?datacenterId=AU9")
);
return request.CreateResponse(HttpStatusCode.OK,
responseBody: TestResponses.ListNetworkDomains_Success,
mediaType: "application/json"
);
});
using (client)
{
NetworkDomainQuery query = NetworkDomainQuery.ByDatacenter("AU9");
NetworkDomains networkDomains = await client.ListNetworkDomains(query);
Assert.NotNull(networkDomains);
Assert.Equal(2, networkDomains.TotalCount);
Assert.Equal(2, networkDomains.Items.Count);
Assert.Equal("AU9", networkDomains.Items[0].DatacenterId);
Assert.Equal("AU9", networkDomains.Items[1].DatacenterId);
}
}
/// <summary>
/// List a page of network domains (successful).
/// </summary>
[Fact]
public async Task ListNetworkDomains_Paged_Success()
{
CloudControlClient client = CreateCloudControlClientWithUserAccount(request =>
{
MessageAssert.AcceptsMediaType(request,
"application/json"
);
MessageAssert.HasRequestUri(request,
CreateApiUri($"caas/2.4/{TestOrganizationId}/network/networkDomain?datacenterId=AU9&pageNumber=1&pageSize=250")
);
return request.CreateResponse(HttpStatusCode.OK,
responseBody: TestResponses.ListNetworkDomains_Success,
mediaType: "application/json"
);
});
using (client)
{
NetworkDomainQuery query = NetworkDomainQuery.ByDatacenter("AU9");
Paging paging = new Paging
{
PageNumber = 1,
PageSize = 250
};
NetworkDomains networkDomains = await client.ListNetworkDomains(query, paging);
Assert.NotNull(networkDomains);
Assert.Equal(2, networkDomains.TotalCount);
Assert.Equal(2, networkDomains.Items.Count);
}
}
/// <summary>
/// Create a new network domain.
/// </summary>
[Fact]
public async Task CreateNetworkDomain_Success()
{
CloudControlClient client = CreateCloudControlClientWithUserAccount(async request =>
{
MessageAssert.AcceptsMediaType(request,
"application/json"
);
MessageAssert.HasRequestUri(request,
CreateApiUri($"caas/2.4/{TestOrganizationId}/network/deployNetworkDomain")
);
JObject expectedRequestBody = (JObject)JToken.Parse(
TestRequests.CreateNetworkDomain_Success
);
JObject actualRequestBody = (JObject)JToken.Parse(
await request.Content.ReadAsStringAsync()
);
Assert.Equal(
expectedRequestBody.ToString(Formatting.Indented).Trim(),
actualRequestBody.ToString(Formatting.Indented).Trim()
);
return request.CreateResponse(HttpStatusCode.OK,
responseBody: TestResponses.CreateNetworkDomain_Success,
mediaType: "application/json"
);
});
using (client)
{
Guid expectedNetworkDomainId = new Guid("f14a871f-9a25-470c-aef8-51e13202e1aa");
Guid actualNetworkDomainId = await client.CreateNetworkDomain(
datacenterId: "AU9",
name: "A Network Domain",
description: "This is a network domain",
type: NetworkDomainType.Essentials
);
Assert.Equal(
expectedNetworkDomainId,
actualNetworkDomainId
);
}
}
/// <summary>
/// Request bodies used in tests.
/// </summary>
static class TestRequests
{
/// <summary>
/// Request for CreateNetworkDomain (successful).
/// </summary>
public const string CreateNetworkDomain_Success = @"
{
""name"": ""A Network Domain"",
""description"": ""This is a network domain"",
""datacenterId"": ""AU9"",
""type"": ""ESSENTIALS""
}
";
}
/// <summary>
/// Response bodies used in tests.
/// </summary>
static class TestResponses
{
/// <summary>
/// Response for ListNetworkDomains (successful).
/// </summary>
public const string ListNetworkDomains_Success = @"
{
""networkDomain"": [
{
""name"": ""Domain 1"",
""description"": ""This is test domain 1"",
""type"": ""ESSENTIALS"",
""snatIpv4Address"": ""168.128.17.63"",
""createTime"": ""2016-01-12T22:33:05.000Z"",
""state"": ""NORMAL"",
""id"": ""75ab2a57-b75e-4ec6-945a-e8c60164fdf6"",
""datacenterId"": ""AU9""
},
{
""name"": ""Domain 2"",
""description"": """",
""type"": ""ESSENTIALS"",
""snatIpv4Address"": ""168.128.7.18"",
""createTime"": ""2016-01-18T08:56:16.000Z"",
""state"": ""NORMAL"",
""id"": ""b91e0ba4-322c-32ca-bbc7-50b9a72d5f98"",
""datacenterId"": ""AU9""
}
],
""pageNumber"": 1,
""pageCount"": 2,
""totalCount"": 2,
""pageSize"": 250
}
";
/// <summary>
/// Response for CreateNetworkDomain (successful).
/// </summary>
public const string CreateNetworkDomain_Success = @"
{
""operation"": ""DEPLOY_NETWORK_DOMAIN"",
""responseCode"": ""IN_PROGRESS"",
""message"": ""Request to deploy Network Domain 'A Network Domain' has been accepted and is being processed."",
""info"": [
{
""name"": ""networkDomainId"",
""value"": ""f14a871f-9a25-470c-aef8-51e13202e1aa""
}
],
""warning"": [],
""error"": [],
""requestId"": ""na9_20160321T074626030-0400_7e9fffe7-190b-46f2-9107-9d52fe57d0ad""
}
";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Security.Cryptography.Apple;
namespace System.Security.Cryptography
{
internal static partial class ECDiffieHellmanImplementation
{
public sealed partial class ECDiffieHellmanSecurityTransforms : ECDiffieHellman
{
private readonly EccSecurityTransforms _ecc = new EccSecurityTransforms();
public ECDiffieHellmanSecurityTransforms()
{
KeySize = 521;
}
internal ECDiffieHellmanSecurityTransforms(SafeSecKeyRefHandle publicKey)
{
KeySizeValue = _ecc.SetKeyAndGetSize(SecKeyPair.PublicOnly(publicKey));
}
internal ECDiffieHellmanSecurityTransforms(SafeSecKeyRefHandle publicKey, SafeSecKeyRefHandle privateKey)
{
KeySizeValue = _ecc.SetKeyAndGetSize(SecKeyPair.PublicPrivatePair(publicKey, privateKey));
}
public override KeySizes[] LegalKeySizes
{
get
{
// Return the three sizes that can be explicitly set (for backwards compatibility)
return new[]
{
new KeySizes(minSize: 256, maxSize: 384, skipSize: 128),
new KeySizes(minSize: 521, maxSize: 521, skipSize: 0),
};
}
}
public override int KeySize
{
get { return base.KeySize; }
set
{
if (KeySize == value)
return;
// Set the KeySize before freeing the key so that an invalid value doesn't throw away the key
base.KeySize = value;
_ecc.Dispose();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_ecc.Dispose();
}
base.Dispose(disposing);
}
public override ECParameters ExportExplicitParameters(bool includePrivateParameters)
{
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
}
public override ECParameters ExportParameters(bool includePrivateParameters)
{
return _ecc.ExportParameters(includePrivateParameters, KeySize);
}
public override void ImportParameters(ECParameters parameters)
{
KeySizeValue = _ecc.ImportParameters(parameters);
}
public override void ImportSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead)
{
KeySizeValue = _ecc.ImportSubjectPublicKeyInfo(source, out bytesRead);
}
public override void GenerateKey(ECCurve curve)
{
KeySizeValue = _ecc.GenerateKey(curve);
}
private SecKeyPair GetKeys()
{
return _ecc.GetOrGenerateKeys(KeySize);
}
public override byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) =>
DeriveKeyFromHash(otherPartyPublicKey, HashAlgorithmName.SHA256, null, null);
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[] secretPrepend,
byte[] secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
return ECDiffieHellmanDerivation.DeriveKeyFromHash(
otherPartyPublicKey,
hashAlgorithm,
secretPrepend,
secretAppend,
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[] hmacKey,
byte[] secretPrepend,
byte[] secretAppend)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
if (string.IsNullOrEmpty(hashAlgorithm.Name))
throw new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, nameof(hashAlgorithm));
return ECDiffieHellmanDerivation.DeriveKeyFromHmac(
otherPartyPublicKey,
hashAlgorithm,
hmacKey,
secretPrepend,
secretAppend,
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel,
byte[] prfSeed)
{
if (otherPartyPublicKey == null)
throw new ArgumentNullException(nameof(otherPartyPublicKey));
if (prfLabel == null)
throw new ArgumentNullException(nameof(prfLabel));
if (prfSeed == null)
throw new ArgumentNullException(nameof(prfSeed));
return ECDiffieHellmanDerivation.DeriveKeyTls(
otherPartyPublicKey,
prfLabel,
prfSeed,
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
private byte[] DeriveSecretAgreement(ECDiffieHellmanPublicKey otherPartyPublicKey, IncrementalHash hasher)
{
if (!(otherPartyPublicKey is ECDiffieHellmanSecurityTransformsPublicKey secTransPubKey))
{
secTransPubKey =
new ECDiffieHellmanSecurityTransformsPublicKey(otherPartyPublicKey.ExportParameters());
}
try
{
SafeSecKeyRefHandle otherPublic = secTransPubKey.KeyHandle;
if (Interop.AppleCrypto.EccGetKeySizeInBits(otherPublic) != KeySize)
{
throw new ArgumentException(
SR.Cryptography_ArgECDHKeySizeMismatch,
nameof(otherPartyPublicKey));
}
SafeSecKeyRefHandle thisPrivate = GetKeys().PrivateKey;
if (thisPrivate == null)
{
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}
// Since Apple only supports secp256r1, secp384r1, and secp521r1; and 521 fits in
// 66 bytes ((521 + 7) / 8), the Span path will always succeed.
Span<byte> secretSpan = stackalloc byte[66];
byte[] secret = Interop.AppleCrypto.EcdhKeyAgree(
thisPrivate,
otherPublic,
secretSpan,
out int bytesWritten);
// Either we wrote to the span or we returned an array, but not both, and not neither.
// ("neither" would have thrown)
Debug.Assert(
(bytesWritten == 0) != (secret == null),
$"bytesWritten={bytesWritten}, (secret==null)={secret == null}");
if (hasher == null)
{
return secret ?? secretSpan.Slice(0, bytesWritten).ToArray();
}
if (secret == null)
{
hasher.AppendData(secretSpan.Slice(0, bytesWritten));
}
else
{
hasher.AppendData(secret);
Array.Clear(secret, 0, secret.Length);
}
return null;
}
finally
{
if (!ReferenceEquals(otherPartyPublicKey, secTransPubKey))
{
secTransPubKey.Dispose();
}
}
}
public override ECDiffieHellmanPublicKey PublicKey =>
new ECDiffieHellmanSecurityTransformsPublicKey(ExportParameters(false));
private class ECDiffieHellmanSecurityTransformsPublicKey : ECDiffieHellmanPublicKey
{
private EccSecurityTransforms _ecc;
public ECDiffieHellmanSecurityTransformsPublicKey(ECParameters ecParameters)
{
Debug.Assert(ecParameters.D == null);
_ecc = new EccSecurityTransforms();
_ecc.ImportParameters(ecParameters);
}
public override string ToXmlString()
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// There is no key blob format for OpenSSL ECDH like there is for Cng ECDH. Instead of allowing
/// this to return a potentially confusing empty byte array, we opt to throw instead.
/// </summary>
public override byte[] ToByteArray()
{
throw new PlatformNotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_ecc.Dispose();
_ecc = null;
}
base.Dispose(disposing);
}
public override ECParameters ExportExplicitParameters() =>
throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
public override ECParameters ExportParameters()
{
if (_ecc == null)
{
throw new ObjectDisposedException(typeof(ECDiffieHellmanSecurityTransformsPublicKey).Name);
}
return _ecc.ExportParameters(includePrivateParameters: false, keySizeInBits: -1);
}
internal SafeSecKeyRefHandle KeyHandle
{
get
{
if (_ecc == null)
{
throw new ObjectDisposedException(
typeof(ECDiffieHellmanSecurityTransformsPublicKey).Name);
}
return _ecc.GetOrGenerateKeys(-1).PublicKey;
}
}
}
}
}
}
| |
//---------------------------------------------------------------------
// File: StreamHelper.cs
//
// Summary:
//
// Author: Kevin B. Smith
//
//---------------------------------------------------------------------
// Copyright (c) 2004-2015, Kevin B. Smith. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------
namespace BizUnit.TestSteps.Common
{
using System;
using System.Xml;
using System.Text;
using System.IO;
/// <summary>
/// Helper class for stream opperations
/// </summary>
public class StreamHelper
{
/// <summary>
/// Performs a binary comparison between two streams
/// </summary>
/// <param name="s1">The 1st stream to compare aginst the 2nd</param>
/// <param name="s2">The 2nd stream to compare aginst the 1st</param>
static public void CompareStreams(Stream s1, Stream s2)
{
var buff1 = new byte[4096];
var buff2 = new byte[4096];
int read1;
do
{
read1 = s1.Read(buff1, 0, 4096);
int read2 = s2.Read(buff2, 0, 4096);
if ( read1 != read2 )
{
throw new ApplicationException( String.Format( "Streams do not contain identical data!" ) );
}
if ( 0 == read1 )
{
break;
}
for ( int c = 0; c < read1; c++ )
{
if ( buff1[c] != buff2[c] )
{
throw new ApplicationException( String.Format( "Streams do not contain identical data!" ) );
}
}
} while( read1 > 0 );
}
/// <summary>
/// Helper method to load a disc FILE into a MemoryStream
/// </summary>
/// <param name="filePath">The path to the FILE containing the data</param>
/// <param name="timeout">The timeout afterwhich if the FILE is not found the method will fail</param>
/// <returns>MemoryStream containing the data in the FILE</returns>
public static MemoryStream LoadFileToStream(string filePath, double timeout)
{
MemoryStream ms = null;
bool loaded = false;
DateTime now = DateTime.Now;
do
{
try
{
ms = LoadFileToStream(filePath);
loaded = true;
break;
}
catch(Exception)
{
if ( DateTime.Now < now.AddMilliseconds(timeout) )
{
System.Threading.Thread.Sleep(500);
}
}
} while ( DateTime.Now < now.AddMilliseconds(timeout) );
if ( !loaded )
{
throw new ApplicationException( string.Format( "The file: {0} was not found within the timeout period!", filePath ) );
}
return ms;
}
/// <summary>
/// Helper method to load a disc FILE into a MemoryStream
/// </summary>
/// <param name="filePath">The path to the FILE containing the data</param>
/// <returns>MemoryStream containing the data in the FILE</returns>
public static MemoryStream LoadFileToStream(string filePath)
{
FileStream fs = null;
MemoryStream s;
try
{
// Get the match data...
fs = File.OpenRead(filePath);
s = new MemoryStream();
var buff = new byte[1024];
int read = fs.Read(buff, 0, 1024);
while ( 0 < read )
{
s.Write(buff, 0, read);
read = fs.Read(buff, 0, 1024);
}
s.Flush();
s.Seek(0, SeekOrigin.Begin);
}
finally
{
if ( null != fs )
{
fs.Close();
}
}
return s;
}
/// <summary>
/// Helper method to write the data in a stream to the console
/// </summary>
/// <param name="description">The description text that will be written before the stream data</param>
/// <param name="ms">Stream containing the data to write</param>
/// <param name="context">The BizUnit context object which holds state and is passed between test steps</param>
public static void WriteStreamToConsole(string description, MemoryStream ms, Context context)
{
ms.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(ms);
context.LogData( description, sr.ReadToEnd() );
ms.Seek(0, SeekOrigin.Begin);
}
/// <summary>
/// Helper method to load a forward only stream into a seekable MemoryStream
/// </summary>
/// <param name="s">The forward only stream to read the data from</param>
/// <returns>MemoryStream containg the data as read from s</returns>
public static MemoryStream LoadMemoryStream(Stream s)
{
var ms = new MemoryStream();
var buff = new byte[1024];
int read = s.Read(buff, 0, 1024);
while ( 0 < read )
{
ms.Write(buff, 0, read);
read = s.Read(buff, 0, 1024);
}
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
/// <summary>
/// Helper method to load a string into a MemoryStream
/// </summary>
/// <param name="s">The string containing the data that will be loaded into the stream</param>
/// <returns>MemoryStream containg the data read from the string</returns>
public static MemoryStream LoadMemoryStream(string s)
{
Encoding utf8 = Encoding.UTF8;
byte[] bytes = utf8.GetBytes(s);
var ms = new MemoryStream(bytes);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
/// <summary>
/// Helper method to compare two Xml documents from streams
/// </summary>
/// <param name="s1">Stream containing the 1st Xml document</param>
/// <param name="s2">Stream containing the 2nd Xml document</param>
/// <param name="context">The BizUnit context object which holds state and is passed between test steps</param>
public static void CompareXmlDocs(Stream s1, Stream s2, Context context)
{
var doc = new XmlDocument();
doc.Load(new XmlTextReader(s1));
XmlElement root = doc.DocumentElement;
string data1 = root.OuterXml;
doc = new XmlDocument();
doc.Load(new XmlTextReader(s2));
root = doc.DocumentElement;
string data2 = root.OuterXml;
context.LogInfo("About to compare the following Xml documents:\r\nDocument1: {0},\r\nDocument2: {1}", data1, data2);
CompareStreams( LoadMemoryStream(data1), LoadMemoryStream(data2) );
}
/// <summary>
/// Helper method to encode a stream
/// </summary>
/// <param name="rawData">Stream containing data to be encoded</param>
/// <param name="encoding">The encoding to be used for the data</param>
/// <returns>Encoded MemoryStream</returns>
public static Stream EncodeStream(Stream rawData, Encoding encoding)
{
rawData.Seek(0, SeekOrigin.Begin);
var sr = new StreamReader(rawData);
string data = sr.ReadToEnd();
Encoding e = encoding;
byte[] bytes = e.GetBytes(data);
return new MemoryStream(bytes);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Wukong.Helpers;
using Wukong.Models;
using static System.Threading.Timeout;
namespace Wukong.Services
{
public class UserSong
{
public delegate void ClientSongChangedHandler(UserSong userSong, ClientSong previousSong);
public readonly string UserId;
private ClientSong song;
public ClientSong Song
{
get => song;
set
{
var previous = song;
song = value;
}
}
public UserSong(string userId)
{
UserId = userId;
}
public UserSong Clone()
{
return new UserSong(UserId)
{
Song = Song
};
}
}
public class Channel
{
public string Id { get; }
private readonly ISocketManager socketManager;
private readonly IProvider provider;
private readonly IUserManager userManager;
private readonly IMemoryCache cache;
private readonly ISet<string> finishedUsers = new HashSet<string>();
private readonly ISet<string> downvoteUsers = new HashSet<string>();
private readonly ChannelUserList list = new ChannelUserList();
private DateTime startTime;
private Timer finishTimeoutTimer;
private double Elapsed => (DateTime.Now - startTime).TotalSeconds;
public bool Empty => list.Empty;
private Song nextServerSong;
public List<string> UserList => list.UserList;
public Channel(string id, ISocketManager socketManager, IProvider provider, IUserManager userManager, IMemoryCache cache)
{
Id = id;
this.socketManager = socketManager;
this.provider = provider;
this.userManager = userManager;
this.cache = cache;
list.CurrentChanged += song =>
{
startTime = DateTime.Now;
finishedUsers.Clear();
downvoteUsers.Clear();
BroadcastPlayCurrentSong(song);
};
list.UserChanged += (add, userId) =>
{
BroadcastUserListUpdated();
};
list.NextChanged += song =>
{
BroadcastNextSongUpdated(song);
};
}
public void Join(string userId)
{
list.AddUser(userId);
if (socketManager.IsConnected(userId))
{
EmitChannelInfo(userId);
}
}
public void Leave(string userId)
{
list.RemoveUser(userId);
}
public void Connect(string userId)
{
EmitChannelInfo(userId);
}
public void UpdateSong(string userId, ClientSong song)
{
list.SetSong(userId, song);
}
public bool ReportFinish(string userId, ClientSong song, bool force = false)
{
if (song != list.CurrentPlaying?.Song)
{
CheckShouldForwardCurrentSong();
// Workaround: told the user the current song
EmitChannelInfo(userId);
return false;
}
if (force) downvoteUsers.Add(userId);
else finishedUsers.Add(userId);
CheckShouldForwardCurrentSong();
return true;
}
public bool HasUser(string userId)
{
return list.UserList.Contains(userId);
}
private void CheckShouldForwardCurrentSong()
{
var userList = list.UserList;
var downVoteUserCount = downvoteUsers.Intersect(userList).Count;
var undeterminedCount = userList.Except(downvoteUsers).Except(finishedUsers).Count();
var connectedUserCount = userList.Select(it => socketManager.IsConnected(it)).Count();
if (!list.IsPlaying || downVoteUserCount >= QueryForceForwardCount(connectedUserCount) || undeterminedCount == 0)
{
ShouldForwardNow();
}
else if (undeterminedCount <= connectedUserCount * 0.5)
{
if (finishTimeoutTimer != null) return;
finishTimeoutTimer = new Timer(ShouldForwardNow, null, 5 * 1000, Infinite);
}
}
private static int QueryForceForwardCount(int total)
{
return Convert.ToInt32(Math.Ceiling((double)total / 2));
}
private void ShouldForwardNow(object state = null)
{
finishTimeoutTimer?.Change(Infinite, Infinite);
finishTimeoutTimer?.Dispose();
finishTimeoutTimer = null;
list.GoNext();
}
private async Task<Song> GetSong(ClientSong song) {
if (song == null) return null;
if (cache.TryGetValue(song, out Song cachedSong)) {
return cachedSong;
}
cachedSong = await provider.GetSong(song, true);
if (cachedSong != null) {
cache.Set(song, cachedSong, TimeSpan.FromMinutes(10));
}
return cachedSong;
}
private void BroadcastUserListUpdated(string userId = null)
{
var users = list.UserList;
socketManager.SendMessage(userId != null ? new[] { userId } : users.ToArray(),
new UserListUpdated
{
ChannelId = Id,
Users = users.Select(it => userManager.GetUser(it)).ToList()
});
}
private async void BroadcastNextSongUpdated(ClientSong next, string userId = null)
{
if (next == null) return;
if (nextServerSong == null || nextServerSong.SongId != next.SongId || nextServerSong.SiteId != next.SiteId)
{
nextServerSong = await GetSong(next);
}
if (nextServerSong == null) return;
socketManager.SendMessage(userId != null ? new[] { userId } : UserList.ToArray(),
new NextSongUpdated
{
ChannelId = Id,
Song = nextServerSong
});
}
private async void BroadcastPlayCurrentSong(UserSong current, string userId = null)
{
if (current?.Song != null)
{
Song song;
if (nextServerSong != null &&
nextServerSong.SiteId == current.Song.SiteId &&
nextServerSong.SongId == current.Song.SongId)
{
song = nextServerSong;
}
else
{
song = await GetSong(current.Song);
}
socketManager.SendMessage(userId != null ? new[] { userId } : list.UserList.ToArray()
, new Play
{
ChannelId = Id,
Downvote = downvoteUsers.Contains(userId),
Song = song ?? new Song
{
SiteId = current.Song.SiteId,
SongId = current.Song.SongId,
Title = "server load error",
Artist = current.Song.SiteId,
Album = current.Song.SongId
}, // Workaround for play song == null problem
Elapsed = Elapsed,
User = current.UserId
});
if (song == null)
{
BroadcastNotification(string.Format("Server error: Failed to get song {0}:{1}", current.Song.SiteId, current.Song.SongId), userId);
}
}
}
private void BroadcastNotification(string message, string userId = null)
{
socketManager.SendMessage(userId != null ? new[] { userId } : list.UserList.ToArray(),
new NotificationEvent
{
ChannelId = Id,
Notification = new Notification
{
Message = message,
Timeout = 10000
}
});
}
private void EmitChannelInfo(string userId)
{
BroadcastUserListUpdated(userId);
BroadcastPlayCurrentSong(list.CurrentPlaying, userId);
BroadcastNextSongUpdated(list.NextSong, userId);
}
public async Task<Song> GetCurrent() {
return await GetSong(list.CurrentPlaying?.Song);
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT 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 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT 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 SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using SharpNeat.Core;
using SharpNeat.Network;
using SharpNeat.Utility;
namespace SharpNeat.Genomes.Neat
{
/// <summary>
/// An IGenomeFactory for NeatGenomes. We use the factory as a means of generating an initial population either
/// randomly or using a seed genome or genomes.
/// Subsequently all NeatGenome objects keep a reference to this factory object for convenient access to
/// NeatGenome parameters and ID generator objects.
/// </summary>
public class NeatGenomeFactory : IGenomeFactory<NeatGenome>
{
const int __INNOVATION_HISTORY_BUFFER_SIZE = 0x20000;
/// <summary>NeatGenomeParameters currently in effect.</summary>
protected NeatGenomeParameters _neatGenomeParamsCurrent;
readonly NeatGenomeParameters _neatGenomeParamsComplexifying;
readonly NeatGenomeParameters _neatGenomeParamsSimplifying;
readonly NeatGenomeStats _stats = new NeatGenomeStats();
readonly int _inputNeuronCount;
readonly int _outputNeuronCount;
readonly UInt32IdGenerator _genomeIdGenerator;
readonly UInt32IdGenerator _innovationIdGenerator;
int _searchMode;
readonly KeyedCircularBuffer<ConnectionEndpointsStruct,uint?> _addedConnectionBuffer
= new KeyedCircularBuffer<ConnectionEndpointsStruct,uint?>(__INNOVATION_HISTORY_BUFFER_SIZE);
readonly KeyedCircularBuffer<uint,AddedNeuronGeneStruct> _addedNeuronBuffer
= new KeyedCircularBuffer<uint,AddedNeuronGeneStruct>(__INNOVATION_HISTORY_BUFFER_SIZE);
/// <summary>Random number generator associated with this factory.</summary>
protected readonly FastRandom _rng = new FastRandom();
readonly ZigguratGaussianSampler _gaussianSampler = new ZigguratGaussianSampler();
/// <summary>Activation function library associated with this factory.</summary>
protected readonly IActivationFunctionLibrary _activationFnLibrary;
#region Constructors [NEAT]
/// <summary>
/// Constructs with default NeatGenomeParameters and ID generators initialized to zero.
/// </summary>
public NeatGenomeFactory(int inputNeuronCount, int outputNeuronCount)
{
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_neatGenomeParamsCurrent = new NeatGenomeParameters();
_neatGenomeParamsComplexifying = _neatGenomeParamsCurrent;
_neatGenomeParamsSimplifying = NeatGenomeParameters.CreateSimplifyingParameters(_neatGenomeParamsComplexifying);
_genomeIdGenerator = new UInt32IdGenerator();
_innovationIdGenerator = new UInt32IdGenerator();
_activationFnLibrary = DefaultActivationFunctionLibrary.CreateLibraryNeat(_neatGenomeParamsCurrent.ActivationFn);
}
/// <summary>
/// Constructs a NeatGenomeFactory with the provided NeatGenomeParameters and ID generators initialized to zero.
/// </summary>
public NeatGenomeFactory(int inputNeuronCount, int outputNeuronCount,
NeatGenomeParameters neatGenomeParams)
{
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_activationFnLibrary = DefaultActivationFunctionLibrary.CreateLibraryNeat(neatGenomeParams.ActivationFn);
_neatGenomeParamsCurrent = neatGenomeParams;
_neatGenomeParamsComplexifying = _neatGenomeParamsCurrent;
_neatGenomeParamsSimplifying = NeatGenomeParameters.CreateSimplifyingParameters(_neatGenomeParamsComplexifying);
_genomeIdGenerator = new UInt32IdGenerator();
_innovationIdGenerator = new UInt32IdGenerator();
}
/// <summary>
/// Constructs a NeatGenomeFactory with the provided NeatGenomeParameters and ID generators.
/// </summary>
public NeatGenomeFactory(int inputNeuronCount, int outputNeuronCount,
NeatGenomeParameters neatGenomeParams,
UInt32IdGenerator genomeIdGenerator,
UInt32IdGenerator innovationIdGenerator)
{
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_activationFnLibrary = DefaultActivationFunctionLibrary.CreateLibraryNeat(neatGenomeParams.ActivationFn);
_neatGenomeParamsCurrent = neatGenomeParams;
_neatGenomeParamsComplexifying = _neatGenomeParamsCurrent;
_neatGenomeParamsSimplifying = NeatGenomeParameters.CreateSimplifyingParameters(_neatGenomeParamsComplexifying);
_genomeIdGenerator = genomeIdGenerator;
_innovationIdGenerator = innovationIdGenerator;
}
#endregion
#region Constructors [CPPN/HyperNEAT]
/// <summary>
/// Constructs with default NeatGenomeParameters, ID generators initialized to zero and the provided
/// IActivationFunctionLibrary.
/// This overload required for CPPN support.
/// </summary>
public NeatGenomeFactory(int inputNeuronCount, int outputNeuronCount,
IActivationFunctionLibrary activationFnLibrary)
{
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_activationFnLibrary = activationFnLibrary;
_neatGenomeParamsCurrent = new NeatGenomeParameters();
_neatGenomeParamsComplexifying = _neatGenomeParamsCurrent;
_neatGenomeParamsSimplifying = NeatGenomeParameters.CreateSimplifyingParameters(_neatGenomeParamsComplexifying);
_genomeIdGenerator = new UInt32IdGenerator();
_innovationIdGenerator = new UInt32IdGenerator();
}
/// <summary>
/// Constructs with ID generators initialized to zero and the provided
/// IActivationFunctionLibrary and NeatGenomeParameters.
/// This overload required for CPPN support.
/// </summary>
public NeatGenomeFactory(int inputNeuronCount, int outputNeuronCount,
IActivationFunctionLibrary activationFnLibrary,
NeatGenomeParameters neatGenomeParams)
{
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_activationFnLibrary = activationFnLibrary;
_neatGenomeParamsCurrent = neatGenomeParams;
_neatGenomeParamsComplexifying = _neatGenomeParamsCurrent;
_neatGenomeParamsSimplifying = NeatGenomeParameters.CreateSimplifyingParameters(_neatGenomeParamsComplexifying);
_genomeIdGenerator = new UInt32IdGenerator();
_innovationIdGenerator = new UInt32IdGenerator();
}
/// <summary>
/// Constructs with the provided IActivationFunctionLibrary, NeatGenomeParameters and
/// ID Generators.
/// This overload required for CPPN support.
/// </summary>
public NeatGenomeFactory(int inputNeuronCount, int outputNeuronCount,
IActivationFunctionLibrary activationFnLibrary,
NeatGenomeParameters neatGenomeParams,
UInt32IdGenerator genomeIdGenerator,
UInt32IdGenerator innovationIdGenerator)
{
_inputNeuronCount = inputNeuronCount;
_outputNeuronCount = outputNeuronCount;
_activationFnLibrary = activationFnLibrary;
_neatGenomeParamsCurrent = neatGenomeParams;
_neatGenomeParamsComplexifying = _neatGenomeParamsCurrent;
_neatGenomeParamsSimplifying = NeatGenomeParameters.CreateSimplifyingParameters(_neatGenomeParamsComplexifying);
_genomeIdGenerator = genomeIdGenerator;
_innovationIdGenerator = innovationIdGenerator;
}
#endregion
#region IGenomeFactory<NeatGenome> Members
/// <summary>
/// Gets the factory's genome ID generator.
/// </summary>
public UInt32IdGenerator GenomeIdGenerator
{
get { return _genomeIdGenerator; }
}
/// <summary>
/// Gets or sets a mode value. This is intended as a means for an evolution algorithm to convey changes
/// in search mode to genomes, and because the set of modes is specific to each concrete implementation
/// of an IEvolutionAlgorithm the mode is defined as an integer (rather than an enum[eration]).
/// E.g. SharpNEAT's implementation of NEAT uses an evolutionary algorithm that alternates between
/// a complexifying and simplifying mode, in order to do this the algorithm class needs to notify the genomes
/// of the current mode so that the CreateOffspring() methods are able to generate offspring appropriately -
/// e.g. we avoid adding new nodes and connections and increase the rate of deletion mutations when in
/// simplifying mode.
/// </summary>
public int SearchMode
{
get { return _searchMode; }
set
{
// Store the mode and switch to a set of NeatGenomeParameters appropriate to the mode.
// Note. we don't reference the ComplexityRegulationMode enum directly so as not to introduce a
// compile time dependency between this class and the NeatEvolutionaryAlgorithm - we
// may wish to use NeatGenome with other algorithm classes in the future.
_searchMode = value;
switch(value)
{
case 0: // ComplexityRegulationMode.Complexifying
_neatGenomeParamsCurrent = _neatGenomeParamsComplexifying;
break;
case 1: // ComplexityRegulationMode.Simplifying
_neatGenomeParamsCurrent = _neatGenomeParamsSimplifying;
break;
default:
throw new SharpNeatException("Unexpected SearchMode");
}
}
}
/// <summary>
/// Creates a list of randomly initialised genomes.
/// </summary>
/// <param name="length">The number of genomes to create.</param>
/// <param name="birthGeneration">The current evolution algorithm generation.
/// Assigned to the new genomes as their birth generation.</param>
public List<NeatGenome> CreateGenomeList(int length, uint birthGeneration)
{
List<NeatGenome> genomeList = new List<NeatGenome>(length);
for(int i=0; i<length; i++)
{ // We reset the innovation ID to zero so that all created genomes use the same
// innovation IDs for matching neurons and connections. This isn't a strict requirement but
// throughout the SharpNeat code we attempt to use the same innovation ID for like structures
// to improve the effectiveness of sexual reproduction.
_innovationIdGenerator.Reset();
genomeList.Add(CreateGenome(birthGeneration));
}
return genomeList;
}
/// <summary>
/// Creates a list of genomes spawned from a seed genome. Spawning uses asexual reproduction.
/// </summary>
/// <param name="length">The number of genomes to create.</param>
/// <param name="birthGeneration">The current evolution algorithm generation.
/// Assigned to the new genomes as their birth generation.</param>
/// <param name="seedGenome">The seed genome to spawn new genomes from.</param>
public List<NeatGenome> CreateGenomeList(int length, uint birthGeneration, NeatGenome seedGenome)
{
Debug.Assert(this == seedGenome.GenomeFactory, "seedGenome is from a different genome factory.");
List<NeatGenome> genomeList = new List<NeatGenome>(length);
// Add an exact copy of the seed to the list.
NeatGenome newGenome = CreateGenomeCopy(seedGenome, _genomeIdGenerator.NextId, birthGeneration);
genomeList.Add(newGenome);
// For the remainder we create mutated offspring from the seed.
for(int i=1; i<length; i++) {
genomeList.Add(seedGenome.CreateOffspring(birthGeneration));
}
return genomeList;
}
/// <summary>
/// Creates a list of genomes spawned from a list of seed genomes. Spawning uses asexual reproduction and
/// typically we would simply repeatedly loop over (and spawn from) the seed genomes until we have the
/// required number of spawned genomes.
/// </summary>
/// <param name="length">The number of genomes to create.</param>
/// <param name="birthGeneration">The current evolution algorithm generation.
/// Assigned to the new genomes as their birth generation.</param>
/// <param name="seedGenomeList">A list of seed genomes from which to spawn new genomes from.</param>
public List<NeatGenome> CreateGenomeList(int length, uint birthGeneration, List<NeatGenome> seedGenomeList)
{
if(seedGenomeList.Count == 0) {
throw new SharpNeatException("CreateGenomeList() requires at least on seed genome in seedGenomeList.");
}
// Create a copy of the list so that we can shuffle the items without modifying the original list.
seedGenomeList = new List<NeatGenome>(seedGenomeList);
Utilities.Shuffle(seedGenomeList, _rng);
// Make exact copies of seed genomes and insert them into our new genome list.
List<NeatGenome> genomeList = new List<NeatGenome>(length);
int idx=0;
int seedCount = seedGenomeList.Count;
for(int seedIdx=0; idx<length && seedIdx<seedCount; idx++, seedIdx++)
{
// Add an exact copy of the seed to the list.
NeatGenome newGenome = CreateGenomeCopy(seedGenomeList[seedIdx], _genomeIdGenerator.NextId, birthGeneration);
genomeList.Add(newGenome);
}
// Keep spawning offspring from seed genomes until we have the required number of genomes.
for(; idx<length;) {
for(int seedIdx=0; idx<length && seedIdx<seedCount; idx++, seedIdx++) {
genomeList.Add(seedGenomeList[seedIdx].CreateOffspring(birthGeneration));
}
}
return genomeList;
}
/// <summary>
/// Creates a single randomly initialised genome.
/// A random set of connections are made form the input to the output neurons, the number of
/// connections made is based on the NeatGenomeParameters.InitialInterconnectionsProportion
/// which specifies the proportion of all posssible input-output connections to be made in
/// initial genomes.
///
/// The connections that are made are allocated innovation IDs in a consistent manner across
/// the initial population of genomes. To do this we allocate IDs sequentially to all possible
/// interconnections and then randomly select some proportion of connections for inclusion in the
/// genome. In addition, for this scheme to work the innovation ID generator must be reset to zero
/// prior to each call to CreateGenome(), and a test is made to ensure this is the case.
///
/// The consistent allocation of innovation IDs ensure that equivalent connections in different
/// genomes have the same innovation ID, and although this isn't strictly necessary it is
/// required for sexual reproduction to work effectively - like structures are detected by comparing
/// innovation IDs only.
/// </summary>
/// <param name="birthGeneration">The current evolution algorithm generation.
/// Assigned to the new genome as its birth generation.</param>
public NeatGenome CreateGenome(uint birthGeneration)
{
NeuronGeneList neuronGeneList = new NeuronGeneList(_inputNeuronCount + _outputNeuronCount);
NeuronGeneList inputNeuronGeneList = new NeuronGeneList(_inputNeuronCount); // includes single bias neuron.
NeuronGeneList outputNeuronGeneList = new NeuronGeneList(_outputNeuronCount);
// Create a single bias neuron.
uint biasNeuronId = _innovationIdGenerator.NextId;
if(0 != biasNeuronId)
{ // The ID generator must be reset before calling this method so that all generated genomes use the
// same innovation ID for matching neurons and structures.
throw new SharpNeatException("IdGenerator must be reset before calling CreateGenome(uint)");
}
// Note. Genes within nGeneList must always be arranged according to the following layout plan.
// Bias - single neuron. Innovation ID = 0
// Input neurons.
// Output neurons.
// Hidden neurons.
NeuronGene neuronGene = CreateNeuronGene(biasNeuronId, NodeType.Bias);
inputNeuronGeneList.Add(neuronGene);
neuronGeneList.Add(neuronGene);
// Create input neuron genes.
for(int i=0; i<_inputNeuronCount; i++)
{
neuronGene = CreateNeuronGene(_innovationIdGenerator.NextId, NodeType.Input);
inputNeuronGeneList.Add(neuronGene);
neuronGeneList.Add(neuronGene);
}
// Create output neuron genes.
for(int i=0; i<_outputNeuronCount; i++)
{
neuronGene = CreateNeuronGene(_innovationIdGenerator.NextId, NodeType.Output);
outputNeuronGeneList.Add(neuronGene);
neuronGeneList.Add(neuronGene);
}
// Define all possible connections between the input and output neurons (fully interconnected).
int srcCount = inputNeuronGeneList.Count;
int tgtCount = outputNeuronGeneList.Count;
ConnectionDefinition[] connectionDefArr = new ConnectionDefinition[srcCount * tgtCount];
for(int srcIdx=0, i=0; srcIdx<srcCount; srcIdx++) {
for(int tgtIdx=0; tgtIdx<tgtCount; tgtIdx++) {
connectionDefArr[i++] = new ConnectionDefinition(_innovationIdGenerator.NextId, srcIdx, tgtIdx);
}
}
// Shuffle the array of possible connections.
Utilities.Shuffle(connectionDefArr, _rng);
// Select connection definitions from the head of the list and convert them to real connections.
// We want some proportion of all possible connections but at least one (Connectionless genomes are not allowed).
int connectionCount = (int)Utilities.ProbabilisticRound(
(double)connectionDefArr.Length * _neatGenomeParamsComplexifying.InitialInterconnectionsProportion,
_rng);
connectionCount = Math.Max(1, connectionCount);
// Create the connection gene list and populate it.
ConnectionGeneList connectionGeneList = new ConnectionGeneList(connectionCount);
for(int i=0; i<connectionCount; i++)
{
ConnectionDefinition def = connectionDefArr[i];
NeuronGene srcNeuronGene = inputNeuronGeneList[def._sourceNeuronIdx];
NeuronGene tgtNeuronGene = outputNeuronGeneList[def._targetNeuronIdx];
ConnectionGene cGene = new ConnectionGene(def._innovationId,
srcNeuronGene.InnovationId,
tgtNeuronGene.InnovationId,
GenerateRandomConnectionWeight());
connectionGeneList.Add(cGene);
// Register connection with endpoint neurons.
srcNeuronGene.TargetNeurons.Add(cGene.TargetNodeId);
tgtNeuronGene.SourceNeurons.Add(cGene.SourceNodeId);
}
// Ensure connections are sorted.
connectionGeneList.SortByInnovationId();
// Create and return the completed genome object.
return CreateGenome(_genomeIdGenerator.NextId, birthGeneration,
neuronGeneList, connectionGeneList,
_inputNeuronCount, _outputNeuronCount, false);
}
/// <summary>
/// Supports debug/integrity checks. Checks that a given genome object's type is consistent with the genome factory.
/// Typically the wrong type of object may occur where factorys are subtyped and not all of the relevant virtual methods are overriden.
/// Returns true if OK.
/// </summary>
public virtual bool CheckGenomeType(NeatGenome genome)
{
return genome.GetType() == typeof(NeatGenome);
}
#endregion
#region Properties [NeatGenome Specific]
/// <summary>
/// Gets the factory's NeatGenomeParameters currently in effect.
/// </summary>
public NeatGenomeParameters NeatGenomeParameters
{
get { return _neatGenomeParamsCurrent; }
}
/// <summary>
/// Gets the number of input neurons expressed by the genomes related to this factory.
/// </summary>
public int InputNeuronCount
{
get { return _inputNeuronCount; }
}
/// <summary>
/// Gets the number of output neurons expressed by the genomes related to this factory.
/// </summary>
public int OutputNeuronCount
{
get { return _outputNeuronCount; }
}
/// <summary>
/// Gets the factory's activation function library.
/// </summary>
public IActivationFunctionLibrary ActivationFnLibrary
{
get { return _activationFnLibrary; }
}
/// <summary>
/// Gets the factory's innovation ID generator.
/// </summary>
public UInt32IdGenerator InnovationIdGenerator
{
get { return _innovationIdGenerator; }
}
/// <summary>
/// Gets the history buffer of added connections. Used when adding new connections to check if an
/// identical connection has been added to a genome elsewhere in the population. This allows re-use
/// of the same innovation ID for like connections.
/// </summary>
public KeyedCircularBuffer<ConnectionEndpointsStruct,uint?> AddedConnectionBuffer
{
get { return _addedConnectionBuffer; }
}
/// <summary>
/// Gets the history buffer of added neurons. Used when adding new neurons to check if an
/// identical neuron has been added to a genome elsewhere in the population. This allows re-use
/// of the same innovation ID for like neurons.
/// </summary>
public KeyedCircularBuffer<uint,AddedNeuronGeneStruct> AddedNeuronBuffer
{
get { return _addedNeuronBuffer; }
}
/// <summary>
/// Gets a random number generator associated with the factory.
/// Note. The provided RNG is not thread safe, if concurrent use is required then sync locks
/// are necessary or some other RNG mechanism.
/// </summary>
public FastRandom Rng
{
get { return _rng; }
}
/// <summary>
/// Gets a Gaussian sampler associated with the factory.
/// Note. The provided RNG is not thread safe, if concurrent use is required then sync locks
/// are necessary or some other RNG mechanism.
/// </summary>
public ZigguratGaussianSampler GaussianSampler
{
get { return _gaussianSampler; }
}
/// <summary>
/// Gets some statistics assocated with the factory and NEAT genomes that it has spawned.
/// </summary>
public NeatGenomeStats Stats
{
get { return _stats; }
}
#endregion
#region Public Methods [NeatGenome Specific]
/// <summary>
/// Convenient method for obtaining the next genome ID.
/// </summary>
public uint NextGenomeId()
{
return _genomeIdGenerator.NextId;
}
/// <summary>
/// Convenient method for obtaining the next innovation ID.
/// </summary>
public uint NextInnovationId()
{
return _innovationIdGenerator.NextId;
}
/// <summary>
/// Convenient method for generating a new random connection weight that conforms to the connection
/// weight range defined by the NeatGenomeParameters.
/// </summary>
public double GenerateRandomConnectionWeight()
{
return ((_rng.NextDouble()*2.0) - 1.0) * _neatGenomeParamsCurrent.ConnectionWeightRange;
}
/// <summary>
/// Gets a variable from the Gaussian distribution with the provided mean and standard deviation.
/// </summary>
public double SampleGaussianDistribution(double mu, double sigma)
{
return _gaussianSampler.NextSample(mu, sigma);
}
/// <summary>
/// Create a genome with the provided internal state/definition data/objects.
/// Overridable method to allow alternative NeatGenome sub-classes to be used.
/// </summary>
public virtual NeatGenome CreateGenome(uint id,
uint birthGeneration,
NeuronGeneList neuronGeneList,
ConnectionGeneList connectionGeneList,
int inputNeuronCount,
int outputNeuronCount,
bool rebuildNeuronGeneConnectionInfo)
{
return new NeatGenome(this, id, birthGeneration, neuronGeneList, connectionGeneList,
inputNeuronCount, outputNeuronCount, rebuildNeuronGeneConnectionInfo);
}
/// <summary>
/// Create a copy of an existing NeatGenome, substituting in the specified ID and birth generation.
/// Overridable method to allow alternative NeatGenome sub-classes to be used.
/// </summary>
public virtual NeatGenome CreateGenomeCopy(NeatGenome copyFrom, uint id, uint birthGeneration)
{
return new NeatGenome(copyFrom, id, birthGeneration);
}
/// <summary>
/// Overridable method to allow alternative NeuronGene sub-classes to be used.
/// </summary>
public virtual NeuronGene CreateNeuronGene(uint innovationId, NodeType neuronType)
{
// NEAT uses the same activation function at each neuron; Hence we use an activationFnId of 0 here.
return new NeuronGene(innovationId, neuronType, 0);
}
#endregion
#region Inner Class [ConnectionDefinition]
struct ConnectionDefinition
{
public readonly uint _innovationId;
public readonly int _sourceNeuronIdx;
public readonly int _targetNeuronIdx;
public ConnectionDefinition(uint innovationId, int sourceNeuronIdx, int targetNeuronIdx)
{
_innovationId = innovationId;
_sourceNeuronIdx = sourceNeuronIdx;
_targetNeuronIdx = targetNeuronIdx;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
#define FEATURE_MANAGED_ETW
#if !ES_BUILD_STANDALONE
#define FEATURE_ACTIVITYSAMPLING
#endif
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
#else
#if PROJECTN
using NativeInterop = Interop.mincore;
using ManifestEtw = Interop.mincore;
using Win32Interop = Interop.mincore;
#else
using NativeInterop = UnsafeNativeMethods;
using ManifestEtw = UnsafeNativeMethods.ManifestEtw;
using Win32Interop = Win32Native;
#endif
#endif
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.ObjectModel;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
using System.Collections.Generic;
using System.Text;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
using System.Collections.Generic;
using System.Text;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
private byte[] providerMetadata;
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
public EventSource(
string eventSourceName)
: this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
{ }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
public EventSource(
string eventSourceName,
EventSourceSettings config)
: this(eventSourceName, config, null) { }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
/// itself but may be interprated the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
public EventSource(
string eventSourceName,
EventSourceSettings config,
params string[] traits)
: this(
eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
eventSourceName,
config, traits)
{
if (eventSourceName == null)
{
throw new ArgumentNullException("eventSourceName");
}
Contract.EndContractBlock();
}
/// <summary>
/// Writes an event with no fields and default options.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
[SecuritySafeCritical]
public unsafe void Write(string eventName)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event with no fields.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
[SecuritySafeCritical]
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
T data)
{
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is for use with extension methods that wish to efficiently
/// forward the options or data parameter without performing an extra copy.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is meant for clients that need to manipuate the activityId
/// and related ActivityId for the event.
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="activityId">
/// The GUID of the activity associated with this event.
/// </param>
/// <param name="relatedActivityId">
/// The GUID of another activity that is related to this activity, or Guid.Empty
/// if there is no related activity. Most commonly, the Start operation of a
/// new activity specifies a parent activity as its related activity.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref Guid activityId,
ref Guid relatedActivityId,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
{
this.WriteImpl(
eventName,
ref options,
data,
pActivity,
relatedActivityId == Guid.Empty ? null : pRelated,
SimpleEventTypes<T>.Instance);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// This method does a quick check on whether this event is enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null) </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
if (!this.IsEnabled())
{
return;
}
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// Attention: This API does not check whether the event is enabled or not.
/// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
/// not enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventTypes.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventTypes.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
if (nameInfo == null)
{
return;
}
identity = nameInfo.identity;
EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if (!ES_BUILD_PCL && !PROJECTN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
var info = eventTypes.typeInfos[i];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i]));
}
this.WriteEventRaw(
ref descriptor,
activityID,
childActivityID,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
/// <summary>
/// Writes an extended event, where the values of the event have already
/// been serialized in "data".
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="data">
/// The previously serialized values to include in the event. Must not be null.
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
[SecuritySafeCritical]
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
EventData* data)
{
if (!this.IsEnabled())
{
return;
}
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
// We make a descriptor for each EventData, and because we morph strings to counted strings
// we may have 2 for each arg, so we allocate enough for this.
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
// Until M3, we need to morph strings to a counted representation
// When TDH supports null terminated strings, we can remove this.
if (eventTypes.typeInfos[i].DataType == typeof(string))
{
// Write out the size of the string
descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size;
descriptors[numDescrs].m_Size = 2;
numDescrs++;
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
numDescrs++;
}
else
{
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size;
// old conventions for bool is 4 bytes, but meta-data assumes 1.
if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
descriptors[numDescrs].m_Size = 1;
numDescrs++;
}
}
this.WriteEventRaw(
ref descriptor,
activityID,
childActivityID,
numDescrs,
(IntPtr)descriptors);
}
}
}
[SecuritySafeCritical]
private unsafe void WriteImpl(
string eventName,
ref EventSourceOptions options,
object data,
Guid* pActivityId,
Guid* pRelatedActivityId,
TraceLoggingEventTypes eventTypes)
{
try
{
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if (!ES_BUILD_PCL && !PROJECTN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
EventOpcode opcode = (EventOpcode)descriptor.Opcode;
Guid activityId = Guid.Empty;
Guid relatedActivityId = Guid.Empty;
if (pActivityId == null && pRelatedActivityId == null &&
((options.ActivityOptions & EventActivityOptions.Disable) == 0))
{
if (opcode == EventOpcode.Start)
{
m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
}
else if (opcode == EventOpcode.Stop)
{
m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
}
if (activityId != Guid.Empty)
pActivityId = &activityId;
if (relatedActivityId != Guid.Empty)
pRelatedActivityId = &relatedActivityId;
}
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
var info = eventTypes.typeInfos[0];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data));
this.WriteEventRaw(
ref descriptor,
pActivityId,
pRelatedActivityId,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
// TODO enable filtering for listeners.
if (m_Dispatchers != null)
{
var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(ex);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(ex);
}
}
[SecurityCritical]
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventName = eventName;
eventCallbackArgs.m_keywords = (EventKeywords)eventDescriptor.Keywords;
eventCallbackArgs.m_opcode = (EventOpcode)eventDescriptor.Opcode;
eventCallbackArgs.m_tags = tags;
// Self described events do not have an id attached. We mark it internally with -1.
eventCallbackArgs.EventId = -1;
if (pActivityId != null)
eventCallbackArgs.RelatedActivityId = *pActivityId;
if (payload != null)
{
eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
}
DisptachToAllListeners(-1, pActivityId, eventCallbackArgs);
}
#if (!ES_BUILD_PCL && !PROJECTN)
[System.Runtime.ConstrainedExecution.ReliabilityContract(
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
[SecurityCritical]
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
DataCollector.ThreadInstance.Disable();
for (int i = 0; i != cPins; i++)
{
if (IntPtr.Zero != (IntPtr)pPins[i])
{
pPins[i].Free();
}
}
}
private void InitializeProviderMetadata()
{
if (m_traits != null)
{
List<byte> traitMetaData = new List<byte>(100);
for (int i = 0; i < m_traits.Length - 1; i += 2)
{
if (m_traits[i].StartsWith("ETW_"))
{
string etwTrait = m_traits[i].Substring(4);
byte traitNum;
if (!byte.TryParse(etwTrait, out traitNum))
{
if (etwTrait == "GROUP")
{
traitNum = 1;
}
else
{
#if PROJECTN
throw new ArgumentException(SR.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
#else
throw new ArgumentException(Environment.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
#endif
}
}
string value = m_traits[i + 1];
int lenPos = traitMetaData.Count;
traitMetaData.Add(0); // Emit size (to be filled in later)
traitMetaData.Add(0);
traitMetaData.Add(traitNum); // Emit Trait number
var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
}
}
providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
int startPos = providerMetadata.Length - traitMetaData.Count;
foreach (var b in traitMetaData)
providerMetadata[startPos++] = b;
}
else
providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
}
private static int AddValueToMetaData(List<byte> metaData, string value)
{
if (value.Length == 0)
return 0;
int startPos = metaData.Count;
char firstChar = value[0];
if (firstChar == '@')
metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
else if (firstChar == '{')
metaData.AddRange(new Guid(value).ToByteArray());
else if (firstChar == '#')
{
for (int i = 1; i < value.Length; i++)
{
if (value[i] != ' ') // Skp spaces between bytes.
{
if (!(i + 1 < value.Length))
{
#if PROJECTN
throw new ArgumentException(SR.GetResourceString("EvenHexDigits", null), "traits");
#else
throw new ArgumentException(Environment.GetResourceString("EvenHexDigits"), "traits");
#endif
}
metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
i++;
}
}
}
else if (' ' <= firstChar) // Is it alphabetic (excludes digits and most punctuation.
{
metaData.AddRange(Encoding.UTF8.GetBytes(value));
}
else
{
#if PROJECTN
throw new ArgumentException(SR.GetResourceString("IllegalValue", value), "traits");
#else
throw new ArgumentException(Environment.GetResourceString("IllegalValue", value), "traits");
#endif
}
return metaData.Count - startPos;
}
/// <summary>
/// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
/// </summary>
private static int HexDigit(char c)
{
if ('0' <= c && c <= '9')
{
return (c - '0');
}
if ('a' <= c)
{
c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case
}
if ('A' <= c && c <= 'F')
{
return (c - 'A' + 10);
}
#if PROJECTN
throw new ArgumentException(SR.Format("BadHexDigit", c), "traits");
#else
throw new ArgumentException(Environment.GetResourceString("BadHexDigit", c), "traits");
#endif
}
private NameInfo UpdateDescriptor(
string name,
TraceLoggingEventTypes eventInfo,
ref EventSourceOptions options,
out EventDescriptor descriptor)
{
NameInfo nameInfo = null;
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventInfo.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventInfo.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventInfo.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventInfo.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
identity = nameInfo.identity;
}
descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
return nameInfo;
}
}
}
| |
/* ====================================================================
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.Chart
{
using System;
using System.Text;
using NPOI.Util;
/**
* The series record describes the overall data for a series.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Glen Stampoultzis (glens at apache.org)
*/
public class SeriesRecord
: StandardRecord
{
public const short sid = 0x1003;
private short field_1_categoryDataType;
public const short CATEGORY_DATA_TYPE_DATES = 0;
public const short CATEGORY_DATA_TYPE_NUMERIC = 1;
public const short CATEGORY_DATA_TYPE_SEQUENCE = 2;
public const short CATEGORY_DATA_TYPE_TEXT = 3;
private short field_2_valuesDataType;
public const short VALUES_DATA_TYPE_DATES = 0;
public const short VALUES_DATA_TYPE_NUMERIC = 1;
public const short VALUES_DATA_TYPE_SEQUENCE = 2;
public const short VALUES_DATA_TYPE_TEXT = 3;
private short field_3_numCategories;
private short field_4_numValues;
private short field_5_bubbleSeriesType;
public const short BUBBLE_SERIES_TYPE_DATES = 0;
public const short BUBBLE_SERIES_TYPE_NUMERIC = 1;
public const short BUBBLE_SERIES_TYPE_SEQUENCE = 2;
public const short BUBBLE_SERIES_TYPE_TEXT = 3;
private short field_6_numBubbleValues;
public SeriesRecord()
{
}
/**
* Constructs a Series record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public SeriesRecord(RecordInputStream in1)
{
field_1_categoryDataType = in1.ReadShort();
field_2_valuesDataType = in1.ReadShort();
field_3_numCategories = in1.ReadShort();
field_4_numValues = in1.ReadShort();
field_5_bubbleSeriesType = in1.ReadShort();
field_6_numBubbleValues = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[SERIES]\n");
buffer.Append(" .categoryDataType = ")
.Append("0x").Append(HexDump.ToHex(CategoryDataType))
.Append(" (").Append(CategoryDataType).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .valuesDataType = ")
.Append("0x").Append(HexDump.ToHex(ValuesDataType))
.Append(" (").Append(ValuesDataType).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .numCategories = ")
.Append("0x").Append(HexDump.ToHex(NumCategories))
.Append(" (").Append(NumCategories).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .numValues = ")
.Append("0x").Append(HexDump.ToHex(NumValues))
.Append(" (").Append(NumValues).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .bubbleSeriesType = ")
.Append("0x").Append(HexDump.ToHex(BubbleSeriesType))
.Append(" (").Append(BubbleSeriesType).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .numBubbleValues = ")
.Append("0x").Append(HexDump.ToHex(NumBubbleValues))
.Append(" (").Append(NumBubbleValues).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append("[/SERIES]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_categoryDataType);
out1.WriteShort(field_2_valuesDataType);
out1.WriteShort(field_3_numCategories);
out1.WriteShort(field_4_numValues);
out1.WriteShort(field_5_bubbleSeriesType);
out1.WriteShort(field_6_numBubbleValues);
}
/**
* Size of record (exluding 4 byte header)
*/
protected override int DataSize
{
get { return 2 + 2 + 2 + 2 + 2 + 2; }
}
public override short Sid
{
get { return sid; }
}
public override Object Clone()
{
SeriesRecord rec = new SeriesRecord();
rec.field_1_categoryDataType = field_1_categoryDataType;
rec.field_2_valuesDataType = field_2_valuesDataType;
rec.field_3_numCategories = field_3_numCategories;
rec.field_4_numValues = field_4_numValues;
rec.field_5_bubbleSeriesType = field_5_bubbleSeriesType;
rec.field_6_numBubbleValues = field_6_numBubbleValues;
return rec;
}
/**
* Get the category data type field for the Series record.
*
* @return One of
* CATEGORY_DATA_TYPE_DATES
* CATEGORY_DATA_TYPE_NUMERIC
* CATEGORY_DATA_TYPE_SEQUENCE
* CATEGORY_DATA_TYPE_TEXT
*/
public short CategoryDataType
{
get
{
return field_1_categoryDataType;
}
set
{
this.field_1_categoryDataType = value;
}
}
/**
* Get the values data type field for the Series record.
*
* @return One of
* VALUES_DATA_TYPE_DATES
* VALUES_DATA_TYPE_NUMERIC
* VALUES_DATA_TYPE_SEQUENCE
* VALUES_DATA_TYPE_TEXT
*/
public short ValuesDataType
{
get
{
return field_2_valuesDataType;
}
set
{
this.field_2_valuesDataType = value;
}
}
/**
* Get the num categories field for the Series record.
*/
public short NumCategories
{
get
{
return field_3_numCategories;
}
set
{
this.field_3_numCategories = value;
}
}
/**
* Get the num values field for the Series record.
*/
public short NumValues
{
get
{
return field_4_numValues;
}
set
{
this.field_4_numValues = value;
}
}
/**
* Get the bubble series type field for the Series record.
*
* @return One of
* BUBBLE_SERIES_TYPE_DATES
* BUBBLE_SERIES_TYPE_NUMERIC
* BUBBLE_SERIES_TYPE_SEQUENCE
* BUBBLE_SERIES_TYPE_TEXT
*/
public short BubbleSeriesType
{
get
{
return field_5_bubbleSeriesType;
}
set
{
this.field_5_bubbleSeriesType = value;
}
}
/**
* Get the num bubble values field for the Series record.
*/
public short NumBubbleValues
{
get
{
return field_6_numBubbleValues;
}
set
{
this.field_6_numBubbleValues =value;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using static Google.Ads.GoogleAds.V10.Enums.BiddingStrategyTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example adds a cross-account bidding strategy to a manager account and attaches it
/// to a client customer's campaign. Also lists all the bidding strategies that are owned by the
/// manager and accessible by the customer.
/// Please read our guide pages more information on bidding strategies:
/// https://developers.google.com/google-ads/api/docs/campaigns/bidding/cross-account-strategies
/// </summary>
public class UseCrossAccountBiddingStrategy : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="UseCrossAccountBiddingStrategy"/>
/// example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads client customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads client customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// The ID of the account that owns the cross-account bidding strategy. This is
/// typically the ID of the manager account.
/// </summary>
[Option("managerCustomerId", Required = true, HelpText =
"The ID of the account that owns the cross-account bidding strategy. This is" +
"typically the ID of the manager account.")]
public long ManagerCustomerId { get; set; }
/// <summary>
/// The ID of the campaign owned by the customer ID to which the cross-account bidding
/// strategy will be attached.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"The ID of the campaign owned by the customer ID to which the cross-account " +
"bidding strategy will be attached.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
Parser.Default.ParseArguments<Options>(args).MapResult(
delegate(Options o)
{
options = o;
return 0;
}, delegate(IEnumerable<Error> errors)
{
// The Google Ads client customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// The manager customer ID.
options.ManagerCustomerId = long.Parse("INSERT_MANAGER_CUSTOMER_ID_HERE");
// The ID of the campaign owned by the customer ID to which the cross-account
// bidding strategy will be attached.
options.CampaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
return 0;
});
UseCrossAccountBiddingStrategy codeExample = new UseCrossAccountBiddingStrategy();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.ManagerCustomerId,
options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds a cross-account bidding strategy to a manager account and " +
"attaches it to a client customer's campaign. Also lists all the bidding strategies " +
"that are owned by the manager and accessible by the customer.\n" +
"Please read our guide pages more information on bidding strategies:" +
"https://developers.google.com/google-ads/api/docs/campaigns/bidding/cross-account-strategies";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads client customer ID for which the call is
/// made.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
/// <param name="campaignId">The ID of the campaign owned by the customer ID to which the
/// cross-account bidding strategy will be attached.</param>
public void Run(GoogleAdsClient client, long customerId, long managerCustomerId,
long campaignId)
{
try
{
string biddingStrategyResourceName =
CreateBiddingStrategy(client, managerCustomerId);
ListManagerOwnedBiddingStrategies(client, managerCustomerId);
ListCustomerAccessibleBiddingStrategies(client, customerId);
AttachCrossAccountBiddingStrategyToCampaign(client, customerId, campaignId,
biddingStrategyResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
// [START create_cross_account_strategy]
/// <summary>
/// Creates a new TargetSpend (Maximize Clicks) cross-account bidding strategy in the
/// specified manager account.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
/// <returns>The resource name of the newly created bidding strategy.</returns>
private string CreateBiddingStrategy(GoogleAdsClient client, long managerCustomerId)
{
BiddingStrategyServiceClient biddingStrategyServiceClient =
client.GetService(Services.V10.BiddingStrategyService);
// Create a portfolio bidding strategy.
// [START set_currency_code]
BiddingStrategy portfolioBiddingStrategy = new BiddingStrategy
{
Name = $"Maximize clicks #{ExampleUtilities.GetRandomString()}",
TargetSpend = new TargetSpend(),
// Set the currency of the new bidding strategy. If not provided, the bidding
// strategy uses the manager account's default currency.
CurrencyCode = "USD"
};
// [END set_currency_code]
// Send a create operation that will create the portfolio bidding strategy.
MutateBiddingStrategiesResponse mutateBiddingStrategiesResponse =
biddingStrategyServiceClient.MutateBiddingStrategies(managerCustomerId.ToString(),
new[]
{
new BiddingStrategyOperation
{
Create = portfolioBiddingStrategy
}
});
// Print and return the resource name of the newly created cross-account bidding
// strategy.
string biddingStrategyResourceName =
mutateBiddingStrategiesResponse.Results.First().ResourceName;
Console.WriteLine("Created cross-account bidding strategy " +
$"'{biddingStrategyResourceName}'.");
return biddingStrategyResourceName;
}
// [END create_cross_account_strategy]
// [START list_manager_strategies]
/// <summary>
/// Lists all cross-account bidding strategies in a specified manager account.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
private void ListManagerOwnedBiddingStrategies(GoogleAdsClient client,
long managerCustomerId)
{
GoogleAdsServiceClient googleAdsServiceClient =
client.GetService(Services.V10.GoogleAdsService);
// Create a GAQL query that will retrieve all cross-account bidding strategies.
string query = @"
SELECT
bidding_strategy.id,
bidding_strategy.name,
bidding_strategy.type,
bidding_strategy.currency_code
FROM bidding_strategy";
// Issue a streaming search request, then iterate through and print the results.
googleAdsServiceClient.SearchStream(managerCustomerId.ToString(), query,
delegate(SearchGoogleAdsStreamResponse resp)
{
Console.WriteLine("Cross-account bid strategies in manager account " +
$"{managerCustomerId}:");
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
BiddingStrategy biddingStrategy = googleAdsRow.BiddingStrategy;
Console.WriteLine($"\tID: {biddingStrategy.Id}\n" +
$"\tName: {biddingStrategy.Name}\n" +
"\tStrategy type: " +
$"{Enum.GetName(typeof(BiddingStrategyType), biddingStrategy.Type)}\n" +
$"\tCurrency: {biddingStrategy.CurrencyCode}\n\n");
}
}
);
}
// [END list_manager_strategies]
// [START list_accessible_strategies]
/// <summary>
/// Lists all bidding strategies available to specified client customer account. This
/// includes both portfolio bidding strategies owned by the client customer account and
/// cross-account bidding strategies shared by any of its managers.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads client customer ID for which the call is
/// made.</param>
private void ListCustomerAccessibleBiddingStrategies(GoogleAdsClient client,
long customerId)
{
GoogleAdsServiceClient googleAdsServiceClient =
client.GetService(Services.V10.GoogleAdsService);
// Create a GAQL query that will retrieve all accessible bidding strategies.
string query = @"
SELECT
accessible_bidding_strategy.resource_name,
accessible_bidding_strategy.id,
accessible_bidding_strategy.name,
accessible_bidding_strategy.type,
accessible_bidding_strategy.owner_customer_id,
accessible_bidding_strategy.owner_descriptive_name
FROM accessible_bidding_strategy";
// Uncomment the following WHERE clause addition to the query to filter results to
// *only* cross-account bidding strategies shared with the current customer by a manager
// (and not also include the current customer's portfolio bidding strategies).
// query += $" WHERE accessible_bidding_strategy.owner_customer_id != {customerId}";
// Issue a streaming search request, then iterate through and print the results.
googleAdsServiceClient.SearchStream(customerId.ToString(), query,
delegate(SearchGoogleAdsStreamResponse resp)
{
Console.WriteLine($"All bid strategies accessible by account {customerId}:");
foreach (GoogleAdsRow googleAdsRow in resp.Results)
{
AccessibleBiddingStrategy biddingStrategy =
googleAdsRow.AccessibleBiddingStrategy;
Console.WriteLine($"\tID: {biddingStrategy.Id}\n" +
$"\tName: {biddingStrategy.Name}\n" +
$"\tStrategy type: {biddingStrategy.Type.ToString()}\n" +
$"\tOwner customer ID: {biddingStrategy.OwnerCustomerId}\n" +
$"\tOwner description: {biddingStrategy.OwnerDescriptiveName}\n\n");
}
}
);
}
// [END list_accessible_strategies]
// [START attach_strategy]
/// <summary>
/// Attaches a specified cross-account bidding strategy to a campaign owned by a specified
/// client customer account.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads client customer ID for which the call is
/// made.</param>
/// <param name="campaignId">The ID of the campaign owned by the customer ID to which the
/// cross-account bidding strategy will be attached.</param>
/// <param name="biddingStrategyResourceName">A cross-account bidding strategy resource
/// name.</param>
private void AttachCrossAccountBiddingStrategyToCampaign(GoogleAdsClient client,
long customerId, long campaignId, string biddingStrategyResourceName)
{
CampaignServiceClient campaignServiceClient =
client.GetService(Services.V10.CampaignService);
Campaign campaign = new Campaign
{
ResourceName = ResourceNames.Campaign(customerId, campaignId),
BiddingStrategy = biddingStrategyResourceName
};
// Mutate the campaign and print the resource name of the updated campaign.
MutateCampaignsResponse mutateCampaignsResponse =
campaignServiceClient.MutateCampaigns(customerId.ToString(), new[]
{
new CampaignOperation
{
Update = campaign,
UpdateMask = FieldMasks.AllSetFieldsOf(campaign)
}
});
Console.WriteLine("Updated campaign with resource name " +
$"'{mutateCampaignsResponse.Results.First().ResourceName}'.");
}
// [END attach_strategy]
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Client
{
/// <summary>
/// <para>Signals an error in the HTTP protocol. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/ClientProtocolException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/ClientProtocolException", AccessFlags = 33)]
public partial class ClientProtocolException : global::System.IO.IOException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public ClientProtocolException() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public ClientProtocolException(string @string) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/Throwable;)V", AccessFlags = 1)]
public ClientProtocolException(global::System.Exception exception) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public ClientProtocolException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A handler for determining if the given execution context is user specific or not. The token object returned by this handler is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if the context does not contain any resources or details specific to the current user. </para><para>The user token will be used to ensure that user specific resouces will not shared with or reused by other users.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/UserTokenHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/UserTokenHandler", AccessFlags = 1537)]
public partial interface IUserTokenHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>The token object returned by this method is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if it is not.</para><para></para>
/// </summary>
/// <returns>
/// <para>user token that uniquely identifies the user or <code>null</null> if the context is not user specific. </code></para>
/// </returns>
/// <java-name>
/// getUserToken
/// </java-name>
[Dot42.DexImport("getUserToken", "(Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025)]
object GetUserToken(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals a circular redirect</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/CircularRedirectException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/CircularRedirectException", AccessFlags = 33)]
public partial class CircularRedirectException : global::Org.Apache.Http.Client.RedirectException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new CircularRedirectException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CircularRedirectException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new CircularRedirectException with the specified detail message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public CircularRedirectException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new CircularRedirectException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public CircularRedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract credentials provider.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/CredentialsProvider
/// </java-name>
[Dot42.DexImport("org/apache/http/client/CredentialsProvider", AccessFlags = 1537)]
public partial interface ICredentialsProvider
/* scope: __dot42__ */
{
/// <summary>
/// <para>Sets the credentials for the given authentication scope. Any previous credentials for the given scope will be overwritten.</para><para><para>getCredentials(AuthScope) </para></para>
/// </summary>
/// <java-name>
/// setCredentials
/// </java-name>
[Dot42.DexImport("setCredentials", "(Lorg/apache/http/auth/AuthScope;Lorg/apache/http/auth/Credentials;)V", AccessFlags = 1025)]
void SetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope, global::Org.Apache.Http.Auth.ICredentials credentials) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Get the credentials for the given authentication scope.</para><para><para>setCredentials(AuthScope, Credentials) </para></para>
/// </summary>
/// <returns>
/// <para>the credentials</para>
/// </returns>
/// <java-name>
/// getCredentials
/// </java-name>
[Dot42.DexImport("getCredentials", "(Lorg/apache/http/auth/AuthScope;)Lorg/apache/http/auth/Credentials;", AccessFlags = 1025)]
global::Org.Apache.Http.Auth.ICredentials GetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Clears all credentials. </para>
/// </summary>
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1025)]
void Clear() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A handler for determining if an HTTP request should be redirected to a new location in response to an HTTP response received from the target server.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/RedirectHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/RedirectHandler", AccessFlags = 1537)]
public partial interface IRedirectHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Determines if a request should be redirected to a new location given the response from the target server.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request should be redirected, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isRedirectRequested
/// </java-name>
[Dot42.DexImport("isRedirectRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)]
bool IsRedirectRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Determines the location request is expected to be redirected to given the response from the target server and the current request execution context.</para><para></para>
/// </summary>
/// <returns>
/// <para>redirect URI </para>
/// </returns>
/// <java-name>
/// getLocationURI
/// </java-name>
[Dot42.DexImport("getLocationURI", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/net/U" +
"RI;", AccessFlags = 1025)]
global::System.Uri GetLocationURI(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>A client-side request director. The director decides which steps are necessary to execute a request. It establishes connections and optionally processes redirects and authentication challenges. The director may therefore generate and send a sequence of requests in order to execute one initial request.</para><para><br></br><b>Note:</b> It is most likely that implementations of this interface will allocate connections, and return responses that depend on those connections for reading the response entity. Such connections MUST be released, but that is out of the scope of a request director.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/RequestDirector
/// </java-name>
[Dot42.DexImport("org/apache/http/client/RequestDirector", AccessFlags = 1537)]
public partial interface IRequestDirector
/* scope: __dot42__ */
{
/// <summary>
/// <para>Executes a request. <br></br><b>Note:</b> For the time being, a new director is instantiated for each request. This is the same behavior as for <code>HttpMethodDirector</code> in HttpClient 3.</para><para></para>
/// </summary>
/// <returns>
/// <para>the final response to the request. This is never an intermediate response with status code 1xx.</para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals failure to retry the request due to non-repeatable request entity.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/NonRepeatableRequestException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/NonRepeatableRequestException", AccessFlags = 33)]
public partial class NonRepeatableRequestException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new NonRepeatableEntityException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public NonRepeatableRequestException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NonRepeatableEntityException with the specified detail message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public NonRepeatableRequestException(string message) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>A handler for determining if an HttpRequest should be retried after a recoverable exception during execution.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/HttpRequestRetryHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/HttpRequestRetryHandler", AccessFlags = 1537)]
public partial interface IHttpRequestRetryHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Determines if a method should be retried after an IOException occurs during execution.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the method should be retried, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// retryRequest
/// </java-name>
[Dot42.DexImport("retryRequest", "(Ljava/io/IOException;ILorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)]
bool RetryRequest(global::System.IO.IOException exception, int executionCount, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/AuthenticationHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/AuthenticationHandler", AccessFlags = 1537)]
public partial interface IAuthenticationHandler
/* scope: __dot42__ */
{
/// <java-name>
/// isAuthenticationRequested
/// </java-name>
[Dot42.DexImport("isAuthenticationRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)]
bool IsAuthenticationRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// getChallenges
/// </java-name>
[Dot42.DexImport("getChallenges", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" +
"Map;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" +
"Map<Ljava/lang/String;Lorg/apache/http/Header;>;")]
global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> GetChallenges(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <java-name>
/// selectScheme
/// </java-name>
[Dot42.DexImport("selectScheme", "(Ljava/util/Map;Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpConte" +
"xt;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1025, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/Header;>;Lorg/apache/http/Http" +
"Response;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/auth/AuthScheme" +
";")]
global::Org.Apache.Http.Auth.IAuthScheme SelectScheme(global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> challenges, global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Handler that encapsulates the process of generating a response object from a HttpResponse.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/ResponseHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/client/ResponseHandler", AccessFlags = 1537, Signature = "<T:Ljava/lang/Object;>Ljava/lang/Object;")]
public partial interface IResponseHandler<T>
/* scope: __dot42__ */
{
/// <summary>
/// <para>Processes an HttpResponse and returns some value corresponding to that response.</para><para></para>
/// </summary>
/// <returns>
/// <para>A value determined by the response</para>
/// </returns>
/// <java-name>
/// handleResponse
/// </java-name>
[Dot42.DexImport("handleResponse", "(Lorg/apache/http/HttpResponse;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;)TT;")]
T HandleResponse(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/HttpClient
/// </java-name>
[Dot42.DexImport("org/apache/http/client/HttpClient", AccessFlags = 1537)]
public partial interface IHttpClient
/* scope: __dot42__ */
{
/// <summary>
/// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the default parameters </para>
/// </returns>
/// <java-name>
/// getParams
/// </java-name>
[Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
global::Org.Apache.Http.Params.IHttpParams GetParams() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Obtains the connection manager used by this client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the connection manager </para>
/// </returns>
/// <java-name>
/// getConnectionManager
/// </java-name>
[Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1025)]
global::Org.Apache.Http.Conn.IClientConnectionManager GetConnectionManager() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the default context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/protocol/HttpCon" +
"text;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;)Lorg/apache/http/HttpRes" +
"ponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost request, global::Org.Apache.Http.IHttpRequest context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" +
"/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)]
global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" +
"andler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" +
"/http/client/ResponseHandler<+TT;>;)TT;")]
T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" +
"andler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" +
"/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext;)TT;")]
T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest target, global::Org.Apache.Http.Client.IResponseHandler<T> request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" +
"esponseHandler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" +
"g/apache/http/client/ResponseHandler<+TT;>;)TT;")]
T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Executes a request to the target using the given context and processes the response using the given response handler.</para><para></para>
/// </summary>
/// <returns>
/// <para>the response object as generated by the response handler. </para>
/// </returns>
/// <java-name>
/// execute
/// </java-name>
[Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" +
"esponseHandler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" +
"g/apache/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext" +
";)TT;")]
T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> responseHandler, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals a non 2xx HTTP response. </para>
/// </summary>
/// <java-name>
/// org/apache/http/client/HttpResponseException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/HttpResponseException", AccessFlags = 33)]
public partial class HttpResponseException : global::Org.Apache.Http.Client.ClientProtocolException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(ILjava/lang/String;)V", AccessFlags = 1)]
public HttpResponseException(int statusCode, string s) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getStatusCode
/// </java-name>
[Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)]
public virtual int GetStatusCode() /* MethodBuilder.Create */
{
return default(int);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal HttpResponseException() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getStatusCode
/// </java-name>
public int StatusCode
{
[Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)]
get{ return GetStatusCode(); }
}
}
/// <summary>
/// <para>Signals violation of HTTP specification caused by an invalid redirect</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/RedirectException
/// </java-name>
[Dot42.DexImport("org/apache/http/client/RedirectException", AccessFlags = 33)]
public partial class RedirectException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new RedirectException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RedirectException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new RedirectException with the specified detail message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public RedirectException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new RedirectException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public RedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract cookie store.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/CookieStore
/// </java-name>
[Dot42.DexImport("org/apache/http/client/CookieStore", AccessFlags = 1537)]
public partial interface ICookieStore
/* scope: __dot42__ */
{
/// <summary>
/// <para>Adds an HTTP cookie, replacing any existing equivalent cookies. If the given cookie has already expired it will not be added, but existing values will still be removed.</para><para></para>
/// </summary>
/// <java-name>
/// addCookie
/// </java-name>
[Dot42.DexImport("addCookie", "(Lorg/apache/http/cookie/Cookie;)V", AccessFlags = 1025)]
void AddCookie(global::Org.Apache.Http.Cookie.ICookie cookie) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns all cookies contained in this store.</para><para></para>
/// </summary>
/// <returns>
/// <para>all cookies </para>
/// </returns>
/// <java-name>
/// getCookies
/// </java-name>
[Dot42.DexImport("getCookies", "()Ljava/util/List;", AccessFlags = 1025, Signature = "()Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;")]
global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> GetCookies() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Removes all of cookies in this store that have expired by the specified date.</para><para></para>
/// </summary>
/// <returns>
/// <para>true if any cookies were purged. </para>
/// </returns>
/// <java-name>
/// clearExpired
/// </java-name>
[Dot42.DexImport("clearExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)]
bool ClearExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Clears all cookies. </para>
/// </summary>
/// <java-name>
/// clear
/// </java-name>
[Dot42.DexImport("clear", "()V", AccessFlags = 1025)]
void Clear() /* MethodBuilder.Create */ ;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
public static class Int16Tests
{
[Fact]
public static void Ctor_Empty()
{
var i = new short();
Assert.Equal(0, i);
}
[Fact]
public static void Ctor_Value()
{
short i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void MaxValue()
{
Assert.Equal(0x7FFF, short.MaxValue);
}
[Fact]
public static void MinValue()
{
Assert.Equal(unchecked((short)0x8000), short.MinValue);
}
[Theory]
[InlineData((short)234, (short)234, 0)]
[InlineData((short)234, short.MinValue, 1)]
[InlineData((short)234, (short)-123, 1)]
[InlineData((short)234, (short)0, 1)]
[InlineData((short)234, (short)123, 1)]
[InlineData((short)234, (short)456, -1)]
[InlineData((short)234, short.MaxValue, -1)]
[InlineData((short)-234, (short)-234, 0)]
[InlineData((short)-234, (short)234, -1)]
[InlineData((short)-234, (short)-432, 1)]
[InlineData((short)234, null, 1)]
public static void CompareTo(short i, object obj, int expected)
{
if (obj is short)
{
Assert.Equal(expected, Math.Sign(i.CompareTo((short)obj)));
}
IComparable comparable = i;
Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
}
[Fact]
public static void CompareTo_ObjectNotShort_ThrowsArgumentException()
{
IComparable comparable = (short)234;
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a short
AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a short
}
[Theory]
[InlineData((short)789, (short)789, true)]
[InlineData((short)789, (short)-789, false)]
[InlineData((short)789, (short)0, false)]
[InlineData((short)0, (short)0, true)]
[InlineData((short)-789, (short)-789, true)]
[InlineData((short)-789, (short)789, false)]
[InlineData((short)789, null, false)]
[InlineData((short)789, "789", false)]
[InlineData((short)789, 789, false)]
public static void Equals(short i1, object obj, bool expected)
{
if (obj is short)
{
short i2 = (short)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
}
Assert.Equal(expected, i1.Equals(obj));
}
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
yield return new object[] { short.MinValue, "G", emptyFormat, "-32768" };
yield return new object[] { (short)-4567, "G", emptyFormat, "-4567" };
yield return new object[] { (short)0, "G", emptyFormat, "0" };
yield return new object[] { (short)4567, "G", emptyFormat, "4567" };
yield return new object[] { short.MaxValue, "G", emptyFormat, "32767" };
yield return new object[] { (short)0x2468, "x", emptyFormat, "2468" };
yield return new object[] { (short)-0x2468, "x", emptyFormat, "DB98" };
yield return new object[] { (short)2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) };
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.NegativeSign = "#";
customFormat.NumberDecimalSeparator = "~";
customFormat.NumberGroupSeparator = "*";
yield return new object[] { (short)-2468, "N", customFormat, "#2*468~00" };
yield return new object[] { (short)2468, "N", customFormat, "2*468~00" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public static void ToString(short i, string format, IFormatProvider provider, string expected)
{
// Format is case insensitive
string upperFormat = format.ToUpperInvariant();
string lowerFormat = format.ToLowerInvariant();
string upperExpected = expected.ToUpperInvariant();
string lowerExpected = expected.ToLowerInvariant();
bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo);
if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G")
{
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString());
Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
}
Assert.Equal(upperExpected, i.ToString(provider));
}
if (isDefaultProvider)
{
Assert.Equal(upperExpected, i.ToString(upperFormat));
Assert.Equal(lowerExpected, i.ToString(lowerFormat));
Assert.Equal(upperExpected, i.ToString(upperFormat, null));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
}
Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
}
[Fact]
public static void ToString_InvalidFormat_ThrowsFormatException()
{
short i = 123;
Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format
Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format
}
public static IEnumerable<object[]> Parse_Valid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo emptyFormat = new NumberFormatInfo();
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
yield return new object[] { "-32768", defaultStyle, null, (short)-32768 };
yield return new object[] { "-123", defaultStyle, null, (short)-123 };
yield return new object[] { "0", defaultStyle, null, (short)0 };
yield return new object[] { "123", defaultStyle, null, (short)123 };
yield return new object[] { "+123", defaultStyle, null, (short)123 };
yield return new object[] { " 123 ", defaultStyle, null, (short)123 };
yield return new object[] { "32767", defaultStyle, null, (short)32767 };
yield return new object[] { "123", NumberStyles.HexNumber, null, (short)0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, null, (short)0xabc };
yield return new object[] { "ABC", NumberStyles.HexNumber, null, (short)0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, null, (short)1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, (short)-123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyFormat, (short)123 };
yield return new object[] { "123", NumberStyles.Any, emptyFormat, (short)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyFormat, (short)0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, customFormat, (short)1000 };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Parse(string value, NumberStyles style, IFormatProvider provider, short expected)
{
short result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.True(short.TryParse(value, out result));
Assert.Equal(expected, result);
Assert.Equal(expected, short.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Equal(expected, short.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.True(short.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(expected, result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Equal(expected, short.Parse(value, style));
}
Assert.Equal(expected, short.Parse(value, style, provider ?? new NumberFormatInfo()));
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
NumberStyles defaultStyle = NumberStyles.Integer;
NumberFormatInfo customFormat = new NumberFormatInfo();
customFormat.CurrencySymbol = "$";
customFormat.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, null, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, null, typeof(FormatException) };
yield return new object[] { " \t \n \r ", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, null, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, null, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, null, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, null, typeof(FormatException) }; // Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, null, typeof(FormatException) }; // Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, null, typeof(FormatException) }; // Decimal
yield return new object[] { "+-123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "-+123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) };
yield return new object[] { "- 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "+ 123", defaultStyle, null, typeof(FormatException) };
yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; // Hex value
yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, customFormat, typeof(FormatException) }; // Decimal
yield return new object[] { "-32769", defaultStyle, null, typeof(OverflowException) }; // < min value
yield return new object[] { "32768", defaultStyle, null, typeof(OverflowException) }; // > max value
yield return new object[] { "2147483648", defaultStyle, null, typeof(OverflowException) }; // Internally, Parse pretends we are inputting an Int32, so this overflows
yield return new object[] { "FFFFFFFF", NumberStyles.HexNumber, null, typeof(OverflowException) }; // Hex number < 0
yield return new object[] { "10000", NumberStyles.HexNumber, null, typeof(OverflowException) }; // Hex number > max value
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
short result;
// If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.False(short.TryParse(value, out result));
Assert.Equal(default(short), result);
Assert.Throws(exceptionType, () => short.Parse(value));
// If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (provider != null)
{
Assert.Throws(exceptionType, () => short.Parse(value, provider));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.False(short.TryParse(value, style, provider ?? new NumberFormatInfo(), out result));
Assert.Equal(default(short), result);
// If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (provider == null)
{
Assert.Throws(exceptionType, () => short.Parse(value, style));
}
Assert.Throws(exceptionType, () => short.Parse(value, style, provider ?? new NumberFormatInfo()));
}
[Theory]
[InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)]
[InlineData(unchecked((NumberStyles)0xFFFFFC00))]
public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style)
{
short result = 0;
Assert.Throws<ArgumentException>(() => short.TryParse("1", style, null, out result));
Assert.Equal(default(short), result);
Assert.Throws<ArgumentException>(() => short.Parse("1", style));
Assert.Throws<ArgumentException>(() => short.Parse("1", style, null));
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections;
using System.Collections.Generic;
namespace Encog.Util.KMeans
{
/// <summary>
/// Generic KMeans clustering object.
/// </summary>
/// <typeparam name="TK">The type to cluster</typeparam>
public class KMeansUtil<TK> where TK : class
{
/// <summary>
/// The clusters.
/// </summary>
private readonly IList<Cluster<TK>> _clusters;
/// <summary>
/// The number of clusters.
/// </summary>
private readonly int _k;
/// <summary>
/// Construct the clusters. Call process to perform the cluster.
/// </summary>
/// <param name="theK">The number of clusters.</param>
/// <param name="theElements">The elements to cluster.</param>
public KMeansUtil(int theK, IList theElements)
{
_k = theK;
_clusters = new List<Cluster<TK>>(theK);
InitRandomClusters(theElements);
}
/// <summary>
/// The number of clusters.
/// </summary>
public int Count
{
get { return _clusters.Count; }
}
/// <summary>
/// Create random clusters.
/// </summary>
/// <param name="elements">The elements to cluster.</param>
private void InitRandomClusters(IList elements)
{
int clusterIndex = 0;
int elementIndex = 0;
// first simply fill out the clusters, until we run out of clusters
while ((elementIndex < elements.Count) && (clusterIndex < _k)
&& (elements.Count - elementIndex > _k - clusterIndex))
{
var element = elements[elementIndex];
bool added = false;
// if this element is identical to another, add it to this cluster
for (int i = 0; i < clusterIndex; i++)
{
Cluster<TK> cluster = _clusters[i];
if (cluster.Centroid().Distance((TK) element) == 0)
{
cluster.Add(element as TK);
added = true;
break;
}
}
if (!added)
{
_clusters.Add(new Cluster<TK>(elements[elementIndex] as TK));
clusterIndex++;
}
elementIndex++;
}
// create
while (clusterIndex < _k && elementIndex < elements.Count)
{
_clusters.Add(new Cluster<TK>(elements[elementIndex] as TK));
elementIndex++;
clusterIndex++;
}
// handle case where there were not enough clusters created,
// create empty ones.
while (clusterIndex < _k)
{
_clusters.Add(new Cluster<TK>());
clusterIndex++;
}
// otherwise, handle case where there were still unassigned elements
// add them to the nearest clusters.
while (elementIndex < elements.Count)
{
var element = elements[elementIndex];
NearestCluster(element as TK).Add(element as TK);
elementIndex++;
}
}
/// <summary>
/// Perform the cluster.
/// </summary>
public void Process()
{
bool done;
do
{
done = true;
for (int i = 0; i < _k; i++)
{
Cluster<TK> thisCluster = _clusters[i];
var thisElements = thisCluster.Contents as List<TK>;
for (int j = 0; j < thisElements.Count; j++)
{
TK thisElement = thisElements[j];
// don't make a cluster empty
if (thisCluster.Centroid().Distance(thisElement) > 0)
{
Cluster<TK> nearestCluster = NearestCluster(thisElement);
// move to nearer cluster
if (thisCluster != nearestCluster)
{
nearestCluster.Add(thisElement);
thisCluster.Remove(j);
done = false;
}
}
}
}
} while (!done);
}
/// <summary>
/// Find the nearest cluster to the element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The nearest cluster.</returns>
private Cluster<TK> NearestCluster(TK element)
{
double distance = Double.PositiveInfinity;
Cluster<TK> result = null;
foreach (Cluster<TK> t in _clusters)
{
double thisDistance = t.Centroid().Distance(element);
if (distance > thisDistance)
{
distance = thisDistance;
result = t;
}
}
return result;
}
/// <summary>
/// Get a cluster by index.
/// </summary>
/// <param name="index">The index to get.</param>
/// <returns>The cluster.</returns>
public ICollection<TK> Get(int index)
{
return _clusters[index].Contents;
}
/// <summary>
/// Get a cluster by index.
/// </summary>
/// <param name="i">The index to get.</param>
/// <returns>The cluster.</returns>
public Cluster<TK> GetCluster(int i)
{
return _clusters[i];
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This RegexRunner class is a base class for compiled regex code.
// Implementation notes:
// It provides the driver code that call's the subclass's Go()
// method for either scanning or direct execution.
//
// It also maintains memory allocation for the backtracking stack,
// the grouping stack and the longjump crawlstack, and provides
// methods to push new subpattern match results into (or remove
// backtracked results from) the Match instance.
using System.Diagnostics;
using System.Globalization;
namespace System.Text.RegularExpressions
{
public abstract class RegexRunner
{
protected internal int runtextbeg; // beginning of text to search
protected internal int runtextend; // end of text to search
protected internal int runtextstart; // starting point for search
protected internal string runtext; // text to search
protected internal int runtextpos; // current position in text
protected internal int[] runtrack; // The backtracking stack. Opcodes use this to store data regarding
protected internal int runtrackpos; // what they have matched and where to backtrack to. Each "frame" on
// the stack takes the form of [CodePosition Data1 Data2...], where
// CodePosition is the position of the current opcode and
// the data values are all optional. The CodePosition can be negative, and
// these values (also called "back2") are used by the BranchMark family of opcodes
// to indicate whether they are backtracking after a successful or failed
// match.
// When we backtrack, we pop the CodePosition off the stack, set the current
// instruction pointer to that code position, and mark the opcode
// with a backtracking flag ("Back"). Each opcode then knows how to
// handle its own data.
protected internal int[] runstack; // This stack is used to track text positions across different opcodes.
protected internal int runstackpos; // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark
// pair. SetMark records the text position before we match a*b. Then
// CaptureMark uses that position to figure out where the capture starts.
// Opcodes which push onto this stack are always paired with other opcodes
// which will pop the value from it later. A successful match should mean
// that this stack is empty.
protected internal int[] runcrawl; // The crawl stack is used to keep track of captures. Every time a group
protected internal int runcrawlpos; // has a capture, we push its group number onto the runcrawl stack. In
// the case of a balanced match, we push BOTH groups onto the stack.
protected internal int runtrackcount; // count of states that may do backtracking
protected internal Match runmatch; // result object
protected internal Regex runregex; // regex object
private int _timeout; // timeout in milliseconds (needed for actual)
private bool _ignoreTimeout;
private int _timeoutOccursAt;
// We have determined this value in a series of experiments where x86 retail
// builds (ono-lab-optimized) were run on different pattern/input pairs. Larger values
// of TimeoutCheckFrequency did not tend to increase performance; smaller values
// of TimeoutCheckFrequency tended to slow down the execution.
private const int TimeoutCheckFrequency = 1000;
private int _timeoutChecksToSkip;
protected internal RegexRunner() { }
/// <summary>
/// Scans the string to find the first match. Uses the Match object
/// both to feed text in and as a place to store matches that come out.
///
/// All the action is in the abstract Go() method defined by subclasses. Our
/// responsibility is to load up the class members (as done here) before
/// calling Go.
///
/// The optimizer can compute a set of candidate starting characters,
/// and we could use a separate method Skip() that will quickly scan past
/// any characters that we know can't match.
/// </summary>
protected internal Match Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick)
{
return Scan(regex, text, textbeg, textend, textstart, prevlen, quick, regex.MatchTimeout);
}
protected internal Match Scan(Regex regex, string text, int textbeg, int textend, int textstart, int prevlen, bool quick, TimeSpan timeout)
{
int bump;
int stoppos;
bool initted = false;
// We need to re-validate timeout here because Scan is historically protected and
// thus there is a possibility it is called from user code:
Regex.ValidateMatchTimeout(timeout);
_ignoreTimeout = (Regex.InfiniteMatchTimeout == timeout);
_timeout = _ignoreTimeout
? (int)Regex.InfiniteMatchTimeout.TotalMilliseconds
: (int)(timeout.TotalMilliseconds + 0.5); // Round
runregex = regex;
runtext = text;
runtextbeg = textbeg;
runtextend = textend;
runtextstart = textstart;
bump = runregex.RightToLeft ? -1 : 1;
stoppos = runregex.RightToLeft ? runtextbeg : runtextend;
runtextpos = textstart;
// If previous match was empty or failed, advance by one before matching
if (prevlen == 0)
{
if (runtextpos == stoppos)
return Match.Empty;
runtextpos += bump;
}
StartTimeoutWatch();
for (; ;)
{
#if DEBUG
if (runregex.Debug)
{
Debug.WriteLine("");
Debug.WriteLine("Search range: from " + runtextbeg.ToString(CultureInfo.InvariantCulture) + " to " + runtextend.ToString(CultureInfo.InvariantCulture));
Debug.WriteLine("Firstchar search starting at " + runtextpos.ToString(CultureInfo.InvariantCulture) + " stopping at " + stoppos.ToString(CultureInfo.InvariantCulture));
}
#endif
if (FindFirstChar())
{
CheckTimeout();
if (!initted)
{
InitMatch();
initted = true;
}
#if DEBUG
if (runregex.Debug)
{
Debug.WriteLine("Executing engine starting at " + runtextpos.ToString(CultureInfo.InvariantCulture));
Debug.WriteLine("");
}
#endif
Go();
if (runmatch._matchcount[0] > 0)
{
// We'll return a match even if it touches a previous empty match
return TidyMatch(quick);
}
// reset state for another go
runtrackpos = runtrack.Length;
runstackpos = runstack.Length;
runcrawlpos = runcrawl.Length;
}
// failure!
if (runtextpos == stoppos)
{
TidyMatch(true);
return Match.Empty;
}
// Recognize leading []* and various anchors, and bump on failure accordingly
// Bump by one and start again
runtextpos += bump;
}
// We never get here
}
private void StartTimeoutWatch()
{
if (_ignoreTimeout)
return;
_timeoutChecksToSkip = TimeoutCheckFrequency;
// We are using Environment.TickCount and not Timewatch for performance reasons.
// Environment.TickCount is an int that cycles. We intentionally let timeoutOccursAt
// overflow it will still stay ahead of Environment.TickCount for comparisons made
// in DoCheckTimeout():
unchecked
{
_timeoutOccursAt = Environment.TickCount + _timeout;
}
}
protected void CheckTimeout()
{
if (_ignoreTimeout)
return;
DoCheckTimeout();
}
private void DoCheckTimeout()
{
if (--_timeoutChecksToSkip != 0)
return;
_timeoutChecksToSkip = TimeoutCheckFrequency;
// Note that both, Environment.TickCount and timeoutOccursAt are ints and can overflow and become negative.
// See the comment in StartTimeoutWatch().
int currentMillis = Environment.TickCount;
if (currentMillis < _timeoutOccursAt)
return;
if (0 > _timeoutOccursAt && 0 < currentMillis)
return;
#if DEBUG
if (runregex.Debug)
{
Debug.WriteLine("");
Debug.WriteLine("RegEx match timeout occurred!");
Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(_timeout).ToString());
Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency);
Debug.WriteLine("Search pattern: " + runregex.pattern);
Debug.WriteLine("Input: " + runtext);
Debug.WriteLine("About to throw RegexMatchTimeoutException.");
}
#endif
throw new RegexMatchTimeoutException(runtext, runregex.pattern, TimeSpan.FromMilliseconds(_timeout));
}
/// <summary>
/// The responsibility of Go() is to run the regular expression at
/// runtextpos and call Capture() on all the captured subexpressions,
/// then to leave runtextpos at the ending position. It should leave
/// runtextpos where it started if there was no match.
/// </summary>
protected abstract void Go();
/// <summary>
/// The responsibility of FindFirstChar() is to advance runtextpos
/// until it is at the next position which is a candidate for the
/// beginning of a successful match.
/// </summary>
protected abstract bool FindFirstChar();
/// <summary>
/// InitTrackCount must initialize the runtrackcount field; this is
/// used to know how large the initial runtrack and runstack arrays
/// must be.
/// </summary>
protected abstract void InitTrackCount();
/// <summary>
/// Initializes all the data members that are used by Go()
/// </summary>
private void InitMatch()
{
// Use a hashtabled Match object if the capture numbers are sparse
if (runmatch == null)
{
if (runregex.caps != null)
runmatch = new MatchSparse(runregex, runregex.caps, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
else
runmatch = new Match(runregex, runregex.capsize, runtext, runtextbeg, runtextend - runtextbeg, runtextstart);
}
else
{
runmatch.Reset(runregex, runtext, runtextbeg, runtextend, runtextstart);
}
// note we test runcrawl, because it is the last one to be allocated
// If there is an alloc failure in the middle of the three allocations,
// we may still return to reuse this instance, and we want to behave
// as if the allocations didn't occur. (we used to test _trackcount != 0)
if (runcrawl != null)
{
runtrackpos = runtrack.Length;
runstackpos = runstack.Length;
runcrawlpos = runcrawl.Length;
return;
}
InitTrackCount();
int tracksize = runtrackcount * 8;
int stacksize = runtrackcount * 8;
if (tracksize < 32)
tracksize = 32;
if (stacksize < 16)
stacksize = 16;
runtrack = new int[tracksize];
runtrackpos = tracksize;
runstack = new int[stacksize];
runstackpos = stacksize;
runcrawl = new int[32];
runcrawlpos = 32;
}
/// <summary>
/// Put match in its canonical form before returning it.
/// </summary>
private Match TidyMatch(bool quick)
{
if (!quick)
{
Match match = runmatch;
runmatch = null;
match.Tidy(runtextpos);
return match;
}
else
{
// in quick mode, a successful match returns null, and
// the allocated match object is left in the cache
return null;
}
}
/// <summary>
/// Called by the implementation of Go() to increase the size of storage
/// </summary>
protected void EnsureStorage()
{
if (runstackpos < runtrackcount * 4)
DoubleStack();
if (runtrackpos < runtrackcount * 4)
DoubleTrack();
}
/// <summary>
/// Called by the implementation of Go() to decide whether the pos
/// at the specified index is a boundary or not. It's just not worth
/// emitting inline code for this logic.
/// </summary>
protected bool IsBoundary(int index, int startpos, int endpos)
{
return (index > startpos && RegexCharClass.IsWordChar(runtext[index - 1])) !=
(index < endpos && RegexCharClass.IsWordChar(runtext[index]));
}
protected bool IsECMABoundary(int index, int startpos, int endpos)
{
return (index > startpos && RegexCharClass.IsECMAWordChar(runtext[index - 1])) !=
(index < endpos && RegexCharClass.IsECMAWordChar(runtext[index]));
}
protected static bool CharInSet(char ch, string set, string category)
{
string charClass = RegexCharClass.ConvertOldStringsToClass(set, category);
return RegexCharClass.CharInClass(ch, charClass);
}
protected static bool CharInClass(char ch, string charClass)
{
return RegexCharClass.CharInClass(ch, charClass);
}
/// <summary>
/// Called by the implementation of Go() to increase the size of the
/// backtracking stack.
/// </summary>
protected void DoubleTrack()
{
int[] newtrack;
newtrack = new int[runtrack.Length * 2];
Array.Copy(runtrack, 0, newtrack, runtrack.Length, runtrack.Length);
runtrackpos += runtrack.Length;
runtrack = newtrack;
}
/// <summary>
/// Called by the implementation of Go() to increase the size of the
/// grouping stack.
/// </summary>
protected void DoubleStack()
{
int[] newstack;
newstack = new int[runstack.Length * 2];
Array.Copy(runstack, 0, newstack, runstack.Length, runstack.Length);
runstackpos += runstack.Length;
runstack = newstack;
}
/// <summary>
/// Increases the size of the longjump unrolling stack.
/// </summary>
protected void DoubleCrawl()
{
int[] newcrawl;
newcrawl = new int[runcrawl.Length * 2];
Array.Copy(runcrawl, 0, newcrawl, runcrawl.Length, runcrawl.Length);
runcrawlpos += runcrawl.Length;
runcrawl = newcrawl;
}
/// <summary>
/// Save a number on the longjump unrolling stack
/// </summary>
protected void Crawl(int i)
{
if (runcrawlpos == 0)
DoubleCrawl();
runcrawl[--runcrawlpos] = i;
}
/// <summary>
/// Remove a number from the longjump unrolling stack
/// </summary>
protected int Popcrawl()
{
return runcrawl[runcrawlpos++];
}
/// <summary>
/// Get the height of the stack
/// </summary>
protected int Crawlpos()
{
return runcrawl.Length - runcrawlpos;
}
/// <summary>
/// Called by Go() to capture a subexpression. Note that the
/// capnum used here has already been mapped to a non-sparse
/// index (by the code generator RegexWriter).
/// </summary>
protected void Capture(int capnum, int start, int end)
{
if (end < start)
{
int T;
T = end;
end = start;
start = T;
}
Crawl(capnum);
runmatch.AddMatch(capnum, start, end - start);
}
/// <summary>
/// Called by Go() to capture a subexpression. Note that the
/// capnum used here has already been mapped to a non-sparse
/// index (by the code generator RegexWriter).
/// </summary>
protected void TransferCapture(int capnum, int uncapnum, int start, int end)
{
int start2;
int end2;
// these are the two intervals that are cancelling each other
if (end < start)
{
int T;
T = end;
end = start;
start = T;
}
start2 = MatchIndex(uncapnum);
end2 = start2 + MatchLength(uncapnum);
// The new capture gets the innermost defined interval
if (start >= end2)
{
end = start;
start = end2;
}
else if (end <= start2)
{
start = start2;
}
else
{
if (end > end2)
end = end2;
if (start2 > start)
start = start2;
}
Crawl(uncapnum);
runmatch.BalanceMatch(uncapnum);
if (capnum != -1)
{
Crawl(capnum);
runmatch.AddMatch(capnum, start, end - start);
}
}
/*
* Called by Go() to revert the last capture
*/
protected void Uncapture()
{
int capnum = Popcrawl();
runmatch.RemoveMatch(capnum);
}
/// <summary>
/// Call out to runmatch to get around visibility issues
/// </summary>
protected bool IsMatched(int cap)
{
return runmatch.IsMatched(cap);
}
/// <summary>
/// Call out to runmatch to get around visibility issues
/// </summary>
protected int MatchIndex(int cap)
{
return runmatch.MatchIndex(cap);
}
/// <summary>
/// Call out to runmatch to get around visibility issues
/// </summary>
protected int MatchLength(int cap)
{
return runmatch.MatchLength(cap);
}
#if DEBUG
/// <summary>
/// Dump the current state
/// </summary>
internal virtual void DumpState()
{
Debug.WriteLine("Text: " + TextposDescription());
Debug.WriteLine("Track: " + StackDescription(runtrack, runtrackpos));
Debug.WriteLine("Stack: " + StackDescription(runstack, runstackpos));
}
private static string StackDescription(int[] a, int index)
{
var sb = new StringBuilder();
sb.Append(a.Length - index);
sb.Append('/');
sb.Append(a.Length);
if (sb.Length < 8)
sb.Append(' ', 8 - sb.Length);
sb.Append('(');
for (int i = index; i < a.Length; i++)
{
if (i > index)
sb.Append(' ');
sb.Append(a[i]);
}
sb.Append(')');
return sb.ToString();
}
internal virtual string TextposDescription()
{
var sb = new StringBuilder();
int remaining;
sb.Append(runtextpos);
if (sb.Length < 8)
sb.Append(' ', 8 - sb.Length);
if (runtextpos > runtextbeg)
sb.Append(RegexCharClass.CharDescription(runtext[runtextpos - 1]));
else
sb.Append('^');
sb.Append('>');
remaining = runtextend - runtextpos;
for (int i = runtextpos; i < runtextend; i++)
{
sb.Append(RegexCharClass.CharDescription(runtext[i]));
}
if (sb.Length >= 64)
{
sb.Length = 61;
sb.Append("...");
}
else
{
sb.Append('$');
}
return sb.ToString();
}
#endif
}
}
| |
using System.Collections.Generic;
using BlackFox.U2F.Gnubby.Simulated;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
namespace BlackFox.U2F.Tests
{
public static class TestVectors
{
public const int COUNTER_VALUE = 1;
public const string ACCOUNT_NAME = "test@example.com";
public static readonly List<string> TRUSTED_DOMAINS = new List<string> {"http://example.com"};
public const string SESSION_ID = "session_id";
public const string APP_ID_ENROLL = "http://example.com";
public static readonly byte[] APP_ID_ENROLL_SHA256 = TestUtils.ComputeSha256(APP_ID_ENROLL);
public const string APP_ID_SIGN = "https://gstatic.com/securitykey/a/example.com";
public static readonly byte[] APP_ID_SIGN_SHA256 = TestUtils.ComputeSha256(APP_ID_SIGN);
public const string ORIGIN = "http://example.com";
public const string SERVER_CHALLENGE_ENROLL_BASE64 = "vqrS6WXDe1JUs5_c3i4-LkKIHRr-3XVb3azuA5TifHo";
public static readonly byte[] SERVER_CHALLENGE_ENROLL = WebSafeBase64Converter.FromBase64String(SERVER_CHALLENGE_ENROLL_BASE64);
public const string SERVER_CHALLENGE_SIGN_BASE64 = "opsXqUifDriAAmWclinfbS0e-USY0CgyJHe_Otd7z8o";
public static readonly byte[] SERVER_CHALLENGE_SIGN = WebSafeBase64Converter.FromBase64String(SERVER_CHALLENGE_SIGN_BASE64);
public const string VENDOR_CERTIFICATE_HEX = "3082013c3081e4a003020102020a47901280001155957352300a06082a8648ce"
+ "3d0403023017311530130603550403130c476e756262792050696c6f74301e17" + "0d3132303831343138323933325a170d3133303831343138323933325a303131"
+ "2f302d0603550403132650696c6f74476e756262792d302e342e312d34373930" + "313238303030313135353935373335323059301306072a8648ce3d020106082a"
+ "8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c144668" + "2c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf02"
+ "03b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cd" + "b6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220"
+ "631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df";
public static readonly X509Certificate VENDOR_CERTIFICATE
= TestUtils.ParseCertificate(VENDOR_CERTIFICATE_HEX);
public static readonly ECPrivateKeyParameters VENDOR_CERTIFICATE_PRIVATE_KEY
= TestUtils.ParsePrivateKey("f3fccc0d00d8031954f90864d43c247f4bf5f0665c6b50cc17749a27d1cf7664"
);
public const string CHANNEL_ID_STRING = @"{""kty"":""EC"",""crv"":""P-256"",""x"":""HzQwlfXX7Q4S5MtCCnZUNBw3RMzPO9tOyWjBqRl4tJ8"",""y"":""XVguGFLIZx1fXg3wNqfdbn75hi4-_7-BxhMljw42Ht4""}";
public static readonly JObject CHANNEL_ID_JSON = JObject.Parse(CHANNEL_ID_STRING);
public static readonly string BROWSER_DATA_ENROLL = @"{""typ"":""navigator.id.finishEnrollment""," +
$@"""challenge"":""{SERVER_CHALLENGE_ENROLL_BASE64}""," +
$@"""cid_pubkey"":{CHANNEL_ID_STRING}," +
$@"""origin"":""{ORIGIN}""}}";
public static readonly string BROWSER_DATA_ENROLL_BASE64 = WebSafeBase64Converter.ToBase64String(BROWSER_DATA_ENROLL);
public static readonly byte[] BROWSER_DATA_ENROLL_SHA256 = TestUtils.ComputeSha256(BROWSER_DATA_ENROLL);
public static readonly string BROWSER_DATA_SIGN =
$@"{{""typ"":""navigator.id.getAssertion"",""challenge"":""{SERVER_CHALLENGE_SIGN_BASE64}"",""cid_pubkey"":{CHANNEL_ID_STRING},""origin"":""{ORIGIN}""}}";
public static readonly string BROWSER_DATA_SIGN_BASE64 = WebSafeBase64Converter.ToBase64String(BROWSER_DATA_SIGN);
public static readonly byte[] BROWSER_DATA_SIGN_SHA256 = TestUtils.ParseHex
("ccd6ee2e47baef244d49a222db496bad0ef5b6f93aa7cc4d30c4821b3b9dbc57");
public static readonly byte[] REGISTRATION_REQUEST_DATA = TestUtils.ParseHex
("4142d21c00d94ffb9d504ada8f99b721f4b191ae4e37ca0140f696b6983cfacb" + "f0e6a6a97042a4f1f1c87f5f7d44315b2d852c2df5c7991cc66241bf7072d1c4"
);
public static readonly byte[] REGISTRATION_RESPONSE_DATA = TestUtils.ParseHex
("0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b" + "657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2"
+ "f6d9402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2" + "e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772"
+ "d70c253082013c3081e4a003020102020a47901280001155957352300a06082a" + "8648ce3d0403023017311530130603550403130c476e756262792050696c6f74"
+ "301e170d3132303831343138323933325a170d3133303831343138323933325a" + "3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34"
+ "373930313238303030313135353935373335323059301306072a8648ce3d0201" + "06082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c"
+ "1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23" + "abaf0203b4b8911ba0569994e101300a06082a8648ce3d040302034700304402"
+ "2060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30d" + "fa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b3"
+ "0410df304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80f" + "cab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5"
+ "ad7804a6d3d3961ef871");
public static readonly string REGISTRATION_DATA_BASE64 = WebSafeBase64Converter.ToBase64String(REGISTRATION_RESPONSE_DATA);
public static readonly byte[] REGISTRATION_RESPONSE_DATA_ONE_TRANSPORT
= TestUtils.ParseHex("0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc"
+ "6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552d" + "fdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab6"
+ "1d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082019a30820140" + "a0030201020209012242000255962657300a06082a8648ce3d0403023045310b30090"
+ "603550406130241553113301106035504080c0a536f6d652d53746174653121301f06" + "0355040a0c18496e7465726e6574205769646769747320507479204c74643020170d3"
+ "135303830353136353131325a180f32303633303630373136353131325a3045310b30" + "090603550406130241553113301106035504080c0a536f6d652d53746174653121301"
+ "f060355040a0c18496e7465726e6574205769646769747320507479204c7464305930" + "1306072a8648ce3d020106082a8648ce3d030107034200042e09745f6e0f412a7a84b"
+ "367eb0b8dcb4a61d1fa336bbecfe30bd0a2c8faf74734a82fc03412589f4cc107f932" + "d3167e961eb664c3080347e505626c1d5d15cfa31730153013060b2b0601040182e51"
+ "c020101040403020780300a06082a8648ce3d040302034800304502202106e368bbe2" + "fc9f86991826b90a51c694b90fb7c01945e7a9531e4b65315ac5022100aa8e75a071e"
+ "645000376150c7faef1b8a57cb4bd41729c28d9b9bec744ebb4493045022070c1b332" + "667853491a525850b15599cc88be0433fc673be89e991b550921c2110221008326311"
+ "e0feaf1698110bed2c0737f3614298a8f265121f896db3cad459607fb");
public static readonly string REGISTRATION_RESPONSE_DATA_ONE_TRANSPORT_BASE64
= WebSafeBase64Converter.ToBase64String(REGISTRATION_RESPONSE_DATA_ONE_TRANSPORT
);
public static readonly byte[] REGISTRATION_RESPONSE_DATA_MULTIPLE_TRANSPORTS
= TestUtils.ParseHex("0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6"
+ "b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfd" + "b7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d1"
+ "6591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082019930820140a003" + "0201020209012242000255962657300a06082a8648ce3d0403023045310b3009060355"
+ "0406130241553113301106035504080c0a536f6d652d53746174653121301f06035504" + "0a0c18496e7465726e6574205769646769747320507479204c74643020170d31353038"
+ "30353136343932345a180f32303633303630373136343932345a3045310b3009060355" + "0406130241553113301106035504080c0a536f6d652d53746174653121301f06035504"
+ "0a0c18496e7465726e6574205769646769747320507479204c74643059301306072a86" + "48ce3d020106082a8648ce3d030107034200042e09745f6e0f412a7a84b367eb0b8dcb"
+ "4a61d1fa336bbecfe30bd0a2c8faf74734a82fc03412589f4cc107f932d3167e961eb6" + "64c3080347e505626c1d5d15cfa31730153013060b2b0601040182e51c020101040403"
+ "0204d0300a06082a8648ce3d0403020347003044022058b52f205dc9772e1bef915973" + "6098290ffb5850769efd1c37cfc97141279e5f02200c4d91c96c457d1a607a0d16b0b5"
+ "47bbb2e5e2865490112e4b94607b3adcad18304402202548b5204488995f00c905d2b9" + "25ca2f9b8c0aba76faf3461dc6778864eb5ee3022005f2d852969864577e01c71cbb10"
+ "93412ef0fef518141d698cda2a45fe2bc767");
public static readonly string REGISTRATION_RESPONSE_DATA_MULTIPLE_TRANSPORTS_BASE64
= WebSafeBase64Converter.ToBase64String(REGISTRATION_RESPONSE_DATA_MULTIPLE_TRANSPORTS
);
public static readonly byte[] REGISTRATION_RESPONSE_DATA_MALFORMED_TRANSPORTS
= TestUtils.ParseHex("0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b"
+ "952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfdb7" + "477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d1659"
+ "1659cbaf00b4950f7abfe6660e2e006f76868b772d70c25308201983082013ea0030201" + "020209012242000255962657300a06082a8648ce3d0403023045310b300906035504061"
+ "30241553113301106035504080c0a536f6d652d53746174653121301f060355040a0c18" + "496e7465726e6574205769646769747320507479204c74643020170d313530383036323"
+ "3333532385a180f32303633303630383233333532385a3045310b300906035504061302" + "41553113301106035504080c0a536f6d652d53746174653121301f060355040a0c18496"
+ "e7465726e6574205769646769747320507479204c74643059301306072a8648ce3d0201" + "06082a8648ce3d030107034200042e09745f6e0f412a7a84b367eb0b8dcb4a61d1fa336"
+ "bbecfe30bd0a2c8faf74734a82fc03412589f4cc107f932d3167e961eb664c3080347e5" + "05626c1d5d15cfa31530133011060b2b0601040182e51c0201010402aa80300a06082a8"
+ "648ce3d0403020348003045022100907f965f33d857982b39d9f4c22ccb4a63359fc10a" + "af08a81997c0e04b73dc9b02204f45d556ae2ea71a5fdfa646b516584dada84954a5d8b"
+ "9d27bdb041e89b216b6304402206b5085168e0c0e850677d3423c0f3972860bd3fbf6d2" + "d98cd7af9e1d3f46269402201bde430c86260666bcaa23155296bd0627a8e48d98c2009"
+ "212bec8a7a77f7974");
public static readonly string REGISTRATION_RESPONSE_DATA_MALFORMED_TRANSPORTS_BASE64
= WebSafeBase64Converter.ToBase64String(REGISTRATION_RESPONSE_DATA_MALFORMED_TRANSPORTS
);
public static readonly byte[] KEY_HANDLE = TestUtils.ParseHex
("2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a" + "6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c25"
);
public static readonly string KEY_HANDLE_BASE64 = WebSafeBase64Converter.ToBase64String(KEY_HANDLE);
public static readonly byte[] USER_PUBLIC_KEY_ENROLL_HEX = TestUtils.ParseHex
("04b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b65" + "7c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6"
+ "d9");
public const string USER_PRIVATE_KEY_ENROLL_HEX = "9a9684b127c5e3a706d618c86401c7cf6fd827fd0bc18d24b0eb842e36d16df1";
public static readonly ECPublicKeyParameters USER_PUBLIC_KEY_ENROLL
= TestUtils.ParsePublicKey(USER_PUBLIC_KEY_ENROLL_HEX);
public static readonly ECPrivateKeyParameters USER_PRIVATE_KEY_ENROLL
= TestUtils.ParsePrivateKey(USER_PRIVATE_KEY_ENROLL_HEX);
public static readonly ECKeyPair USER_KEY_PAIR_ENROLL = new
ECKeyPair(USER_PUBLIC_KEY_ENROLL, USER_PRIVATE_KEY_ENROLL);
public const string USER_PRIVATE_KEY_SIGN_HEX = "ffa1e110dde5a2f8d93c4df71e2d4337b7bf5ddb60c75dc2b6b81433b54dd3c0";
public static readonly byte[] USER_PUBLIC_KEY_SIGN_HEX = TestUtils.ParseHex
("04d368f1b665bade3c33a20f1e429c7750d5033660c019119d29aa4ba7abc04a" + "a7c80a46bbe11ca8cb5674d74f31f8a903f6bad105fb6ab74aefef4db8b0025e"
+ "1d");
public static readonly ECPublicKeyParameters USER_PUBLIC_KEY_SIGN =
TestUtils.ParsePublicKey(USER_PUBLIC_KEY_SIGN_HEX);
public static readonly ECPrivateKeyParameters USER_PRIVATE_KEY_SIGN
= TestUtils.ParsePrivateKey(USER_PRIVATE_KEY_SIGN_HEX);
public static readonly ECKeyPair USER_KEY_PAIR_SIGN = new
ECKeyPair(USER_PUBLIC_KEY_SIGN, USER_PRIVATE_KEY_SIGN);
public static readonly byte[] SIGN_REQUEST_DATA = TestUtils.ParseHex
("ccd6ee2e47baef244d49a222db496bad0ef5b6f93aa7cc4d30c4821b3b9dbc" + "574b0be934baebb5d12d26011b69227fa5e86df94e7d94aa2949a89f2d493992"
+ "ca402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3" + "925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d7"
+ "0c25");
public static readonly byte[] SIGN_RESPONSE_DATA = TestUtils.ParseHex
("0100000001304402204b5f0cd17534cedd8c34ee09570ef542a353df4436030c" + "e43d406de870b847780220267bb998fac9b7266eb60e7cb0b5eabdfd5ba9614f"
+ "53c7b22272ec10047a923f");
public static readonly string SIGN_RESPONSE_DATA_BASE64 = WebSafeBase64Converter.ToBase64String(SIGN_RESPONSE_DATA);
public static readonly byte[] EXPECTED_REGISTER_SIGNED_BYTES = TestUtils.ParseHex
("00f0e6a6a97042a4f1f1c87f5f7d44315b2d852c2df5c7991cc66241bf7072d1" + "c44142d21c00d94ffb9d504ada8f99b721f4b191ae4e37ca0140f696b6983cfa"
+ "cb2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e392" + "5a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c"
+ "2504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b" + "657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2"
+ "f6d9");
public static readonly byte[] EXPECTED_AUTHENTICATE_SIGNED_BYTES = TestUtils.ParseHex
("4b0be934baebb5d12d26011b69227fa5e86df94e7d94aa2949a89f2d493992ca" + "0100000001ccd6ee2e47baef244d49a222db496bad0ef5b6f93aa7cc4d30c482"
+ "1b3b9dbc57");
public static readonly byte[] SIGNATURE_ENROLL = TestUtils.ParseHex
("304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017" + "db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804"
+ "a6d3d3961ef871");
public static readonly byte[] SIGNATURE_AUTHENTICATE = TestUtils.ParseHex
("304402204b5f0cd17534cedd8c34ee09570ef542a353df4436030ce43d406de8" + "70b847780220267bb998fac9b7266eb60e7cb0b5eabdfd5ba9614f53c7b22272"
+ "ec10047a923f");
public const string APP_ID_2 = APP_ID_ENROLL;
public const string CHALLENGE_2_BASE64 = SERVER_CHALLENGE_ENROLL_BASE64;
public static readonly string BROWSER_DATA_2_BASE64 = BROWSER_DATA_ENROLL_BASE64;
public const string TRUSTED_CERTIFICATE_2_HEX = "308201443081eaa0030201020209019189ffffffff5183300a06082a8648ce3d"
+ "040302301b3119301706035504031310476e756262792048534d204341203030" + "3022180f32303132303630313030303030305a180f3230363230353331323335"
+ "3935395a30303119301706035504031310476f6f676c6520476e756262792076" + "3031133011060355042d030a00019189ffffffff51833059301306072a8648ce"
+ "3d020106082a8648ce3d030107034200041f1302f12173a9cbea83d06d755411" + "e582a87fbb5850eddcf3607ec759a4a12c3cb392235e8d5b17caee1b34e5b5eb"
+ "548649696257f0ea8efb90846f88ad5f72300a06082a8648ce3d040302034900" + "3046022100b4caea5dc60fbf9f004ed84fc4f18522981c1c303155c08274e889"
+ "f3f10c5b23022100faafb4f10b92f4754e3b08b5af353f78485bc903ece7ea91" + "1264fc1673b6598f";
public static readonly X509Certificate TRUSTED_CERTIFICATE_2
= TestUtils.ParseCertificate(TRUSTED_CERTIFICATE_2_HEX);
private const string TRUSTED_CERTIFICATE_ONE_TRANSPORT_BASE64 = "MIIBmjCCAUCgAwIBAgIJASJCAAJVliZXMAoGCCqGSM49BAMCMEUxCzAJBgNVBAYT"
+ "AkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRn" + "aXRzIFB0eSBMdGQwIBcNMTUwODA1MTY1MTEyWhgPMjA2MzA2MDcxNjUxMTJaMEUx"
+ "CzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRl" + "cm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQu"
+ "CXRfbg9BKnqEs2frC43LSmHR+jNrvs/jC9CiyPr3RzSoL8A0ElifTMEH+TLTFn6W" + "HrZkwwgDR+UFYmwdXRXPoxcwFTATBgsrBgEEAYLlHAIBAQQEAwIHgDAKBggqhkjO"
+ "PQQDAgNIADBFAiAhBuNou+L8n4aZGCa5ClHGlLkPt8AZReepUx5LZTFaxQIhAKqO" + "daBx5kUAA3YVDH+u8bilfLS9QXKcKNm5vsdE67RJ";
public static readonly X509Certificate TRUSTED_CERTIFICATE_ONE_TRANSPORT
= TestUtils.ParseCertificateBase64(TRUSTED_CERTIFICATE_ONE_TRANSPORT_BASE64
);
private const string TRUSTED_CERTIFICATE_MULTIPLE_TRANSPORTS_BASE64 = "MIIBmTCCAUCgAwIBAgIJASJCAAJVliZXMAoGCCqGSM49BAMCMEUxCzAJBgNVBAYT"
+ "AkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRn" + "aXRzIFB0eSBMdGQwIBcNMTUwODA1MTY0OTI0WhgPMjA2MzA2MDcxNjQ5MjRaMEUx"
+ "CzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRl" + "cm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQu"
+ "CXRfbg9BKnqEs2frC43LSmHR+jNrvs/jC9CiyPr3RzSoL8A0ElifTMEH+TLTFn6W" + "HrZkwwgDR+UFYmwdXRXPoxcwFTATBgsrBgEEAYLlHAIBAQQEAwIE0DAKBggqhkjO"
+ "PQQDAgNHADBEAiBYtS8gXcl3LhvvkVlzYJgpD/tYUHae/Rw3z8lxQSeeXwIgDE2R" + "yWxFfRpgeg0WsLVHu7Ll4oZUkBEuS5RgezrcrRg=";
public static readonly X509Certificate TRUSTED_CERTIFICATE_MULTIPLE_TRANSPORTS
= TestUtils.ParseCertificateBase64(TRUSTED_CERTIFICATE_MULTIPLE_TRANSPORTS_BASE64
);
private const string TRUSTED_CERTIFICATE_MALFORMED_TRANSPORTS_EXTENSION_BASE64 =
"MIIBmDCCAT6gAwIBAgIJASJCAAJVliZXMAoGCCqGSM49BAMCMEUxCzAJBgNVBAYT" + "AkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRn"
+ "aXRzIFB0eSBMdGQwIBcNMTUwODA2MjMzNTI4WhgPMjA2MzA2MDgyMzM1MjhaMEUx" + "CzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRl"
+ "cm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQu" + "CXRfbg9BKnqEs2frC43LSmHR+jNrvs/jC9CiyPr3RzSoL8A0ElifTMEH+TLTFn6W"
+ "HrZkwwgDR+UFYmwdXRXPoxUwEzARBgsrBgEEAYLlHAIBAQQCqoAwCgYIKoZIzj0E" + "AwIDSAAwRQIhAJB/ll8z2FeYKznZ9MIsy0pjNZ/BCq8IqBmXwOBLc9ybAiBPRdVW"
+ "ri6nGl/fpka1FlhNrahJVKXYudJ72wQeibIWtg==";
public static readonly X509Certificate TRUSTED_CERTIFICATE_MALFORMED_TRANSPORTS_EXTENSION
= TestUtils.ParseCertificateBase64(TRUSTED_CERTIFICATE_MALFORMED_TRANSPORTS_EXTENSION_BASE64
);
public static readonly byte[] REGISTRATION_DATA_2 = TestUtils.ParseHex
("0504478E16BBDBBB741A660A000314A8B6BD63095196ED704C52EEBC0FA02A61" + "8F19FF59DF18451A11CEE43DEFD9A29B5710F63DFC671F752B1B0C6CA76C8427"
+ "AF2D403C2415E1760D1108105720C6069A9039C99D09F76909C36D9EFC350937" + "31F85F55AC6D73EA69DE7D9005AE9507B95E149E19676272FC202D949A3AB151"
+ "B96870308201443081EAA0030201020209019189FFFFFFFF5183300A06082A86" + "48CE3D040302301B3119301706035504031310476E756262792048534D204341"
+ "2030303022180F32303132303630313030303030305A180F3230363230353331" + "3233353935395A30303119301706035504031310476F6F676C6520476E756262"
+ "7920763031133011060355042D030A00019189FFFFFFFF51833059301306072A" + "8648CE3D020106082A8648CE3D030107034200041F1302F12173A9CBEA83D06D"
+ "755411E582A87FBB5850EDDCF3607EC759A4A12C3CB392235E8D5B17CAEE1B34" + "E5B5EB548649696257F0EA8EFB90846F88AD5F72300A06082A8648CE3D040302"
+ "0349003046022100B4CAEA5DC60FBF9F004ED84FC4F18522981C1C303155C082" + "74E889F3F10C5B23022100FAAFB4F10B92F4754E3B08B5AF353F78485BC903EC"
+ "E7EA911264FC1673B6598F3046022100F3BE1BF12CBF0BE7EAB5EA32F3664EDB" + "18A24D4999AAC5AA40FF39CF6F34C9ED022100CE72631767367467DFE2AECF6A"
+ "5A4EBA9779FAC65F5CA8A2C325B174EE4769AC");
public static readonly string REGISTRATION_DATA_2_BASE64 = WebSafeBase64Converter.ToBase64String(REGISTRATION_DATA_2);
public static readonly byte[] KEY_HANDLE_2 = TestUtils.ParseHex
("3c2415e1760d1108105720c6069a9039c99d09f76909c36d9efc35093731f85f" + "55ac6d73ea69de7d9005ae9507b95e149e19676272fc202d949a3ab151b96870"
);
public static readonly byte[] USER_PUBLIC_KEY_2 = TestUtils.ParseHex
("04478e16bbdbbb741a660a000314a8b6bd63095196ed704c52eebc0fa02a618f" + "19ff59df18451a11cee43defd9a29b5710f63dfc671f752b1b0c6ca76c8427af"
+ "2d");
public static readonly byte[] SIGN_DATA_2 = TestUtils.ParseHex
("01000000223045022100FB16D12F8EC73D93EAB43BFDF141BF94E31AD3B1C98E" + "E4459E9E80CBBBD892F70220796DBCB8BBF57EC95A20A76D9ED3365CB688BF88"
+ "2ECCEABCC8D4A674024F6ABA");
public static readonly string SIGN_DATA_2_BASE64 = WebSafeBase64Converter.ToBase64String(SIGN_DATA_2);
//Test vectors from FIDO U2F: Raw Message Formats - Draft 4
// Has Bluetooth Radio transport
// Has Bluetooth Radio, Bluetooth Low Energy, and NFC transports
// Test vectors provided by Discretix
// Has Bluetooth Radio transport
// Has Bluetooth Radio, Bluetooth Low Energy, and NFC transports
}
}
| |
using FontBuddyLib;
using InputHelper;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using ResolutionBuddy;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace MenuBuddy
{
/// <summary>
/// A popup message box screen, used to display "are you sure?" confirmation messages.
/// </summary>
public class MessageBoxScreen : MenuScreen, IClickable, IDisposable
{
#region Properties
/// <summary>
/// The message to be displayed
/// </summary>
public string Message { get; private set; }
public event EventHandler<ClickEventArgs> OnSelect;
public event EventHandler<ClickEventArgs> OnCancel;
protected IStackLayout ControlStack { get; private set; }
public string OkText { get; set; }
public string CancelText { get; set; }
public bool HasBackground { get; set; }
public bool ExitOnOk { get; set; }
#endregion //Properties
#region Methods
/// <summary>
/// Constructor lets the caller specify whether to include the standard
/// "A=ok, B=cancel" usage text prompt.
/// </summary>
public MessageBoxScreen(string message, string menuTitle = "", ContentManager content = null) :
base(menuTitle, content)
{
ExitOnOk = true;
//grab the message
Message = message;
HasBackground = true;
CoverOtherScreens = true;
Transition.OnTime = 0.2f;
Transition.OffTime = 0.2f;
OkText = "Ok";
CancelText = "Cancel";
Modal = true;
}
/// <summary>
/// Loads graphics content for this screen. This uses the shared ContentManager
/// provided by the Game class, so the content will remain loaded forever.
/// Whenever a subsequent MessageBoxScreen tries to load this same content,
/// it will just get back another reference to the already loaded data.
/// </summary>
public override async Task LoadContent()
{
await base.LoadContent();
var screenLayout = new RelativeLayout()
{
Size = new Vector2(Resolution.ScreenArea.Width, Resolution.ScreenArea.Height),
Position = new Point(0),
Horizontal = HorizontalAlignment.Left,
Vertical = VerticalAlignment.Top,
};
//Create the stack for the label text
var labelStack = new StackLayout()
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center,
Alignment = StackAlignment.Top,
};
ControlStack = new StackLayout()
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center,
Alignment = StackAlignment.Top,
};
//Split up the label text into lines
var lines = Message.Split('\n').ToList();
//split the line into lines that will actuall fit on the screen
IFontBuddy tempFont;
if (StyleSheet.UseFontPlus)
{
tempFont = new FontBuddyPlus();
tempFont.LoadContent(Content, StyleSheet.SmallFontResource, true, StyleSheet.SmallFontSize);
}
else
{
tempFont = new FontBuddy();
tempFont.LoadContent(Content, StyleSheet.SmallFontResource);
}
//Add all the label text to the stack
foreach (var line in lines)
{
var splitLines = tempFont.BreakTextIntoList(line, Resolution.TitleSafeArea.Width - 64);
foreach (var splitLine in splitLines)
{
//Set the label text
var label = new Label(splitLine, Content, FontSize.Small)
{
Highlightable = false,
TextColor = StyleSheet.MessageBoxTextColor,
};
ControlStack.AddItem(label);
}
}
tempFont.Dispose();
tempFont = null;
try
{
await AddAdditionalControls();
}
catch (Exception ex)
{
await ScreenManager.AddScreen(new ErrorScreen(ex));
}
//add a shim between the text and the buttons
ControlStack.AddItem(new Shim() { Size = new Vector2(0, 32f) });
labelStack.AddItem(ControlStack);
//Add the buttons
await AddButtons(labelStack);
//Set the position of the labelstack
labelStack.Position = new Point(labelStack.Rect.Width / 2, 0);
var absScreenLayout = new AbsoluteLayout()
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center,
Size = new Vector2(labelStack.Rect.Width, labelStack.Rect.Height),
};
absScreenLayout.AddItem(labelStack);
screenLayout.AddItem(absScreenLayout);
AddItem(screenLayout);
if (HasBackground)
{
AddBackgroundImage(labelStack);
}
}
public override void UnloadContent()
{
base.UnloadContent();
OnSelect = null;
OnCancel = null;
}
/// <summary>
/// Override this method to add any additional controls to the ControlStack
/// </summary>
protected virtual Task AddAdditionalControls()
{
return Task.CompletedTask;
}
/// <summary>
/// Override with method to validate any data that has been entered before exiting the screen.
/// </summary>
/// <returns></returns>
protected virtual bool Validate()
{
return true;
}
protected virtual async Task AddButtons(StackLayout stack)
{
var buttonLayout = new RelativeLayout()
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Top,
Size = new Vector2( Resolution.TitleSafeArea.Width * 0.8f, 64f)
};
var okButton = await AddMessageBoxOkButton();
okButton.Horizontal = HorizontalAlignment.Left;
buttonLayout.AddItem(okButton);
AddMenuItem(okButton, 100);
var cancelButton = await AddMessageBoxCancelButton();
cancelButton.Horizontal = HorizontalAlignment.Right;
buttonLayout.AddItem(cancelButton);
AddMenuItem(cancelButton, 101);
//make sure user can left/right with controller
okButton.OnRight += (e, obj) =>
{
SetSelectedItem(cancelButton);
};
cancelButton.OnLeft += (e, obj) =>
{
SetSelectedItem(okButton);
};
stack.AddItem(buttonLayout);
stack.AddItem(new Shim(0, 16));
}
private void OkButton_OnRight(object sender, EventArgs e)
{
throw new NotImplementedException();
}
protected async Task<IButton> AddMessageBoxOkButton()
{
var button = await CreateButton(true);
button.OnClick += ((obj, e) =>
{
if (Validate())
{
if (null != OnSelect)
{
OnSelect(obj, e);
}
if (ExitOnOk)
{
ExitScreen();
}
}
});
return button;
}
protected async Task<IButton> AddMessageBoxCancelButton()
{
var button = await CreateButton(false);
button.OnClick += ((obj, e) =>
{
if (null != OnCancel)
{
OnCancel(obj, e);
}
ExitScreen();
});
return button;
}
private async Task<IButton> CreateButton(bool okButton)
{
//Create the menu entry "Cancel"
var label = new Label(okButton ? OkText : CancelText, Content, FontSize.Small)
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center,
Layer = 1,
};
//check if there is a background image for this button
var backgrounImage = okButton ? StyleSheet.MessageBoxOkImageResource : StyleSheet.MessageBoxCancelImageResource;
var hasBackgroundImage = !string.IsNullOrEmpty(backgrounImage);
//Create the menu entry for "OK"
var button = new RelativeLayoutButton()
{
HasBackground = !hasBackgroundImage,
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Top,
Size = new Vector2(Resolution.TitleSafeArea.Width * 0.4f - 16, label.Rect.Height * 2f)
};
button.AddItem(label);
if (hasBackgroundImage)
{
button.AddItem(new Image(Content.Load<Texture2D>(backgrounImage))
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center,
Size = button.Rect.Size.ToVector2(),
Highlightable = false,
PulsateOnHighlight = false,
FillRect = true,
Layer = 0
});
}
await button.LoadContent(this);
return button;
}
public virtual void AddBackgroundImage(ILayout labelStack)
{
//get the background image dimensions
var width = Math.Min(Resolution.TitleSafeArea.Width, labelStack.Rect.Width + 128);
var height = Math.Min(Resolution.TitleSafeArea.Height, labelStack.Rect.Height + 200);
//Add the background image
var bkgImage = new BackgroundImage(Content.Load<Texture2D>(StyleSheet.MessageBoxBackgroundImageResource))
{
FillRect = true,
Position = new Point(labelStack.Rect.Center.X, labelStack.Rect.Center.Y),
Size = new Vector2(width, height),
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Center
};
AddItem(bkgImage);
}
/// <summary>
/// Draws the message box.
/// </summary>
public override void Draw(GameTime gameTime)
{
ScreenManager.SpriteBatchBegin();
//Darken down any other screens that were drawn beneath the popup.
FadeBackground();
ScreenManager.SpriteBatchEnd();
base.Draw(gameTime);
}
#endregion //Methods
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using MICore;
using System.Diagnostics;
using System.Globalization;
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
namespace Microsoft.MIDebugEngine
{
#region Event base classes
internal class AD7AsynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7StoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7SynchronousEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
internal class AD7SynchronousStoppingEvent : IDebugEvent2
{
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_STOPPING | (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
eventAttributes = Attributes;
return Constants.S_OK;
}
}
#endregion
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
internal sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2
{
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 _engine;
private AD7EngineCreateEvent(AD7Engine engine)
{
_engine = engine;
}
public static void Send(AD7Engine engine)
{
AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine);
engine.Callback.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine)
{
engine = _engine;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
internal sealed class AD7ProgramCreateEvent : AD7SynchronousEvent, IDebugProgramCreateEvent2
{
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine)
{
AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent();
engine.Callback.Send(eventObject, IID, engine, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
internal sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2
{
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
private readonly AD7Module _module;
private readonly bool _fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad)
{
_module = module;
_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad)
{
module = _module;
if (_fLoad)
{
string symbolLoadStatus = _module.DebuggedModule.SymbolsLoaded ?
ResourceStrings.ModuleLoadedWithSymbols :
ResourceStrings.ModuleLoadedWithoutSymbols;
debugMessage = string.Format(CultureInfo.CurrentUICulture, ResourceStrings.ModuleLoadMessage, _module.DebuggedModule.Name, symbolLoadStatus);
fIsLoad = 1;
}
else
{
debugMessage = string.Format(CultureInfo.CurrentUICulture, ResourceStrings.ModuleUnloadMessage, _module.DebuggedModule.Name);
fIsLoad = 0;
}
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
internal sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2
{
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
private readonly uint _exitCode;
public AD7ProgramDestroyEvent(uint exitCode)
{
_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = _exitCode;
return Constants.S_OK;
}
#endregion
}
internal sealed class AD7MessageEvent : IDebugEvent2, IDebugMessageEvent2
{
public const string IID = "3BDB28CF-DBD2-4D24-AF03-01072B67EB9E";
private readonly OutputMessage _outputMessage;
private readonly bool _isAsync;
public AD7MessageEvent(OutputMessage outputMessage, bool isAsync)
{
_outputMessage = outputMessage;
_isAsync = isAsync;
}
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
if (_isAsync)
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
else
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE;
return Constants.S_OK;
}
int IDebugMessageEvent2.GetMessage(enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId)
{
return ConvertMessageToAD7(_outputMessage, pMessageType, out pbstrMessage, out pdwType, out pbstrHelpFileName, out pdwHelpId);
}
internal static int ConvertMessageToAD7(OutputMessage outputMessage, enum_MESSAGETYPE[] pMessageType, out string pbstrMessage, out uint pdwType, out string pbstrHelpFileName, out uint pdwHelpId)
{
const uint MB_ICONERROR = 0x00000010;
const uint MB_ICONWARNING = 0x00000030;
pMessageType[0] = outputMessage.MessageType;
pbstrMessage = outputMessage.Message;
pdwType = 0;
if ((outputMessage.MessageType & enum_MESSAGETYPE.MT_TYPE_MASK) == enum_MESSAGETYPE.MT_MESSAGEBOX)
{
switch (outputMessage.SeverityValue)
{
case OutputMessage.Severity.Error:
pdwType |= MB_ICONERROR;
break;
case OutputMessage.Severity.Warning:
pdwType |= MB_ICONWARNING;
break;
}
}
pbstrHelpFileName = null;
pdwHelpId = 0;
return Constants.S_OK;
}
int IDebugMessageEvent2.SetResponse(uint dwResponse)
{
return Constants.S_OK;
}
}
internal sealed class AD7ErrorEvent : IDebugEvent2, IDebugErrorEvent2
{
public const string IID = "FDB7A36C-8C53-41DA-A337-8BD86B14D5CB";
private readonly OutputMessage _outputMessage;
private readonly bool _isAsync;
public AD7ErrorEvent(OutputMessage outputMessage, bool isAsync)
{
_outputMessage = outputMessage;
_isAsync = isAsync;
}
int IDebugEvent2.GetAttributes(out uint eventAttributes)
{
if (_isAsync)
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
else
eventAttributes = (uint)enum_EVENTATTRIBUTES.EVENT_IMMEDIATE;
return Constants.S_OK;
}
int IDebugErrorEvent2.GetErrorMessage(enum_MESSAGETYPE[] pMessageType, out string errorFormat, out int hrErrorReason, out uint pdwType, out string helpFilename, out uint pdwHelpId)
{
hrErrorReason = unchecked((int)_outputMessage.ErrorCode);
return AD7MessageEvent.ConvertMessageToAD7(_outputMessage, pMessageType, out errorFormat, out pdwType, out helpFilename, out pdwHelpId);
}
}
internal sealed class AD7BreakpointErrorEvent : AD7AsynchronousEvent, IDebugBreakpointErrorEvent2
{
public const string IID = "ABB0CA42-F82B-4622-84E4-6903AE90F210";
private AD7ErrorBreakpoint _error;
public AD7BreakpointErrorEvent(AD7ErrorBreakpoint error)
{
_error = error;
}
public int GetErrorBreakpoint(out IDebugErrorBreakpoint2 ppErrorBP)
{
ppErrorBP = _error;
return Constants.S_OK;
}
}
internal sealed class AD7BreakpointUnboundEvent : AD7AsynchronousEvent, IDebugBreakpointUnboundEvent2
{
public const string IID = "78d1db4f-c557-4dc5-a2dd-5369d21b1c8c";
private readonly enum_BP_UNBOUND_REASON _reason;
private AD7BoundBreakpoint _bp;
public AD7BreakpointUnboundEvent(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
_reason = reason;
_bp = bp;
}
public int GetBreakpoint(out IDebugBoundBreakpoint2 ppBP)
{
ppBP = _bp;
return Constants.S_OK;
}
public int GetReason(enum_BP_UNBOUND_REASON[] pdwUnboundReason)
{
pdwUnboundReason[0] = _reason;
return Constants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
internal sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2
{
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
internal sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2
{
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
private readonly uint _exitCode;
public AD7ThreadDestroyEvent(uint exitCode)
{
_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode)
{
exitCode = _exitCode;
return Constants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
internal sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2
{
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent()
{
}
}
internal sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2
{
public const string IID = "E8414A3E-1642-48EC-829E-5F4040E16DA9";
public AD7EntryPointEvent()
{
}
}
internal sealed class AD7ExpressionCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2
{
private AD7Engine _engine;
public const string IID = "C0E13A85-238A-4800-8315-D947C960A843";
public AD7ExpressionCompleteEvent(AD7Engine engine, IVariableInformation var, IDebugProperty2 prop = null)
{
_engine = engine;
_var = var;
_prop = prop;
}
public int GetExpression(out IDebugExpression2 expr)
{
expr = new AD7Expression(_engine, _var);
return Constants.S_OK;
}
public int GetResult(out IDebugProperty2 prop)
{
prop = _prop != null ? _prop : new AD7Property(_engine, _var);
return Constants.S_OK;
}
private IVariableInformation _var;
private IDebugProperty2 _prop;
}
// This interface tells the session debug manager (SDM) that an exception has occurred in the debuggee.
internal sealed class AD7ExceptionEvent : AD7StoppingEvent, IDebugExceptionEvent2
{
public const string IID = "51A94113-8788-4A54-AE15-08B74FF922D0";
public AD7ExceptionEvent(string name, string description, uint code, Guid? exceptionCategory, ExceptionBreakpointState state)
{
_name = name;
_code = code;
_description = description ?? name;
_category = exceptionCategory ?? new Guid(EngineConstants.EngineId);
switch (state)
{
case ExceptionBreakpointState.None:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE;
break;
case ExceptionBreakpointState.BreakThrown:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE;
break;
case ExceptionBreakpointState.BreakUserHandled:
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT;
break;
default:
Debug.Fail("Unexpected state value");
_state = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE;
break;
}
}
#region IDebugExceptionEvent2 Members
public int CanPassToDebuggee()
{
// Cannot pass it on
return Constants.S_FALSE;
}
public int GetException(EXCEPTION_INFO[] pExceptionInfo)
{
EXCEPTION_INFO ex = new EXCEPTION_INFO();
ex.bstrExceptionName = _name;
ex.dwCode = _code;
ex.dwState = _state;
ex.guidType = _category;
pExceptionInfo[0] = ex;
return Constants.S_OK;
}
public int GetExceptionDescription(out string pbstrDescription)
{
pbstrDescription = _description;
return Constants.S_OK;
}
public int PassToDebuggee(int fPass)
{
return Constants.S_OK;
}
private string _name;
private uint _code;
private string _description;
private Guid _category;
private enum_EXCEPTION_STATE _state;
#endregion
}
// This interface tells the session debug manager (SDM) that a step has completed
internal sealed class AD7StepCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2
{
public const string IID = "0f7f24c1-74d9-4ea6-a3ea-7edb2d81441d";
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
internal sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2
{
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) to output a string for debug tracing.
internal sealed class AD7OutputDebugStringEvent : AD7AsynchronousEvent, IDebugOutputStringEvent2
{
public const string IID = "569c4bb1-7b82-46fc-ae28-4536ddad753e";
private string _str;
public AD7OutputDebugStringEvent(string str)
{
_str = str;
}
#region IDebugOutputStringEvent2 Members
int IDebugOutputStringEvent2.GetString(out string pbstrString)
{
pbstrString = _str;
return Constants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to indicate the results of searching for symbols for a module in the debuggee
internal sealed class AD7SymbolSearchEvent : AD7AsynchronousEvent, IDebugSymbolSearchEvent2
{
public const string IID = "638F7C54-C160-4c7b-B2D0-E0337BC61F8C";
private AD7Module _module;
private string _searchInfo;
private enum_MODULE_INFO_FLAGS _symbolFlags;
public AD7SymbolSearchEvent(AD7Module module, string searchInfo, enum_MODULE_INFO_FLAGS symbolFlags)
{
_module = module;
_searchInfo = searchInfo;
_symbolFlags = symbolFlags;
}
#region IDebugSymbolSearchEvent2 Members
int IDebugSymbolSearchEvent2.GetSymbolSearchInfo(out IDebugModule3 pModule, ref string pbstrDebugMessage, enum_MODULE_INFO_FLAGS[] pdwModuleInfoFlags)
{
pModule = _module;
pbstrDebugMessage = _searchInfo;
pdwModuleInfoFlags[0] = _symbolFlags;
return Constants.S_OK;
}
#endregion
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
internal sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2
{
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint _pendingBreakpoint;
private AD7BoundBreakpoint _boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint)
{
_pendingBreakpoint = pendingBreakpoint;
_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = _boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return Constants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP)
{
ppPendingBP = _pendingBreakpoint;
return Constants.S_OK;
}
#endregion
}
// This Event is sent when a breakpoint is hit in the debuggee
internal sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2
{
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
private IEnumDebugBoundBreakpoints2 _boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints)
{
_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum)
{
ppEnum = _boundBreakpoints;
return Constants.S_OK;
}
#endregion
}
internal sealed class AD7StopCompleteEvent: AD7StoppingEvent, IDebugStopCompleteEvent2
{
public const string IID = "3DCA9DCD-FB09-4AF1-A926-45F293D48B2D";
}
internal sealed class AD7CustomDebugEvent : AD7AsynchronousEvent, IDebugCustomEvent110
{
public const string IID = "2615D9BC-1948-4D21-81EE-7A963F20CF59";
private readonly Guid _guidVSService;
private readonly Guid _sourceId;
private readonly int _messageCode;
private readonly object _parameter1;
private readonly object _parameter2;
public AD7CustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
_guidVSService = guidVSService;
_sourceId = sourceId;
_messageCode = messageCode;
_parameter1 = parameter1;
_parameter2 = parameter2;
}
int IDebugCustomEvent110.GetCustomEventInfo(out Guid guidVSService, VsComponentMessage[] message)
{
guidVSService = _guidVSService;
message[0].SourceId = _sourceId;
message[0].MessageCode = (uint)_messageCode;
message[0].Parameter1 = _parameter1;
message[0].Parameter2 = _parameter2;
return Constants.S_OK;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace Orleans.TestingHost
{
/// <summary>
/// A silo handle and factory which spawns a separate process for each silo.
/// </summary>
public class StandaloneSiloHandle : SiloHandle
{
private readonly StringBuilder _outputBuilder;
private readonly TaskCompletionSource<bool> _startedEvent;
private readonly TaskCompletionSource<bool> _outputCloseEvent;
private readonly StringBuilder _errorBuilder;
private readonly TaskCompletionSource<bool> _errorCloseEvent;
private readonly EventHandler _processExitHandler;
private bool isActive = true;
private Task _runTask;
/// <summary>
/// The configuration key used to identify the process to launch.
/// </summary>
public const string ExecutablePathConfigKey = "ExecutablePath";
/// <summary>Gets a reference to the silo host.</summary>
private Process Process { get; set; }
/// <inheritdoc />
public override bool IsActive => isActive;
public StandaloneSiloHandle(string siloName, IConfiguration configuration, string executablePath)
{
if (string.IsNullOrWhiteSpace(executablePath) || !File.Exists(executablePath))
{
throw new ArgumentException("Must provide at least one assembly path");
}
Name = siloName;
// If the debugger is attached to this process, give it an opportunity to attach to the remote process.
if (Debugger.IsAttached)
{
configuration["AttachDebugger"] = "true";
}
var serializedConfiguration = TestClusterHostFactory.SerializeConfiguration(configuration);
Process = new Process();
Process.StartInfo = new ProcessStartInfo(executablePath)
{
ArgumentList = { Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture), serializedConfiguration },
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WorkingDirectory = new FileInfo(executablePath).Directory.FullName,
UseShellExecute = false,
};
_outputBuilder = new StringBuilder();
_outputCloseEvent = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_startedEvent = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Process.OutputDataReceived += (s, e) =>
{
if (e.Data == null)
{
_outputCloseEvent.SetResult(true);
}
else
{
// Read standard output from the process for status updates.
if (!_startedEvent.Task.IsCompleted)
{
if (e.Data.StartsWith(StandaloneSiloHost.SiloAddressLog, StringComparison.Ordinal))
{
SiloAddress = Orleans.Runtime.SiloAddress.FromParsableString(e.Data.Substring(StandaloneSiloHost.SiloAddressLog.Length));
}
else if (e.Data.StartsWith(StandaloneSiloHost.GatewayAddressLog, StringComparison.Ordinal))
{
GatewayAddress = Orleans.Runtime.SiloAddress.FromParsableString(e.Data.Substring(StandaloneSiloHost.GatewayAddressLog.Length));
}
else if (e.Data.StartsWith(StandaloneSiloHost.StartedLog, StringComparison.Ordinal))
{
_startedEvent.TrySetResult(true);
}
}
lock (_outputBuilder)
{
_outputBuilder.AppendLine(e.Data);
}
}
};
_errorBuilder = new StringBuilder();
_errorCloseEvent = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Process.ErrorDataReceived += (s, e) =>
{
if (e.Data == null)
{
_errorCloseEvent.SetResult(true);
}
else
{
lock (_errorBuilder)
{
_errorBuilder.AppendLine(e.Data);
}
}
};
var selfReference = new WeakReference<StandaloneSiloHandle>(this);
_processExitHandler = (o, e) =>
{
if (selfReference.TryGetTarget(out var target))
{
try
{
target.Process.Kill(entireProcessTree: true);
}
catch
{
}
}
};
AppDomain.CurrentDomain.ProcessExit += _processExitHandler;
}
/// <summary>
/// Spawns a new process to host a silo, using the executable provided in the configuration's "ExecutablePath" property as the entry point.
/// </summary>
public static async Task<SiloHandle> Create(
string siloName,
IConfiguration configuration)
{
var executablePath = configuration[ExecutablePathConfigKey];
var result = new StandaloneSiloHandle(siloName, configuration, executablePath);
await result.StartAsync();
return result;
}
/// <summary>
/// Creates a delegate which spawns a silo in a new process, using the provided executable as the entry point for that silo.
/// </summary>
/// <param name="executablePath">The entry point for spawned silos.</param>
public static Func<string, IConfiguration, Task<SiloHandle>> CreateDelegate(string executablePath)
{
return async (siloName, configuration) =>
{
var result = new StandaloneSiloHandle(siloName, configuration, executablePath);
await result.StartAsync();
return result;
};
}
/// <summary>
/// Creates a delegate which spawns a silo in a new process, with the provided assembly (or its executable counterpart, if it is a library) being the entry point for that silo.
/// </summary>
/// <param name="assembly">The entry point for spawned silos. If the provided assembly is a library (dll), then its executable sibling assembly will be invoked instead.</param>
public static Func<string, IConfiguration, Task<SiloHandle>> CreateForAssembly(Assembly assembly)
{
var executablePath = assembly.Location;
var originalFileInfo = new FileInfo(executablePath);
if (!originalFileInfo.Exists)
{
throw new FileNotFoundException($"Cannot find assembly location for assembly {assembly}. Location property returned \"{executablePath}\"");
}
FileInfo target;
if (string.Equals(".dll", originalFileInfo.Extension))
{
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
target = new FileInfo(Path.GetFileNameWithoutExtension(originalFileInfo.FullName) + ".exe");
}
else
{
// On unix-like operating systems, executables generally do not have an extension.
target = new FileInfo(Path.GetFileNameWithoutExtension(originalFileInfo.FullName));
}
}
else
{
target = originalFileInfo;
}
if (!target.Exists)
{
throw new FileNotFoundException($"Target assembly \"{target.FullName}\" does not exist");
}
return CreateDelegate(target.FullName);
}
private async Task StartAsync()
{
try
{
if (!Process.Start())
{
throw new InvalidOperationException("No process was started");
}
}
catch (Exception)
{
isActive = false;
throw;
}
_runTask = Task.Run(async () =>
{
try
{
Process.BeginOutputReadLine();
Process.BeginErrorReadLine();
var waitForExit = Task.Factory.StartNew(
process => ((Process)process).WaitForExit(-1),
Process,
CancellationToken.None,
TaskCreationOptions.LongRunning | TaskCreationOptions.RunContinuationsAsynchronously,
TaskScheduler.Default);
await Task.WhenAll(waitForExit, _outputCloseEvent.Task, _errorCloseEvent.Task);
if (!await waitForExit)
{
try
{
Process.Kill();
}
catch
{
}
}
}
catch (Exception exception)
{
_startedEvent.TrySetException(exception);
}
});
var task = await Task.WhenAny(_startedEvent.Task, _outputCloseEvent.Task, _errorCloseEvent.Task);
if (!ReferenceEquals(task, _startedEvent.Task))
{
string output;
lock (_outputBuilder)
{
output = _outputBuilder.ToString();
}
string error;
lock (_errorBuilder)
{
error = _errorBuilder.ToString();
}
throw new Exception($"Process failed to start correctly.\nOutput:\n{output}\nError:\n{error}");
}
}
/// <inheritdoc />
public override async Task StopSiloAsync(bool stopGracefully)
{
var cancellation = new CancellationTokenSource();
var ct = cancellation.Token;
if (!stopGracefully) cancellation.Cancel();
await StopSiloAsync(ct);
}
/// <inheritdoc />
public override async Task StopSiloAsync(CancellationToken ct)
{
if (!IsActive) return;
try
{
if (ct.IsCancellationRequested)
{
this.Process?.Kill();
}
else
{
using var registration = ct.Register(() =>
{
var process = this.Process;
if (process is not null)
{
process.Kill();
}
});
await this.Process.StandardInput.WriteLineAsync(StandaloneSiloHost.ShutdownCommand);
var linkedCts = new CancellationTokenSource();
await Task.WhenAny(_runTask, Task.Delay(TimeSpan.FromMinutes(2), linkedCts.Token));
}
}
finally
{
this.isActive = false;
}
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (!this.IsActive) return;
if (disposing)
{
try
{
StopSiloAsync(true).GetAwaiter().GetResult();
}
catch
{
}
this.Process?.Dispose();
}
AppDomain.CurrentDomain.ProcessExit -= _processExitHandler;
}
/// <inheritdoc />
public override async ValueTask DisposeAsync()
{
if (!this.IsActive) return;
await StopSiloAsync(true).ConfigureAwait(false);
this.Process?.Dispose();
AppDomain.CurrentDomain.ProcessExit -= _processExitHandler;
}
}
}
| |
//
// System.Data.ForeignKeyConstraint.cs
//
// Author:
// Franklin Wise <gracenote@earthlink.net>
// Daniel Morgan <danmorg@sc.rr.com>
//
// (C) 2002 Franklin Wise
// (C) 2002 Daniel Morgan
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Data.Common;
namespace System.Data {
[Editor]
[DefaultProperty ("ConstraintName")]
[Serializable]
public class ForeignKeyConstraint : Constraint
{
private UniqueConstraint _parentUniqueConstraint;
//FIXME: create a class which will wrap this collection
private DataColumn [] _parentColumns;
//FIXME: create a class which will wrap this collection
private DataColumn [] _childColumns;
private Rule _deleteRule = Rule.Cascade;
private Rule _updateRule = Rule.Cascade;
private AcceptRejectRule _acceptRejectRule = AcceptRejectRule.None;
private string _parentTableName;
private string _childTableName;
//FIXME: remove those; and use only DataColumns[]
private string [] _parentColumnNames;
private string [] _childColumnNames;
private bool _dataColsNotValidated = false;
#region Constructors
public ForeignKeyConstraint(DataColumn parentColumn, DataColumn childColumn)
{
if (null == parentColumn || null == childColumn) {
throw new NullReferenceException("Neither parentColumn or" +
" childColumn can be null.");
}
_foreignKeyConstraint(null, new DataColumn[] {parentColumn},
new DataColumn[] {childColumn});
}
public ForeignKeyConstraint(DataColumn[] parentColumns, DataColumn[] childColumns)
{
_foreignKeyConstraint(null, parentColumns, childColumns);
}
public ForeignKeyConstraint(string constraintName, DataColumn parentColumn, DataColumn childColumn)
{
if (null == parentColumn || null == childColumn) {
throw new NullReferenceException("Neither parentColumn or" +
" childColumn can be null.");
}
_foreignKeyConstraint(constraintName, new DataColumn[] {parentColumn},
new DataColumn[] {childColumn});
}
public ForeignKeyConstraint(string constraintName, DataColumn[] parentColumns, DataColumn[] childColumns)
{
_foreignKeyConstraint(constraintName, parentColumns, childColumns);
}
//special case
[Browsable (false)]
public ForeignKeyConstraint(string constraintName, string parentTableName, string[] parentColumnNames, string[] childColumnNames, AcceptRejectRule acceptRejectRule, Rule deleteRule, Rule updateRule)
{
_dataColsNotValidated = true;
base.ConstraintName = constraintName;
// "parentTableName" is searched in the "DataSet" to which the "DataTable"
// from which AddRange() is called
// childTable is the "DataTable" which calls AddRange()
// Keep reference to parentTableName to resolve later
_parentTableName = parentTableName;
// Keep reference to parentColumnNames to resolve later
_parentColumnNames = parentColumnNames;
// Keep reference to childColumnNames to resolve later
_childColumnNames = childColumnNames;
_acceptRejectRule = acceptRejectRule;
_deleteRule = deleteRule;
_updateRule = updateRule;
}
internal void postAddRange (DataTable childTable)
{
// LAMESPEC - Does not say that this is mandatory
// Check whether childTable belongs to a DataSet
if (childTable.DataSet == null)
throw new InvalidConstraintException ("ChildTable : " + childTable.TableName + " does not belong to any DataSet");
DataSet dataSet = childTable.DataSet;
_childTableName = childTable.TableName;
// Search for the parentTable in the childTable's DataSet
if (!dataSet.Tables.Contains (_parentTableName))
throw new InvalidConstraintException ("Table : " + _parentTableName + "does not exist in DataSet : " + dataSet);
// Keep reference to parentTable
DataTable parentTable = dataSet.Tables [_parentTableName];
int i = 0, j = 0;
// LAMESPEC - Does not say which Exception is thrown
if (_parentColumnNames.Length < 0 || _childColumnNames.Length < 0)
throw new InvalidConstraintException ("Neither parent nor child columns can be zero length");
// LAMESPEC - Does not say which Exception is thrown
if (_parentColumnNames.Length != _childColumnNames.Length)
throw new InvalidConstraintException ("Both parent and child columns must be of same length");
DataColumn []parentColumns = new DataColumn [_parentColumnNames.Length];
DataColumn []childColumns = new DataColumn [_childColumnNames.Length];
// Search for the parentColumns in parentTable
foreach (string parentCol in _parentColumnNames){
if (!parentTable.Columns.Contains (parentCol))
throw new InvalidConstraintException ("Table : " + _parentTableName + "does not contain the column :" + parentCol);
parentColumns [i++] = parentTable. Columns [parentCol];
}
// Search for the childColumns in childTable
foreach (string childCol in _childColumnNames){
if (!childTable.Columns.Contains (childCol))
throw new InvalidConstraintException ("Table : " + _childTableName + "does not contain the column : " + childCol);
childColumns [j++] = childTable.Columns [childCol];
}
_validateColumns (parentColumns, childColumns);
_parentColumns = parentColumns;
_childColumns = childColumns;
}
#if NET_2_0
[MonoTODO]
public ForeignKeyConstraint (string constraintName, string parentTableName, string parentTableNamespace, string[] parentColumnNames, string[] childColumnNames, AcceptRejectRule acceptRejectRule, Rule deleteRule, Rule updateRule)
{
throw new NotImplementedException ();
}
#endif
private void _foreignKeyConstraint(string constraintName, DataColumn[] parentColumns,
DataColumn[] childColumns)
{
//Validate
_validateColumns(parentColumns, childColumns);
//Set Constraint Name
base.ConstraintName = constraintName;
//Keep reference to columns
_parentColumns = parentColumns;
_childColumns = childColumns;
}
#endregion // Constructors
#region Helpers
private void _validateColumns(DataColumn[] parentColumns, DataColumn[] childColumns)
{
//not null
if (null == parentColumns || null == childColumns)
throw new ArgumentNullException();
//at least one element in each array
if (parentColumns.Length < 1 || childColumns.Length < 1)
throw new ArgumentException("Neither ParentColumns or ChildColumns can't be" +
" zero length.");
//same size arrays
if (parentColumns.Length != childColumns.Length)
throw new ArgumentException("Parent columns and child columns must be the same length.");
DataTable ptable = parentColumns[0].Table;
DataTable ctable = childColumns[0].Table;
for (int i = 0; i < parentColumns.Length; i++) {
DataColumn pc = parentColumns[i];
DataColumn cc = childColumns[i];
//not null check
if (null == pc.Table)
throw new ArgumentException("All columns must belong to a table." +
" ColumnName: " + pc.ColumnName + " does not belong to a table.");
//All columns must belong to the same table
if (ptable != pc.Table)
throw new InvalidConstraintException("Parent columns must all belong to the same table.");
//not null check
if (null == cc.Table)
throw new ArgumentException("All columns must belong to a table." +
" ColumnName: " + pc.ColumnName + " does not belong to a table.");
//All columns must belong to the same table.
if (ctable != cc.Table)
throw new InvalidConstraintException("Child columns must all belong to the same table.");
if (pc.CompiledExpression != null)
throw new ArgumentException(String.Format("Cannot create a constraint based on Expression column {0}.", pc.ColumnName));
if (cc.CompiledExpression != null)
throw new ArgumentException(String.Format("Cannot create a constraint based on Expression column {0}.", cc.ColumnName));
}
//Same dataset. If both are null it's ok
if (ptable.DataSet != ctable.DataSet)
{
//LAMESPEC: spec says InvalidConstraintExceptoin
// impl does InvalidOperationException
throw new InvalidOperationException("Parent column and child column must belong to" +
" tables that belong to the same DataSet.");
}
for (int i = 0; i < parentColumns.Length; i++)
{
DataColumn pc = parentColumns[i];
DataColumn cc = childColumns[i];
//Can't be the same column
if (pc == cc)
throw new InvalidOperationException("Parent and child columns can't be the same column.");
if (! pc.DataType.Equals(cc.DataType))
{
//LAMESPEC: spec says throw InvalidConstraintException
// implementation throws InvalidOperationException
throw new InvalidConstraintException("Parent column is not type compatible with it's child"
+ " column.");
}
}
}
private void _validateRemoveParentConstraint(ConstraintCollection sender,
Constraint constraint, ref bool cancel, ref string failReason)
{
#if !NET_1_1
//if we hold a reference to the parent then cancel it
if (constraint == _parentUniqueConstraint)
{
cancel = true;
failReason = "Cannot remove UniqueConstraint because the"
+ " ForeignKeyConstraint " + this.ConstraintName + " exists.";
}
#endif
}
//Checks to see if a related unique constraint exists
//if it doesn't then a unique constraint is created.
//if a unique constraint can't be created an exception will be thrown
private void _ensureUniqueConstraintExists(ConstraintCollection collection,
DataColumn [] parentColumns)
{
//not null
if (null == parentColumns) throw new ArgumentNullException(
"ParentColumns can't be null");
UniqueConstraint uc = null;
//see if unique constraint already exists
//if not create unique constraint
if(parentColumns[0] != null)
uc = UniqueConstraint.GetUniqueConstraintForColumnSet(parentColumns[0].Table.Constraints, parentColumns);
if (null == uc) {
uc = new UniqueConstraint(parentColumns, false); //could throw
parentColumns [0].Table.Constraints.Add (uc);
}
//keep reference
_parentUniqueConstraint = uc;
//parentColumns [0].Table.Constraints.Add (uc);
//if this unique constraint is attempted to be removed before us
//we can fail the validation
//collection.ValidateRemoveConstraint += new DelegateValidateRemoveConstraint(
// _validateRemoveParentConstraint);
}
#endregion //Helpers
#region Properties
[DataCategory ("Data")]
[DataSysDescription ("For accept and reject changes, indicates what kind of cascading should take place across this relation.")]
[DefaultValue (AcceptRejectRule.None)]
public virtual AcceptRejectRule AcceptRejectRule {
get { return _acceptRejectRule; }
set { _acceptRejectRule = value; }
}
[DataCategory ("Data")]
[DataSysDescription ("Indicates the child columns of this constraint.")]
[ReadOnly (true)]
public virtual DataColumn[] Columns {
get { return _childColumns; }
}
[DataCategory ("Data")]
[DataSysDescription ("For deletions, indicates what kind of cascading should take place across this relation.")]
[DefaultValue (Rule.Cascade)]
public virtual Rule DeleteRule {
get { return _deleteRule; }
set { _deleteRule = value; }
}
[DataCategory ("Data")]
[DataSysDescription ("For updates, indicates what kind of cascading should take place across this relation.")]
[DefaultValue (Rule.Cascade)]
public virtual Rule UpdateRule {
get { return _updateRule; }
set { _updateRule = value; }
}
[DataCategory ("Data")]
[DataSysDescription ("Indicates the parent columns of this constraint.")]
[ReadOnly (true)]
public virtual DataColumn[] RelatedColumns {
get { return _parentColumns; }
}
[DataCategory ("Data")]
[DataSysDescription ("Indicates the child table of this constraint.")]
[ReadOnly (true)]
public virtual DataTable RelatedTable {
get {
if (_parentColumns != null)
if (_parentColumns.Length > 0)
return _parentColumns[0].Table;
throw new InvalidOperationException ("Property not accessible because 'Object reference not set to an instance of an object'");
}
}
[DataCategory ("Data")]
[DataSysDescription ("Indicates the table of this constraint.")]
[ReadOnly (true)]
public override DataTable Table {
get {
if (_childColumns != null)
if (_childColumns.Length > 0)
return _childColumns[0].Table;
throw new InvalidOperationException ("Property not accessible because 'Object reference not set to an instance of an object'");
}
}
internal bool DataColsNotValidated
{
get {
return (_dataColsNotValidated);
}
}
#endregion // Properties
#region Methods
public override bool Equals(object key)
{
ForeignKeyConstraint fkc = key as ForeignKeyConstraint;
if (null == fkc) return false;
//if the fk constrains the same columns then they are equal
if (! DataColumn.AreColumnSetsTheSame( this.RelatedColumns, fkc.RelatedColumns))
return false;
if (! DataColumn.AreColumnSetsTheSame( this.Columns, fkc.Columns) )
return false;
return true;
}
public override int GetHashCode()
{
//initialize hash1 and hash2 with default hashes
//any two DIFFERENT numbers will do here
int hash1 = 32, hash2 = 88;
int i;
//derive the hash code from the columns that way
//Equals and GetHashCode return Equal objects to be the
//same
//Get the first parent column hash
if (this.Columns.Length > 0)
hash1 ^= this.Columns[0].GetHashCode();
//get the rest of the parent column hashes if there any
for (i = 1; i < this.Columns.Length; i++)
{
hash1 ^= this.Columns[1].GetHashCode();
}
//Get the child column hash
if (this.RelatedColumns.Length > 0)
hash2 ^= this.Columns[0].GetHashCode();
for (i = 1; i < this.RelatedColumns.Length; i++)
{
hash2 ^= this.RelatedColumns[1].GetHashCode();
}
//combine the two hashes
return hash1 ^ hash2;
}
internal override void AddToConstraintCollectionSetup(
ConstraintCollection collection)
{
if (collection.Table != Table)
throw new InvalidConstraintException("This constraint cannot be added since ForeignKey doesn't belong to table " + RelatedTable.TableName + ".");
//run Ctor rules again
_validateColumns(_parentColumns, _childColumns);
//we must have a unique constraint on the parent
_ensureUniqueConstraintExists(collection, _parentColumns);
//Make sure we can create this thing
//AssertConstraint();
if (IsConstraintViolated())
throw new ArgumentException("This constraint cannot be enabled as not all values have corresponding parent values.");
//FIXME : if this fails and we created a unique constraint
//we should probably roll it back
// and remove index form Table
}
internal override void RemoveFromConstraintCollectionCleanup(
ConstraintCollection collection)
{
Index = null;
}
protected override bool IsConstraintViolated()
{
if (Table.DataSet == null || RelatedTable.DataSet == null)
return false;
if (!Table.DataSet.EnforceConstraints)
return false;
bool hasErrors = false;
foreach (DataRow row in Table.Rows) {
// first we check if all values in _childColumns place are nulls.
// if yes we return.
if (row.IsNullColumns(_childColumns))
continue;
// check whenever there is (at least one) parent row in RelatedTable
if(!RelatedTable.RowsExist(_parentColumns,_childColumns,row)) {
// if no parent row exists - constraint is violated
hasErrors = true;
string[] values = new string[_childColumns.Length];
for (int i = 0; i < _childColumns.Length; i++){
DataColumn col = _childColumns[i];
values[i] = row[col].ToString();
}
row.RowError = String.Format("ForeignKeyConstraint {0} requires the child key values ({1}) to exist in the parent table.",
ConstraintName, String.Join(",", values));
}
}
if (hasErrors)
//throw new ConstraintException("Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.");
return true;
return false;
}
internal override void AssertConstraint(DataRow row)
{
// first we check if all values in _childColumns place are nulls.
// if yes we return.
if (row.IsNullColumns(_childColumns))
return;
// check whenever there is (at least one) parent row in RelatedTable
if(!RelatedTable.RowsExist(_parentColumns,_childColumns,row)) {
// if no parent row exists - constraint is violated
throw new InvalidConstraintException(GetErrorMessage(row));
}
}
internal override bool IsColumnContained(DataColumn column)
{
for (int i = 0; i < _parentColumns.Length; i++)
if (column == _parentColumns[i])
return true;
for (int i = 0; i < _childColumns.Length; i++)
if (column == _childColumns[i])
return true;
return false;
}
internal override bool CanRemoveFromCollection(ConstraintCollection col, bool shouldThrow){
return true;
}
private string GetErrorMessage(DataRow row)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < _childColumns.Length; i++) {
sb.Append(row[_childColumns[0]].ToString());
if (i != _childColumns.Length - 1) {
sb.Append(',');
}
}
string valStr = sb.ToString();
return "ForeignKeyConstraint " + ConstraintName + " requires the child key values (" + valStr + ") to exist in the parent table.";
}
#endregion // Methods
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using RegionFlags = OpenSim.Framework.RegionFlags;
using Npgsql;
namespace OpenSim.Data.PGSQL
{
/// <summary>
/// A PGSQL Interface for the Region Server.
/// </summary>
public class PGSQLRegionData : IRegionData
{
private string m_Realm;
private List<string> m_ColumnNames = null;
private string m_ConnectionString;
private PGSQLManager m_database;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public PGSQLRegionData(string connectionString, string realm)
{
m_Realm = realm;
m_ConnectionString = connectionString;
m_database = new PGSQLManager(connectionString);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "GridStore");
m.Update();
}
LoadFieldTypes();
}
private void LoadFieldTypes()
{
m_FieldTypes = new Dictionary<string, string>();
string query = string.Format(@"select column_name,data_type
from INFORMATION_SCHEMA.COLUMNS
where table_name = lower('{0}');
", m_Realm);
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
{
conn.Open();
using (NpgsqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
m_FieldTypes.Add((string)rdr[0], (string)rdr[1]);
}
}
}
}
public List<RegionData> Get(string regionName, UUID scopeID)
{
string sql = "select * from "+m_Realm+" where lower(\"regionName\") like lower(:regionName) ";
if (scopeID != UUID.Zero)
sql += " and \"ScopeID\" = :scopeID";
sql += " order by lower(\"regionName\")";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName));
if (scopeID != UUID.Zero)
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public RegionData Get(int posX, int posY, UUID scopeID)
{
string sql = "select * from "+m_Realm+" where \"locX\" = :posX and \"locY\" = :posY";
if (scopeID != UUID.Zero)
sql += " and \"ScopeID\" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("posX", posX));
cmd.Parameters.Add(m_database.CreateParameter("posY", posY));
if (scopeID != UUID.Zero)
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public RegionData Get(UUID regionID, UUID scopeID)
{
string sql = "select * from "+m_Realm+" where uuid = :regionID";
if (scopeID != UUID.Zero)
sql += " and \"ScopeID\" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("regionID", regionID));
if (scopeID != UUID.Zero)
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
List<RegionData> ret = RunCommand(cmd);
if (ret.Count == 0)
return null;
return ret[0];
}
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY";
if (scopeID != UUID.Zero)
sql += " and \"ScopeID\" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("startX", startX));
cmd.Parameters.Add(m_database.CreateParameter("startY", startY));
cmd.Parameters.Add(m_database.CreateParameter("endX", endX));
cmd.Parameters.Add(m_database.CreateParameter("endY", endY));
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public List<RegionData> RunCommand(NpgsqlCommand cmd)
{
List<RegionData> retList = new List<RegionData>();
NpgsqlDataReader result = cmd.ExecuteReader();
while (result.Read())
{
RegionData ret = new RegionData();
ret.Data = new Dictionary<string, object>();
UUID regionID;
UUID.TryParse(result["uuid"].ToString(), out regionID);
ret.RegionID = regionID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
ret.RegionName = result["regionName"].ToString();
ret.posX = Convert.ToInt32(result["locX"]);
ret.posY = Convert.ToInt32(result["locY"]);
ret.sizeX = Convert.ToInt32(result["sizeX"]);
ret.sizeY = Convert.ToInt32(result["sizeY"]);
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "uuid")
continue;
if (s == "ScopeID")
continue;
if (s == "regionName")
continue;
if (s == "locX")
continue;
if (s == "locY")
continue;
ret.Data[s] = result[s].ToString();
}
retList.Add(ret);
}
return retList;
}
public bool Store(RegionData data)
{
if (data.Data.ContainsKey("uuid"))
data.Data.Remove("uuid");
if (data.Data.ContainsKey("ScopeID"))
data.Data.Remove("ScopeID");
if (data.Data.ContainsKey("regionName"))
data.Data.Remove("regionName");
if (data.Data.ContainsKey("posX"))
data.Data.Remove("posX");
if (data.Data.ContainsKey("posY"))
data.Data.Remove("posY");
if (data.Data.ContainsKey("sizeX"))
data.Data.Remove("sizeX");
if (data.Data.ContainsKey("sizeY"))
data.Data.Remove("sizeY");
if (data.Data.ContainsKey("locX"))
data.Data.Remove("locX");
if (data.Data.ContainsKey("locY"))
data.Data.Remove("locY");
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
string update = "update " + m_Realm + " set \"locX\"=:posX, \"locY\"=:posY, \"sizeX\"=:sizeX, \"sizeY\"=:sizeY ";
foreach (string field in fields)
{
update += ", ";
update += " \"" + field + "\" = :" + field;
if (m_FieldTypes.ContainsKey(field))
cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field], m_FieldTypes[field]));
else
cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field]));
}
update += " where uuid = :regionID";
if (data.ScopeID != UUID.Zero)
update += " and \"ScopeID\" = :scopeID";
cmd.CommandText = update;
cmd.Connection = conn;
cmd.Parameters.Add(m_database.CreateParameter("regionID", data.RegionID));
cmd.Parameters.Add(m_database.CreateParameter("regionName", data.RegionName));
cmd.Parameters.Add(m_database.CreateParameter("scopeID", data.ScopeID));
cmd.Parameters.Add(m_database.CreateParameter("posX", data.posX));
cmd.Parameters.Add(m_database.CreateParameter("posY", data.posY));
cmd.Parameters.Add(m_database.CreateParameter("sizeX", data.sizeX));
cmd.Parameters.Add(m_database.CreateParameter("sizeY", data.sizeY));
conn.Open();
try
{
if (cmd.ExecuteNonQuery() < 1)
{
string insert = "insert into " + m_Realm + " (uuid, \"ScopeID\", \"locX\", \"locY\", \"sizeX\", \"sizeY\", \"regionName\", \"" +
String.Join("\", \"", fields) +
"\") values (:regionID, :scopeID, :posX, :posY, :sizeX, :sizeY, :regionName, :" + String.Join(", :", fields) + ")";
cmd.CommandText = insert;
try
{
if (cmd.ExecuteNonQuery() < 1)
{
return false;
}
}
catch (Exception ex)
{
m_log.Warn("[PGSQL Grid]: Error inserting into Regions table: " + ex.Message + ", INSERT sql: " + insert);
}
}
}
catch (Exception ex)
{
m_log.Warn("[PGSQL Grid]: Error updating Regions table: " + ex.Message + ", UPDATE sql: " + update);
}
}
return true;
}
public bool SetDataItem(UUID regionID, string item, string value)
{
string sql = "update " + m_Realm +
" set \"" + item + "\" = :" + item + " where uuid = :UUID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("" + item, value));
cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
public bool Delete(UUID regionID)
{
string sql = "delete from " + m_Realm +
" where uuid = :UUID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
return Get((int)RegionFlags.DefaultRegion, scopeID);
}
public List<RegionData> GetDefaultHypergridRegions(UUID scopeID)
{
return Get((int)RegionFlags.DefaultHGRegion, scopeID);
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID);
RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y);
regions.Sort(distanceComparer);
return regions;
}
public List<RegionData> GetHyperlinks(UUID scopeID)
{
return Get((int)RegionFlags.Hyperlink, scopeID);
}
private List<RegionData> Get(int regionFlags, UUID scopeID)
{
string sql = "SELECT * FROM " + m_Realm + " WHERE (flags & " + regionFlags.ToString() + ") <> 0";
if (scopeID != UUID.Zero)
sql += " AND \"ScopeID\" = :scopeID";
using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString))
using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
}
}
| |
/*
Copyright (c) 2004-2006 Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Threading;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using PHP.Core.Reflection;
using System.Collections.Generic;
using PHP.Core.AST;
using System.Diagnostics;
namespace PHP.Core.Emit
{
/// <summary>
/// Utilities for emitting PHP classes.
/// </summary>
public static class PhpObjectBuilder
{
/// <summary>
/// Used by the <c>WrapperGen</c> to generate the <see cref="PopulateTypeDescMethodName"/> method.
/// </summary>
public struct InfoWithAttributes<T> where T : MemberInfo
{
public InfoWithAttributes(T info, PhpMemberAttributes attributes)
{
this.Info = info;
this.Attributes = attributes;
}
public T Info;
public PhpMemberAttributes Attributes;
}
#region Helper member names
/// <summary>
/// Name of the method that initializes (thread) static fields.
/// </summary>
/// <remarks>This name does not have the <x> format in order to be a valid C# identifier.</remarks>
public const string StaticFieldInitMethodName = "__InitializeStaticFields";
/// <summary>
/// Name of the method that populates the typedesc corresponding to the type.
/// </summary>
/// <remarks>This name does not have the <x> format in order to be a valid C# identifier.</remarks>
public const string PopulateTypeDescMethodName = "__PopulateTypeDesc";
/// <summary>
/// Name of the method that initializes instance fields.
/// </summary>
public const string InstanceFieldInitMethodName = "<InitializeInstanceFields>";
/// <summary>
/// Name of the field that contains reference to the corresponding <see cref="PhpTypeDesc"/>.
/// </summary>
public const string TypeDescFieldName = "<typeDesc>";
/// <summary>
/// Name of the field that contains reference to the corresponding <see cref="ClrObject"/>.
/// </summary>
public const string ProxyFieldName = "<proxy>";
#endregion
#region Constructors
internal const MethodAttributes DefaultConstructorAttributes = MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName;
/// <summary>
/// Attributes used while creating the short constructor of the class.
/// </summary>
internal const MethodAttributes ShortConstructorAttributes = MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName;
/// <summary>
/// Parameter types of the short constructor.
/// </summary>
internal static readonly Type[] ShortConstructorParamTypes = Types.ScriptContext_Bool;
/// <summary>
/// Attributes used while creating the long constructor of the class.
/// </summary>
internal const MethodAttributes LongConstructorAttributes = MethodAttributes.Public | MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName;
/// <summary>
/// Parameter types of the long constructor.
/// </summary>
internal static readonly Type[] LongConstructorParamTypes = Types.ScriptContext_DTypeDesc;
/// <summary>
/// Attributes used while creating the deserializing constructor of the class.
/// </summary>
internal const MethodAttributes DeserializingConstructorAttributes = MethodAttributes.Family |
MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
#if !SILVERLIGHT
/// <summary>
/// Parameter types of the deserializing constructor.
/// </summary>
internal static readonly Type[] DeserializingConstructorParamTypes = Types.SerializationInfo_StreamingContext;
#endif
/// <summary>
/// Emits constructors into a class.
/// </summary>
internal static void EmitClassConstructors(PhpType/*!*/ phpType)
{
#if !SILVERLIGHT
EmitDeserializingConstructor(phpType);
#endif
EmitShortConstructor(phpType);
EmitLongConstructor(phpType);
EmitFinalizer(phpType);
// emit CLR-friendly constructors based on the PHP constructor method effective for the type
if (phpType.IsExported)
EmitExportedConstructors(phpType);
}
/// <summary>
/// Emit the PhpType finalizer. The finalizer is emitted only if there is __destruct() function
/// and there is no finalizer in any base class already. The finalizer calls this.Dispose() which
/// calls __destruct() function directly.
/// </summary>
/// <param name="phpType"></param>
private static void EmitFinalizer(PhpType/*!*/phpType)
{
// only if __destruct was now defined in some base class, no need to override existing definition on Finalize
DRoutine basedestruct;
DRoutineDesc destruct;
if ((destruct = phpType.TypeDesc.GetMethod(Name.SpecialMethodNames.Destruct)) != null && (phpType.Base == null ||
phpType.Base.GetMethod(Name.SpecialMethodNames.Destruct, phpType, out basedestruct) == GetMemberResult.NotFound))
{
MethodBuilder finalizer_builder = phpType.RealTypeBuilder.DefineMethod("Finalize", MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Family, typeof(void), Type.EmptyTypes);
ILEmitter dil = new ILEmitter(finalizer_builder);
// exact Finalize() method pattern follows:
// try
dil.BeginExceptionBlock();
// this.Dispose(false)
dil.Emit(OpCodes.Ldarg_0);
dil.Emit(OpCodes.Ldc_I4_0);
dil.Emit(OpCodes.Callvirt, PHP.Core.Emit.Methods.DObject_Dispose);
// finally
dil.BeginFinallyBlock();
// Object.Finalize()
dil.Emit(OpCodes.Ldarg_0);
dil.Emit(OpCodes.Call, PHP.Core.Emit.Methods.Object_Finalize);
dil.EndExceptionBlock();
dil.Emit(OpCodes.Ret);
}
}
#if !SILVERLIGHT
/// <summary>
/// Emits deserializing (SerializiationInfo, StreamingContext) constructor.
/// </summary>
private static void EmitDeserializingConstructor(PhpType/*!*/ phpType)
{
// (SerializationInfo, StreamingContext) constructor
ConstructorBuilder ctor_builder = phpType.DeserializingConstructorBuilder;
if (ctor_builder != null)
{
ILEmitter cil = new ILEmitter(ctor_builder);
if (phpType.Base == null) EmitInvokePhpObjectDeserializingConstructor(cil);
else phpType.Base.EmitInvokeDeserializationConstructor(cil, phpType, null);
// [ __InitializeStaticFields(context) ]
cil.Emit(OpCodes.Call, Methods.ScriptContext.GetCurrentContext);
cil.EmitCall(OpCodes.Call, phpType.StaticFieldInitMethodInfo, null);
cil.Emit(OpCodes.Ret);
}
}
#endif
/// <summary>
/// Emits (ScriptContext, bool) constructor.
/// </summary>
private static void EmitShortConstructor(PhpType/*!*/ phpType)
{
// (ScriptContext,bool) constructor
ConstructorBuilder ctor_builder = phpType.ShortConstructorBuilder;
ctor_builder.DefineParameter(1, ParameterAttributes.None, "context");
ctor_builder.DefineParameter(2, ParameterAttributes.None, "newInstance");
ILEmitter cil = new ILEmitter(ctor_builder);
// invoke base constructor
if (phpType.Base == null) EmitInvokePhpObjectConstructor(cil);
else phpType.Base.EmitInvokeConstructor(cil, phpType, null);
// perform fast DObject.<typeDesc> init if we are in its subclass
if (phpType.Root is PhpType)
{
// [ if (GetType() == typeof(self)) this.typeDesc = self.<typeDesc> ]
cil.Ldarg(FunctionBuilder.ArgThis);
cil.Emit(OpCodes.Call, Methods.Object_GetType);
cil.Emit(OpCodes.Ldtoken, phpType.RealTypeBuilder);
cil.Emit(OpCodes.Call, Methods.GetTypeFromHandle);
Label label = cil.DefineLabel();
cil.Emit(OpCodes.Bne_Un_S, label);
if (true)
{
cil.Ldarg(FunctionBuilder.ArgThis);
cil.Emit(OpCodes.Ldsfld, phpType.TypeDescFieldInfo);
cil.Emit(OpCodes.Stfld, Fields.DObject_TypeDesc);
cil.MarkLabel(label);
}
}
// register this instance for finalization if it introduced the __destruct method
DRoutine destruct;
if (phpType.TypeDesc.GetMethod(Name.SpecialMethodNames.Destruct) != null && (phpType.Base == null ||
phpType.Base.GetMethod(Name.SpecialMethodNames.Destruct, phpType, out destruct) == GetMemberResult.NotFound))
{
cil.Ldarg(FunctionBuilder.ArgContextInstance);
cil.Ldarg(FunctionBuilder.ArgThis);
if (phpType.ProxyFieldInfo != null) cil.Emit(OpCodes.Ldfld, phpType.ProxyFieldInfo);
cil.Emit(OpCodes.Call, Methods.ScriptContext.RegisterDObjectForFinalization);
}
// [ <InitializeInstanceFields>(arg1) ]
cil.Ldarg(FunctionBuilder.ArgThis);
cil.Ldarg(FunctionBuilder.ArgContextInstance);
cil.EmitCall(OpCodes.Call, phpType.Builder.InstanceFieldInit, null);
// [ __InitializeStaticFields(arg1) ]
cil.Ldarg(FunctionBuilder.ArgContextInstance);
cil.EmitCall(OpCodes.Call, phpType.StaticFieldInitMethodInfo, null);
cil.Emit(OpCodes.Ret);
}
/// <summary>
/// Emits (ScriptContext, DTypeDesc) constructor.
/// </summary>
private static void EmitLongConstructor(PhpType/*!*/ phpType)
{
// (ScriptContext, DTypeDesc) constructor
ConstructorBuilder ctor_builder = phpType.LongConstructorBuilder;
ctor_builder.DefineParameter(1, ParameterAttributes.None, "context");
ctor_builder.DefineParameter(2, ParameterAttributes.None, "caller");
// [ this(arg1,true) ]
ILEmitter cil = new ILEmitter(ctor_builder);
cil.Ldarg(FunctionBuilder.ArgThis);
cil.Ldarg(FunctionBuilder.ArgContextInstance);
cil.LdcI4(1);
cil.Emit(OpCodes.Call, phpType.ShortConstructorInfo);
if (phpType.ProxyFieldInfo != null)
{
// [ <proxy>.InvokeConstructor(args) ]
cil.Ldarg(FunctionBuilder.ArgThis);
cil.Emit(OpCodes.Ldfld, phpType.ProxyFieldInfo);
cil.Ldarg(1);
cil.Ldarg(2);
cil.Emit(OpCodes.Call, Methods.DObject_InvokeConstructor);
}
else
{
// try to find constructor method and call it directly
// if it is publically visible without any reason to throw a warning in runtime
DRoutineDesc construct = null; // = found constructor; if not null, can be called statically without runtime checks
bool constructorFound = false;
// try to find constructor
for (DTypeDesc type_desc = phpType.TypeDesc; type_desc != null; type_desc = type_desc.Base)
{
construct = type_desc.GetMethod(Name.SpecialMethodNames.Construct);
if (construct == null)
construct = type_desc.GetMethod(new Name(type_desc.MakeSimpleName()));
if (construct != null)
{
constructorFound = true;
if (!construct.IsPublic || construct.IsStatic || construct.PhpRoutine == null || construct.PhpRoutine.ArgLessInfo == null)
construct = null; // invalid constructor found, fall back to dynamic behavior
break;
}
}
// emit constructor call
if (construct != null)
{
// publically visible not static constructor, can be called statically anywhere
// [ __construct( this, context.Stack ) ]
cil.Ldarg(FunctionBuilder.ArgThis); // this
cil.Ldarg(1);
cil.Emit(OpCodes.Ldfld, Emit.Fields.ScriptContext_Stack); // context.Stack
cil.Emit(OpCodes.Call, construct.PhpRoutine.ArgLessInfo); // __construct
cil.Emit(OpCodes.Pop);
}
else if (!constructorFound) // there is no ctor at all
{
// [ context.Stack.RemoveFrame() ]
cil.Ldarg(1);
cil.Emit(OpCodes.Ldfld, Emit.Fields.ScriptContext_Stack); // context.Stack
cil.Emit(OpCodes.Callvirt, Emit.Methods.PhpStack.RemoveFrame); // .RemoveFrame
}
else
{
// constructor should be checked in runtime (various visibility cases)
// warnings can be displayed
// [ InvokeConstructor(arg2) ]
cil.Ldarg(FunctionBuilder.ArgThis);
cil.Ldarg(1);
cil.Ldarg(2);
cil.Emit(OpCodes.Call, Methods.DObject_InvokeConstructor);
}
}
cil.Emit(OpCodes.Ret);
}
private static void EmitExportedConstructor(PhpType/*!*/ phpType, ConstructorBuilder/*!*/ ctorStubBuilder,
PhpMethod phpCtor, ParameterInfo[]/*!*/ parameters)
{
// set parameter names and attributes
if (phpCtor != null)
{
ClrStubBuilder.DefineStubParameters(
ctorStubBuilder,
phpCtor.Builder.Signature.FormalParams,
parameters);
}
// emit ctor body
ILEmitter cil = new ILEmitter(ctorStubBuilder);
// [ this(ScriptContext.CurrentContext ]
cil.Ldarg(FunctionBuilder.ArgThis);
cil.EmitCall(OpCodes.Call, Methods.ScriptContext.GetCurrentContext, null);
LocalBuilder sc_local = cil.DeclareLocal(Types.ScriptContext[0]);
cil.Stloc(sc_local);
cil.Ldloc(sc_local);
cil.LdcI4(1);
cil.Emit(OpCodes.Call, phpType.ShortConstructorInfo);
if (phpCtor != null)
{
// invoke the PHP ctor method
ClrStubBuilder.EmitMethodStubBody(
cil,
new Place(sc_local),
parameters,
new GenericTypeParameterBuilder[0],
Types.Void,
phpCtor,
phpCtor.DeclaringType);
}
else cil.Emit(OpCodes.Ret);
}
private static void EmitExportedConstructors(PhpType/*!*/ phpType)
{
PhpMethod ctor = phpType.GetConstructor() as PhpMethod;
foreach (StubInfo info in phpType.Builder.ClrConstructorStubs)
{
EmitExportedConstructor(
phpType,
info.ConstructorBuilder,
ctor,
info.Parameters);
}
}
/// <summary>
/// Defines CLR-friendly constructors based on a PHP "constructor" method.
/// </summary>
public static void DefineExportedConstructors(PhpType/*!*/ phpType)
{
phpType.Builder.ClrConstructorStubs = new List<StubInfo>();
PhpMethod ctor = phpType.GetConstructor() as PhpMethod;
if (ctor == null)
{
// the class defines (nor inherits) no constructor -> create a parameter-less CLR constructor
ConstructorBuilder ctor_builder =
phpType.RealTypeBuilder.DefineConstructor(
DefaultConstructorAttributes,
CallingConventions.Standard,
Type.EmptyTypes);
phpType.ClrConstructorInfos = new ConstructorInfo[] { ctor_builder };
phpType.Builder.ClrConstructorStubs.Add(
new StubInfo(ctor_builder, new ParameterInfo[0], StubInfo.EmptyGenericParameters, null));
}
else if (!ctor.IsAbstract)
{
Debug.Assert(!ctor.IsStatic && ctor.Signature.GenericParamCount == 0);
if (ctor.Builder == null)
{
// contructor not defined in this class
phpType.ClrConstructorInfos = new ConstructorInfo[0];
return;
}
// infer constructor visibility
List<ConstructorInfo> ctor_infos = new List<ConstructorInfo>();
MethodAttributes attr = Reflection.Enums.ToMethodAttributes(ctor.RoutineDesc.MemberAttributes);
foreach (StubInfo info in ClrStubBuilder.DefineMethodExportStubs(
ctor, phpType,
attr,
true,
delegate(string[] genericParamNames, object[] parameterTypes, object returnType)
{
// accept all overloads
return true;
}))
{
phpType.Builder.ClrConstructorStubs.Add(info);
// infos are returned in ascending order w.r.t. parameter count
ctor_infos.Add(info.ConstructorBuilder);
}
phpType.ClrConstructorInfos = ctor_infos.ToArray();
}
}
#if !SILVERLIGHT
/// <summary>
/// Generates the (<see cref="SerializationInfo"/>, <see cref="StreamingContext"/>) constructor.
/// </summary>
/// <param name="typeBuilder">The type builder.</param>
/// <remarks>
/// Part of the constructor body - containing a call to parent's deserializing constructor - is generated.
/// At least a <see cref="OpCodes.Ret"/> has to be emitted to make the constructor complete.
/// </remarks>
public static ConstructorBuilder DefineDeserializingConstructor(TypeBuilder typeBuilder)
{
ConstructorBuilder ctor_builder = typeBuilder.DefineConstructor(DeserializingConstructorAttributes,
CallingConventions.Standard, DeserializingConstructorParamTypes);
// define parameter names
ctor_builder.DefineParameter(1, ParameterAttributes.None, "info");
ctor_builder.DefineParameter(2, ParameterAttributes.None, "context");
// call the base type's deserializing constructor
ILEmitter il = new ILEmitter(ctor_builder);
il.Ldarg(FunctionBuilder.ArgThis);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, typeBuilder.BaseType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, DeserializingConstructorParamTypes, null));
return ctor_builder;
}
#endif
/// <summary>
/// Generates the (<see cref="ScriptContext"/>, <see cref="DTypeDesc"/>) constructor.
/// </summary>
/// <param name="typeBuilder">The type builder.</param>
/// <param name="shortConstructor">This type's short constructor.</param>
/// <returns>The constructor builder.</returns>
/// <remarks>
/// The entire constructor is generated. See <see cref="PHP.Core.PhpObject(PHP.Core.ScriptContext,DTypeDesc)"/>.
/// </remarks>
public static ConstructorBuilder GenerateLongConstructor(TypeBuilder typeBuilder, ConstructorInfo shortConstructor)
{
ConstructorBuilder ctor_builder = typeBuilder.DefineConstructor(LongConstructorAttributes,
CallingConventions.Standard, LongConstructorParamTypes);
// annotate with EditorBrowsable attribute
#if !SILVERLIGHT // Not available on Silverlight
ctor_builder.SetCustomAttribute(AttributeBuilders.EditorBrowsableNever);
#endif
// define parameter names
ctor_builder.DefineParameter(1, ParameterAttributes.None, "context");
ctor_builder.DefineParameter(2, ParameterAttributes.None, "caller");
// call this type's short constructor
ILEmitter il = new ILEmitter(ctor_builder);
il.Ldarg(FunctionBuilder.ArgThis);
il.Ldarg(FunctionBuilder.ArgContextInstance);
il.LdcI4(1);
il.Emit(OpCodes.Call, shortConstructor);
// call PhpObject.InvokeConstructor
il.Ldarg(FunctionBuilder.ArgThis);
il.Ldarg(1);
il.Ldarg(2);
il.Emit(OpCodes.Call, Methods.DObject_InvokeConstructor);
il.Emit(OpCodes.Ret);
return ctor_builder;
}
/// <summary>
/// Defines the (<see cref="ScriptContext"/>) constructor.
/// </summary>
/// <param name="typeBuilder">The type builder.</param>
/// <returns>The constructor builder.</returns>
/// <remarks>
/// Part of the constructor body - containing a call to parent's short constructor - is generated.
/// At least an <see cref="OpCodes.Ret"/> has to be emitted to make the constructor complete.
/// </remarks>
public static ConstructorBuilder DefineShortConstructor(TypeBuilder typeBuilder)
{
ConstructorBuilder ctor_builder = typeBuilder.DefineConstructor(ShortConstructorAttributes,
CallingConventions.Standard, ShortConstructorParamTypes);
// annotate with EditorBrowsable attribute
#if !SILVERLIGHT // Not available on Silverlight
ctor_builder.SetCustomAttribute(AttributeBuilders.EditorBrowsableNever);
#endif
// define parameter names
ctor_builder.DefineParameter(1, ParameterAttributes.None, "context");
ctor_builder.DefineParameter(2, ParameterAttributes.None, "newInstance");
// call the base type's short constructor
ILEmitter il = new ILEmitter(ctor_builder);
il.Ldarg(FunctionBuilder.ArgThis);
il.Ldarg(FunctionBuilder.ArgContextInstance);
il.Ldarg(2);
il.Emit(OpCodes.Call, typeBuilder.BaseType.GetConstructor(ShortConstructorParamTypes));
return ctor_builder;
}
private static void EmitInvokePhpObjectConstructor(ILEmitter/*!*/ il)
{
// [ base(arg1,arg2) ]
il.Ldarg(FunctionBuilder.ArgThis);
il.Ldarg(FunctionBuilder.ArgContextInstance);
il.Ldarg(2);
il.Emit(OpCodes.Call, Constructors.PhpObject.ScriptContext_Bool);
}
private static void EmitInvokePhpObjectDeserializingConstructor(ILEmitter/*!*/ il)
{
#if SILVERLIGHT // Not available on Silverlight
Debug.Fail("Deserialization not supported!");
throw new NotSupportedException("Deserialization not supported!");
#else
// [ base(arg0, arg1, arg2) ]
il.Ldarg(FunctionBuilder.ArgThis);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Call, Constructors.PhpObject.SerializationInfo_StreamingContext);
#endif
}
#endregion
#region Init field helpers
/// <summary>
/// Emits init field helpers (<c>__lastContext</c> field, <c><InitializeInstanceFields></c>
/// method and <c>__InitializeStaticFields</c> into a class.
/// </summary>
internal static void EmitInitFieldHelpers(PhpType phpType)
{
//
// <InitializeInstanceFields>
//
// <InitializeInstanceFields> method - will contain instance field initialization
phpType.Builder.InstanceFieldInit = phpType.RealTypeBuilder.DefineMethod(
InstanceFieldInitMethodName,
#if SILVERLIGHT
MethodAttributes.Public | MethodAttributes.HideBySig,
#else
MethodAttributes.Private | MethodAttributes.HideBySig,
#endif
CallingConventions.Standard,
Types.Void,
Types.ScriptContext);
phpType.Builder.InstanceFieldInitEmitter = new ILEmitter(phpType.Builder.InstanceFieldInit);
//
// <InitializeStaticFields>
//
// <InitializeStaticFields> method has already been defined during the analysis phase - will contain (thread)
// static field initialization
ILEmitter cil = new ILEmitter(phpType.StaticFieldInitMethodBuilder);
if (phpType.Builder.HasThreadStaticFields)
{
// __lastContext thread-static field - will contain the last SC that inited static fields for this thread
FieldBuilder last_context = phpType.RealTypeBuilder.DefineField(
"<lastScriptContext>",
Types.ScriptContext[0],
FieldAttributes.Private | FieldAttributes.Static);
// SILVERLIGHT: Not sure what this does & what would be the right behavior...
#if !SILVERLIGHT
last_context.SetCustomAttribute(AttributeBuilders.ThreadStatic);
#endif
//
Label init_needed_label = cil.DefineLabel();
// [ if (arg0 == __lastContext) ret ]
cil.Emit(OpCodes.Ldarg_0);
cil.Emit(OpCodes.Ldsfld, last_context);
cil.Emit(OpCodes.Bne_Un_S, init_needed_label);
cil.Emit(OpCodes.Ret);
// [ __lastContext = arg0 ]
cil.MarkLabel(init_needed_label);
cil.Emit(OpCodes.Ldarg_0);
cil.Emit(OpCodes.Stsfld, last_context);
// the rest of the method is created when fields are emitted
}
}
#endregion
#region Type desc population
/// <summary>
/// Generates a <c><PopulateTypeDesc></c> method that populates a <see cref="DTypeDesc"/>
/// at runtime (instead of reflecting the class).
/// </summary>
/// <param name="phpType">The class representation used in the compiler.</param>
internal static void GenerateTypeDescPopulation(PhpType phpType)
{
MethodBuilder populator = DefinePopulateTypeDescMethod(phpType.RealTypeBuilder);
ILEmitter il = new ILEmitter(populator);
// methods
foreach (KeyValuePair<Name, DRoutineDesc> pair in phpType.TypeDesc.Methods)
{
if (!pair.Value.IsAbstract)
{
EmitAddMethod(il, pair.Key.ToString(), pair.Value.MemberAttributes,
pair.Value.PhpMethod.ArgLessInfo);
}
}
// fields
foreach (KeyValuePair<VariableName, DPropertyDesc> pair in phpType.TypeDesc.Properties)
{
PhpField field = pair.Value.PhpField;
// determine whether we need to add this field
if (field.Implementor == field.DeclaringPhpType || field.UpgradesVisibility)
{
EmitAddProperty(il, phpType.Builder.RealOpenType, pair.Key.ToString(),
pair.Value.MemberAttributes, field.RealField);
}
}
// constants
foreach (KeyValuePair<VariableName, DConstantDesc> pair in phpType.TypeDesc.Constants)
{
EmitAddConstant(il, pair.Key.ToString(), pair.Value.ClassConstant);
}
il.Emit(OpCodes.Ret);
}
/// <summary>
/// Generates a <c>__PopulateTypeDesc</c> method that populates a <see cref="DTypeDesc"/>
/// at runtime (instead of reflecting the class).
/// </summary>
/// <param name="typeBuilder">The target <see cref="TypeBuilder"/>.</param>
/// <param name="methods">The methods to add to the type desc.</param>
/// <param name="fields">The fields to add to the type desc.</param>
/// <param name="constants">The constants to add to the type desc. Together with their value. (Consts are public static literal fields)</param>
/// <remarks>Used by WrapperGen.</remarks>
public static void GenerateTypeDescPopulation(TypeBuilder typeBuilder,
ICollection<InfoWithAttributes<MethodInfo>> methods,
ICollection<InfoWithAttributes<FieldInfo>> fields,
ICollection<KeyValuePair<FieldInfo, Object>> constants)
{
MethodBuilder populator = DefinePopulateTypeDescMethod(typeBuilder);
ILEmitter il = new ILEmitter(populator);
// methods
if (methods != null)
{
foreach (InfoWithAttributes<MethodInfo> info in methods)
{
EmitAddMethod(il, info.Info.Name, info.Attributes, info.Info);
}
}
// fields
if (fields != null)
{
foreach (InfoWithAttributes<FieldInfo> info in fields)
{
EmitAddProperty(il, info.Info.DeclaringType, info.Info.Name, info.Attributes, info.Info);
}
}
// constants
if (constants != null)
{
foreach (var info in constants)
{
EmitAddConstant(il, info.Key.Name, info.Value);
}
}
il.Emit(OpCodes.Ret);
}
private static void EmitAddMethod(ILEmitter il, string name, PhpMemberAttributes attributes, MethodInfo argless)
{
// [ typeDesc.AddMethod("method", attributes, new RoutineDelegate(method)) ]
il.Ldarg(0);
il.Emit(OpCodes.Ldstr, name);
il.LdcI4((int)attributes);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ldftn, argless);
il.Emit(OpCodes.Newobj, Constructors.RoutineDelegate);
il.Emit(OpCodes.Call, Methods.AddMethod);
}
private static void EmitAddProperty(ILEmitter il, Type realOpenType, string name, PhpMemberAttributes attributes,
FieldInfo field)
{
// [ typeDesc.AddProperty("field", attributes, new GetterDelegate(getter), new SetterDelegate(setter)) ]
il.Ldarg(0);
il.Emit(OpCodes.Ldstr, name);
il.LdcI4((int)attributes);
MethodInfo getter, setter;
EmitFieldAccessors(
(TypeBuilder)il.MethodBase.DeclaringType,
realOpenType,
field,
out getter,
out setter);
// getter
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ldftn, getter);
il.Emit(OpCodes.Newobj, Constructors.GetterDelegate);
// setter
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ldftn, setter);
il.Emit(OpCodes.Newobj, Constructors.SetterDelegate);
il.Emit(OpCodes.Call, Methods.AddProperty);
}
private static void EmitAddConstant(ILEmitter il, string name, object value)
{
// [ typeDesc.AddConstant("constant", value) ]
//Debug.Assert(constant.IsStatic);
il.Ldarg(0);
il.Emit(OpCodes.Ldstr, name);
il.LoadLiteralBox(value); // for non dynamic literal fields
//il.Emit(OpCodes.Ldsfld, constant); // for non literal field only !
il.Emit(OpCodes.Call, Methods.AddConstant);
}
private static void EmitAddConstant(ILEmitter/*!*/il, string/*!*/name, ClassConstant/*!*/constant)
{
// [ typeDesc.AddConstant("constant", value) ]
il.Ldarg(0);
il.Emit(OpCodes.Ldstr, name);
if (constant.HasValue && constant.RealField.IsLiteral)
{
il.LoadLiteralBox(constant.Value); // for non dynamic literal fields
}
else
{
il.Emit(OpCodes.Ldsfld, constant.RealField); // for non literal field only !
}
il.Emit(OpCodes.Call, Methods.AddConstant);
}
private static void EmitFieldAccessors(TypeBuilder typeBuilder, Type realOpenType, FieldInfo field,
out MethodInfo getter, out MethodInfo setter)
{
// getter
MethodBuilder getter_builder = typeBuilder.DefineMethod(
"<^Getter>",
#if SILVERLIGHT
MethodAttributes.Public | MethodAttributes.Static,
#else
MethodAttributes.PrivateScope | MethodAttributes.Static,
#endif
Types.Object[0],
Types.Object);
getter_builder.DefineParameter(1, ParameterAttributes.None, "instance");
PhpFieldBuilder.EmitGetterStub(new ILEmitter(getter_builder), field, realOpenType);
// setter
MethodBuilder setter_builder = typeBuilder.DefineMethod(
"<^Setter>",
#if SILVERLIGHT
MethodAttributes.Public | MethodAttributes.Static,
#else
MethodAttributes.PrivateScope | MethodAttributes.Static,
#endif
Types.Void,
Types.Object_Object);
setter_builder.DefineParameter(1, ParameterAttributes.None, "instance");
setter_builder.DefineParameter(2, ParameterAttributes.None, "value");
PhpFieldBuilder.EmitSetterStub(new ILEmitter(setter_builder), field, realOpenType);
getter = getter_builder;
setter = setter_builder;
}
#endregion
#region Utilities
/// <summary>
/// Defines the <c>__InitializeStaticFields</c> static method.
/// </summary>
/// <param name="typeBuilder">The <see cref="TypeBuilder"/> to define the method in.</param>
/// <returns>The <see cref="MethodBuilder"/>.</returns>
internal static MethodBuilder DefineStaticFieldInitMethod(TypeBuilder typeBuilder)
{
MethodBuilder method_builder = typeBuilder.DefineMethod(
StaticFieldInitMethodName,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
Types.Void,
Types.ScriptContext);
#if !SILVERLIGHT
method_builder.SetCustomAttribute(AttributeBuilders.EditorBrowsableNever);
#endif
method_builder.DefineParameter(1, ParameterAttributes.None, "context");
return method_builder;
}
/// <summary>
/// Defines the <c>__PopulateTypeDesc</c> static method.
/// </summary>
/// <param name="typeBuilder">The <see cref="TypeBuilder"/> to define the method in.</param>
/// <returns>The <see cref="MethodBuilder"/>.</returns>
internal static MethodBuilder DefinePopulateTypeDescMethod(TypeBuilder typeBuilder)
{
MethodBuilder method_builder = typeBuilder.DefineMethod(
PopulateTypeDescMethodName,
#if SILVERLIGHT
MethodAttributes.Public | MethodAttributes.Static,
#else
MethodAttributes.Private | MethodAttributes.Static,
#endif
Types.Void,
Types.PhpTypeDesc);
return method_builder;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading;
using System.IO;
class Program
{
static Random r = new Random();
static uint[] countWinnigs = new uint[9];
static void Main()
{
string[,] deck =
{
{"2\u2660","3\u2660","4\u2660","5\u2660","6\u2660","7\u2660","8\u2660","9\u2660","T\u2660","J\u2660","Q\u2660","K\u2660","A\u2660"},
{"2\u2663","3\u2663","4\u2663","5\u2663","6\u2663","7\u2663","8\u2663","9\u2663","T\u2663","J\u2663","Q\u2663","K\u2663","A\u2663"},
{"2\u2665","3\u2665","4\u2665","5\u2665","6\u2665","7\u2665","8\u2665","9\u2665","T\u2665","J\u2665","Q\u2665","K\u2665","A\u2665"},
{"2\u2666","3\u2666","4\u2666","5\u2666","6\u2666","7\u2666","8\u2666","9\u2666","T\u2666","J\u2666","Q\u2666","K\u2666","A\u2666"}
};
Dictionary<string, uint> points = new Dictionary<string, uint>()
{
{"ROYAL FLUSH", 500},
{"STRAIGHT FLUSH", 100},
{"4 OF A KIND", 40},
{"FULL HOUSE", 12},
{"FLUSH", 7},
{"STRAIGHT", 5},
{"3 OF A KIND", 3},
{"TWO PAIR", 2},
{"HIGH PAIR", 1}
};
string title = "ARCH DEVIL's POKER";
int heigth = 23;
int width = 60;
int cardWidth = 8;
int cardHeight = 7;
uint winnings = 0;
uint bet = 1;
uint maxBet = 10;
uint coins = 100;
int deals = 0;
Console.CursorVisible = false;
Console.Title = title;
Console.WindowHeight = heigth;
Console.WindowWidth = width;
Console.BufferHeight = heigth;
Console.BufferWidth = width;
//welcome screen - OK
Menu();
//MainScreen
while (coins > 0)
{
bool[] holdCards = new bool[5];
bool[] winDisplay = new bool[points.Count];
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkGreen;
for (int i = 1; i <= points.Count; i++)
{
PrintWinningBlock(points, i);
}
PrintOnPosition(width - 10, 2, coins.ToString().PadLeft(10, ' '));
PrintOnPosition(width - 5, 1, "Coins");
PrintOnPosition(width - 3, 5, "BET");
PrintOnPosition(width - 3, 6, bet.ToString().PadLeft(3, ' '));
PrintOnPosition(0, 10, new string('_', width));
PrintOnPosition(0, 12, new string('_', width));
for (int i = 0, j = 0; j < 5; i += 11, j++)
{
CardBack(cardHeight, cardWidth, i + 4, 14);
Thread.Sleep(130);
}
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.ForegroundColor = ConsoleColor.Yellow;
PrintOnPosition(15, 11, "Place your bet - up/down arrows");
// Bet
bet = Bet(bet, width, heigth, maxBet);
checked
{
try
{
coins -= bet;
PrintOnPosition(width - 10, 2, coins.ToString().PadLeft(10, ' '));
}
catch (OverflowException)
{
bet = coins;
coins = 0;
PrintOnPosition(width - 10, 2, "ALL IN".PadLeft(10, ' '));
PrintOnPosition(width - 2, 6, bet.ToString().PadLeft(2, ' '));
}
finally
{
PrintOnPosition(40, 8, "YOUR BET: " + bet);
}
}
//Draw - 5 cards - OK
var drawedCards = new List<string>();
var playCards = new string[5];
DrawCards(deck, r, drawedCards, holdCards, playCards);
//print card faces
PutFaceCard(cardWidth, cardHeight, holdCards, playCards);
PrintOnPosition(15, 11, "Press 1-5 to hold/unhold cards ");
//Hold
holdCards = HoldCard(holdCards);
for (int i = 0, j = 0; j < 5; i += 11, j++)
{
if (holdCards[j]) continue;
CardBack(cardHeight, cardWidth, i + 4, 14);
}
Thread.Sleep(500);
//redraw
DrawCards(deck, r, drawedCards, holdCards, playCards);
//print redrawn card faces
PutFaceCard(cardWidth, cardHeight, holdCards, playCards);
//Check for Winnings
uint winningCoins = CheckForWinnings(playCards, winDisplay, points);
coins += winningCoins * bet;
if (winningCoins != 0) winnings++;
for (int i = 1; i <= points.Count; i++)
{
if (!winDisplay[i - 1]) continue;
Console.ForegroundColor = ConsoleColor.Black;
Console.BackgroundColor = ConsoleColor.Cyan;
PrintWinningBlock(points, i);
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkGreen;
PrintOnPosition(40, 9, "COINS WON: " + winningCoins * bet);
deals++;
PrintOnPosition(15, 11, "spaceBar to continue - esc to exit ");
//Game Over or Next Deal
WriteInFile(countWinnigs, winnings, deals);
ConsoleKeyInfo button;
button = Console.ReadKey(true);
if (button.Key == ConsoleKey.Escape)
{
break;
}
}
Console.Clear();
PrintOnPosition((width - 28) / 2, heigth / 2 - 5, "GAME OVER");
using (StreamReader reader = new StreamReader("winnings.txt"))
{
string line = reader.ReadLine();
PrintOnPosition((width - 28) / 2, heigth / 2 - 3, line);
line = reader.ReadLine();
PrintOnPosition((width - 28) / 2, heigth / 2 - 1, line);
int couterLine = 1;
foreach (var key in points.Keys)
{
line = reader.ReadLine();
PrintOnPosition((width - 28) / 2, heigth / 2 + couterLine, string.Concat(key, ": ", line));
couterLine++;
}
}
}
private static void PrintWinningBlock(Dictionary<string, uint> points, int i)
{
var item = points.ElementAt(i - 1);
var itemKey = item.Key;
var itemValue = item.Value;
PrintOnPosition(1, i, itemKey);
PrintOnPosition(30, i, string.Concat("x", itemValue));
}
private static void WriteInFile(uint[] countWinnins, uint winnings, int deals)
{
using (StreamWriter win = new StreamWriter("winnings.txt"))
{
win.WriteLine("Total deals made: {0}", deals);
win.WriteLine("Total winnings: {0}", winnings);
for (int i = 0; i < 9; i++)
{
win.WriteLine(countWinnigs[i]);
}
}
}
private static uint CheckForWinnings(string[] playCards, bool[] winDisplay, Dictionary<string, uint> points)
{
var cardNumber = new int[playCards.Length];
if (playCards[0][1] == playCards[1][1] && playCards[0][1] == playCards[2][1] && playCards[0][1] == playCards[3][1] && playCards[0][1] == playCards[4][1])
{
ReshapeCards(playCards, cardNumber);
if (cardNumber[0] == cardNumber[1] - 1 && cardNumber[0] == cardNumber[2] - 2 && cardNumber[0] == cardNumber[3] - 3 && cardNumber[0] == cardNumber[4] - 4)
{
if (cardNumber[0] == 10)
{
//Royal flush
countWinnigs[0]++;
winDisplay[0] = true;
return points["ROYAL FLUSH"];
}
else
{
//straight flush
countWinnigs[1]++;
winDisplay[1] = true;
return points["STRAIGHT FLUSH"];
}
}
if (cardNumber[4] == 14 && cardNumber[0] == 2 && cardNumber[1] == 3 && cardNumber[2] == 4 && cardNumber[3] == 5)
{
//straight flush
countWinnigs[1]++;
winDisplay[1] = true;
return points["STRAIGHT FLUSH"];
}
else
{
//flush
countWinnigs[4]++;
winDisplay[4] = true;
return points["FLUSH"];
}
}
ReshapeCards(playCards, cardNumber);
if ((cardNumber[0] == cardNumber[1] && cardNumber[0] == cardNumber[2] && cardNumber[0] == cardNumber[3]) || (cardNumber[1] == cardNumber[2] && cardNumber[1] == cardNumber[3] && cardNumber[1] == cardNumber[4]))
{
//4 of a Kind
countWinnigs[2]++;
winDisplay[2] = true;
return points["4 OF A KIND"];
}
if ((cardNumber[0] == cardNumber[1] && cardNumber[0] == cardNumber[2] && cardNumber[3] == cardNumber[4]) || (cardNumber[0] == cardNumber[1] && cardNumber[2] == cardNumber[3] && cardNumber[2] == cardNumber[4]))
{
//Full House
countWinnigs[3]++;
winDisplay[3] = true;
return points["FULL HOUSE"];
}
if ((cardNumber[0] == cardNumber[1] - 1 && cardNumber[0] == cardNumber[2] - 2 && cardNumber[0] == cardNumber[3] - 3 && cardNumber[0] == cardNumber[4] - 4) || (cardNumber[4] == 14 && cardNumber[0] == 2 && cardNumber[1] == 3 && cardNumber[2] == 4 && cardNumber[3] == 5))
{
// straight
countWinnigs[5]++;
winDisplay[5] = true;
return points["STRAIGHT"];
}
if ((cardNumber[0] == cardNumber[1] && cardNumber[0] == cardNumber[2]) || (cardNumber[1] == cardNumber[2] && cardNumber[1] == cardNumber[3]) || (cardNumber[2] == cardNumber[3] && cardNumber[2] == cardNumber[4]))
{
// 3 of a kind
countWinnigs[6]++;
winDisplay[6] = true;
return points["3 OF A KIND"];
}
if ((cardNumber[0] == cardNumber[1] && (cardNumber[2] == cardNumber[3] || cardNumber[3] == cardNumber[4])) || (cardNumber[1] == cardNumber[2] && cardNumber[3] == cardNumber[4]))
{
// two pair
countWinnigs[7]++;
winDisplay[7] = true;
return points["TWO PAIR"];
}
if ((cardNumber[0] == cardNumber[1] && cardNumber[0] > 10) || (cardNumber[1] == cardNumber[2] && cardNumber[1] > 10) || (cardNumber[2] == cardNumber[3] && cardNumber[2] > 10) || (cardNumber[3] == cardNumber[4] && cardNumber[3] > 10))
{
// high pair
countWinnigs[8]++;
winDisplay[8] = true;
return points["HIGH PAIR"];
}
return 0;
}
private static void ReshapeCards(string[] playCards, int[] cardNumber)
{
for (int i = 0; i < playCards.Length; i++)
{
if (playCards[i][0] == 'T') cardNumber[i] = 10;
else if (playCards[i][0] == 'J') cardNumber[i] = 11;
else if (playCards[i][0] == 'Q') cardNumber[i] = 12;
else if (playCards[i][0] == 'K') cardNumber[i] = 13;
else if (playCards[i][0] == 'A') cardNumber[i] = 14;
else cardNumber[i] = int.Parse(playCards[i].Remove(playCards[i].Length - 1));
}
Array.Sort(cardNumber);
}
private static void PutFaceCard(int cardWidth, int cardHeight, bool[] holdCards, string[] playCards)
{
for (int i = 0, j = 0; j < 5; i += 11, j++)
{
if (holdCards[j]) continue;
if (playCards[j].Contains("\u2660") || playCards[j].Contains("\u2663")) Console.ForegroundColor = ConsoleColor.Black;
else Console.ForegroundColor = ConsoleColor.Red;
CardFace(cardHeight, cardWidth, i + 4, 14, playCards[j].ToString());
Thread.Sleep(200);
}
Console.BackgroundColor = ConsoleColor.DarkGreen;
Console.ForegroundColor = ConsoleColor.Yellow;
}
static uint Bet(uint bet, int width, int heigth, uint maxBet)
{
ConsoleKeyInfo keyPressed;
do
{
keyPressed = Console.ReadKey(true);
if (keyPressed.Key == ConsoleKey.UpArrow && bet < maxBet)
{
// sound for betting up
Console.Beep(364, 100);
Console.Beep(424, 100);
bet++;
PrintOnPosition(width - 2, 6, bet.ToString().PadLeft(2, ' '));
}
if (keyPressed.Key == ConsoleKey.DownArrow && bet > 1)
{
// sound for betting down
Console.Beep(424, 100);
Console.Beep(364, 100);
bet--;
PrintOnPosition(width - 2, 6, bet.ToString().PadLeft(2, ' '));
}
} while (keyPressed.Key != ConsoleKey.Spacebar);
// sound for you bet
Console.Beep(700, 200);
Console.Beep(700, 200);
return bet;
}
static bool[] HoldCard(bool[] cards)
{
ConsoleKeyInfo keyPressed;
do
{
keyPressed = Console.ReadKey(true);
if (keyPressed.Key == ConsoleKey.NumPad1 || keyPressed.Key == ConsoleKey.D1)
{
if (cards[0] == false)
{
Console.Beep(600, 150);
cards[0] = true;
PrintOnPosition(6, 21, "Hold");
}
else
{
Console.Beep(260, 170);
cards[0] = false;
PrintOnPosition(6, 21, " ");
}
}
if (keyPressed.Key == ConsoleKey.NumPad2 || keyPressed.Key == ConsoleKey.D2)
{
if (cards[1] == false)
{
Console.Beep(600, 150);
cards[1] = true;
PrintOnPosition(17, 21, "Hold");
}
else
{
Console.Beep(260, 170);
cards[1] = false;
PrintOnPosition(17, 21, " ");
}
}
if (keyPressed.Key == ConsoleKey.NumPad3 || keyPressed.Key == ConsoleKey.D3)
{
if (cards[2] == false)
{
Console.Beep(600, 150);
cards[2] = true;
PrintOnPosition(28, 21, "Hold");
}
else
{
Console.Beep(260, 170);
cards[2] = false;
PrintOnPosition(28, 21, " ");
}
}
if (keyPressed.Key == ConsoleKey.NumPad4 || keyPressed.Key == ConsoleKey.D4)
{
if (cards[3] == false)
{
Console.Beep(600, 150);
cards[3] = true;
PrintOnPosition(39, 21, "Hold");
}
else
{
Console.Beep(260, 170);
cards[3] = false;
PrintOnPosition(39, 21, " ");
}
}
if (keyPressed.Key == ConsoleKey.NumPad5 || keyPressed.Key == ConsoleKey.D5)
{
if (cards[4] == false)
{
Console.Beep(600, 150);
cards[4] = true;
PrintOnPosition(50, 21, "Hold");
}
else
{
Console.Beep(260, 170);
cards[4] = false;
PrintOnPosition(50, 21, " ");
}
}
} while (keyPressed.Key != ConsoleKey.Spacebar);
Console.Beep(700, 200);
Console.Beep(700, 200);
return cards;
}
private static void CardFace(int cardHeight, int cardWidth, int x, int y, string card)
{
string cardOk = card;
if (cardOk[0] == 'T') cardOk = "10" + card[1];
Console.BackgroundColor = ConsoleColor.White;
for (int i = 0; i < cardHeight; i++)
{
for (int j = 0; j < cardWidth; j++)
{
PrintOnPosition(x + j, y + i, " ");
PrintOnPosition(x, y, cardOk);
PrintOnPosition(x + 3, y + 3, cardOk);
PrintOnPosition(x + 5, y + 6, cardOk.PadLeft(3, ' '));
}
}
}
static bool Menu()
{
Console.TreatControlCAsInput = false;
Console.Clear();
Console.CursorVisible = false;
WriteColorString("--------------------5 Card Draw--------------------", 5, 1, ConsoleColor.Black, ConsoleColor.Yellow);
string[] menuchoice = { "Play", "How to play", "Exit" };
WriteColorString("use up and down arrow keys and press enter to choose", 3, 21, ConsoleColor.Black, ConsoleColor.White);
int choice = ChooseListBoxItem(menuchoice, 22, 5, ConsoleColor.DarkCyan, ConsoleColor.Yellow);
if (menuchoice[choice - 1] == "How to play")
{
Console.BackgroundColor = ConsoleColor.Black;
return HelpMenu();
}
else if (menuchoice[choice - 1] == "Exit")
{
Environment.Exit(0);
}
return false;
}
public static int ChooseListBoxItem(string[] items, int ucol, int urow, ConsoleColor back, ConsoleColor fore)
{
int numItems = items.Length;
int maxLength = items[0].Length;
for (int i = 1; i < numItems; i++)
{
if (items[i].Length > maxLength)
{
maxLength = items[i].Length;
}
}
int[] rightSpaces = new int[numItems];
for (int i = 0; i < numItems; i++)
{
rightSpaces[i] = maxLength - items[i].Length + 1;
}
int lcol = ucol + maxLength + 3;
int lrow = urow + numItems + 1;
DrawBox(ucol, urow, lcol, lrow, back, fore, true);
WriteColorString(" " + items[0] + new string(' ', rightSpaces[0]), ucol + 1, urow + 1, fore, back);
for (int i = 2; i <= numItems; i++)
{
WriteColorString(items[i - 1], ucol + 2, urow + i, back, fore);
}
ConsoleKeyInfo cki;
char key;
int choice = 1;
while (true)
{
cki = Console.ReadKey(true);
key = cki.KeyChar;
if (key == '\r') // enter
{
return choice;
}
else if (cki.Key == ConsoleKey.DownArrow)
{
WriteColorString(" " + items[choice - 1] + new string(' ', rightSpaces[choice - 1]), ucol + 1, urow + choice, back, fore);
if (choice < numItems)
{
choice++;
}
else
{
choice = 1;
}
WriteColorString(" " + items[choice - 1] + new string(' ', rightSpaces[choice - 1]), ucol + 1, urow + choice, fore, back);
}
else if (cki.Key == ConsoleKey.UpArrow)
{
WriteColorString(" " + items[choice - 1] + new string(' ', rightSpaces[choice - 1]), ucol + 1, urow + choice, back, fore);
if (choice > 1)
{
choice--;
}
else
{
choice = numItems;
}
WriteColorString(" " + items[choice - 1] + new string(' ', rightSpaces[choice - 1]), ucol + 1, urow + choice, fore, back);
}
}
}
public static void DrawBox(int ucol, int urow, int lcol, int lrow, ConsoleColor back, ConsoleColor fore, bool fill)
{
const char Horizontal = '\u2500';
const char Vertical = '\u2502';
const char UpperLeftCorner = '\u250c';
const char UpperRightCorner = '\u2510';
const char LowerLeftCorner = '\u2514';
const char LowerRightCorner = '\u2518';
string fillLine = fill ? new string(' ', lcol - ucol - 1) : "";
SetColors(back, fore);
// draw top edge
Console.SetCursorPosition(ucol, urow);
Console.Write(UpperLeftCorner);
for (int i = ucol + 1; i < lcol; i++)
{
Console.Write(Horizontal);
}
Console.Write(UpperRightCorner);
// draw sides
for (int i = urow + 1; i < lrow; i++)
{
Console.SetCursorPosition(ucol, i);
Console.Write(Vertical);
if (fill) Console.Write(fillLine);
Console.SetCursorPosition(lcol, i);
Console.Write(Vertical);
}
// draw bottom edge
Console.SetCursorPosition(ucol, lrow);
Console.Write(LowerLeftCorner);
for (int i = ucol + 1; i < lcol; i++)
{
Console.Write(Horizontal);
}
Console.Write(LowerRightCorner);
}
public static void WriteColorString(string s, int col, int row, ConsoleColor back, ConsoleColor fore)
{
SetColors(back, fore);
// write string
Console.SetCursorPosition(col, row);
Console.Write(s);
}
public static void SetColors(ConsoleColor back, ConsoleColor fore)
{
Console.BackgroundColor = back;
Console.ForegroundColor = fore;
}
public static void CleanUp()
{
Console.ResetColor();
Console.CursorVisible = true;
Console.Clear();
}
//The end of welcome menu
static void CardBack(int height, int width, int x, int y)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.DarkCyan;
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
PrintOnPosition(x + i, y + j, "*");
}
}
}
static bool HelpMenu()
{
Console.Clear();
// Console.ForegroundColor = ConsoleColor.Yellow;
WriteColorString("-------------------Help Menu-------------------", 7, 1, ConsoleColor.Black, ConsoleColor.Cyan);
PrintOnPosition(20, 6, "Keys 1 to 5: Hold cards");
PrintOnPosition(20, 8, "Spacebar: Draw cards");
PrintOnPosition(20, 9, "(You can hold any card)");
PrintOnPosition(20, 12, "Press ENTER to play");
while (true)
{
ConsoleKeyInfo key;
key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
return false;
}
}
}
static void PrintOnPosition(int x, int y, string c)
{
Console.SetCursorPosition(x, y);
Console.WriteLine(c);
}
private static void DrawCards(string[,] deck, Random r, List<string> drawedCards, bool[] holdCards, string[] playCards)
{
for (int i = 0; i < 5; i++)
{
if (holdCards[i]) continue;
playCards[i] = deck[r.Next(0, deck.GetLength(0)), r.Next(0, deck.GetLength(1))];
if (drawedCards.Contains(playCards[i]))
{
i--;
continue;
}
else drawedCards.Add(playCards[i]);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.