context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// ToInt64(System.Double)
/// </summary>
public class ConvertToInt32_5
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
//
// TODO: Add your negative test cases here
//
// TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method ToInt32(0<double<0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d >= 0.5);
int actual = Convert.ToInt32(d);
int expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt32(1>double>=0.5)");
try
{
double d;
do
d = TestLibrary.Generator.GetDouble(-55);
while (d < 0.5);
int actual = Convert.ToInt32(d);
int expected = 1;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt32(0)");
try
{
double d = 0d;
int actual = Convert.ToInt32(d);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt32(int32.max)");
try
{
double d = Int32.MaxValue;
int actual = Convert.ToInt32(d);
int expected = Int32.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify method ToInt32(int32.min)");
try
{
double d = Int32.MinValue;
int actual = Convert.ToInt32(d);
int expected = Int32.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("005.1", "Method ToInt32 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
double d = (double)Int32.MaxValue + 1;
int i = Convert.ToInt32(d);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
double d = (double)Int32.MinValue - 1;
int i = Convert.ToInt32(d);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt32_5 test = new ConvertToInt32_5();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt32_5");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//
// General.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
namespace Cogl
{
public static class General
{
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_create_context ();
public static void CreateContext ()
{
cogl_create_context ();
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_destroy_context ();
public static void DestroyContext ()
{
cogl_destroy_context ();
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern FeatureFlags cogl_get_features ();
public static FeatureFlags AvailableFeatures {
get { return cogl_get_features (); }
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern bool cogl_features_available (FeatureFlags features);
public static bool AreFeaturesAvailable (FeatureFlags features)
{
return cogl_features_available (features);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern bool cogl_check_extension (IntPtr name, IntPtr ext);
public static bool CheckExtension (string name, string extension)
{
IntPtr name_ptr = GLib.Marshaller.StringToPtrGStrdup (name);
IntPtr extension_ptr = GLib.Marshaller.StringToPtrGStrdup (extension);
try {
return cogl_check_extension (name_ptr, extension_ptr);
} finally {
GLib.Marshaller.Free (name_ptr);
GLib.Marshaller.Free (extension_ptr);
}
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern CoglSharp.FuncPtrNative cogl_get_proc_address (IntPtr name);
public static FuncPtr GetProcAddress (string name)
{
IntPtr ptr = GLib.Marshaller.StringToPtrGStrdup (name);
try {
return CoglSharp.FuncPtrWrapper.GetManagedDelegate (cogl_get_proc_address (ptr));
} finally {
GLib.Marshaller.Free (ptr);
}
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_perspective (float fovy, float aspect, float z_near, float z_far);
public static void Perspective (float fovy, float aspect, float zNear, float zFar)
{
cogl_perspective (fovy, aspect, zNear, zFar);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_frustum (float left, float right, float bottom, float top, float z_near, float z_far);
public static void Frustum (float left, float right, float bottom, float top, float zNear, float zFar)
{
cogl_frustum (left, right, bottom, top, zNear, zFar);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_setup_viewport (uint width, uint height, float fovy, float aspect, float z_near, float z_far);
public static void SetupViewport (uint width, uint height, float fovy, float aspect, float zNear, float zFar)
{
cogl_setup_viewport (width, height, fovy, aspect, zNear, zFar);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_viewport (uint width, uint height);
public static void SetupViewport (uint width, uint height)
{
cogl_viewport (width, height);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_get_modelview_matrix (out IntPtr matrix);
public static Matrix ModelViewMatrix {
get {
IntPtr matrix;
cogl_get_modelview_matrix (out matrix);
return (Matrix)Marshal.PtrToStructure (matrix, typeof (Matrix));
}
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_get_projection_matrix (out IntPtr matrix);
public static Matrix ProjectionMatrix {
get {
IntPtr matrix;
cogl_get_projection_matrix (out matrix);
return (Matrix)Marshal.PtrToStructure (matrix, typeof (Matrix));
}
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_get_viewport (ref float [] v);
public static float [] Viewport {
get {
float [] v = new float[4];
cogl_get_viewport (ref v);
return v;
}
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_push_matrix ();
public static void PushMatrix ()
{
cogl_push_matrix ();
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_pop_matrix ();
public static void PopMatrix ()
{
cogl_pop_matrix ();
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_scale (float x, float y, float z);
public static void Scale (float x, float y, float z)
{
cogl_scale (x, y, z);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_translate (float x, float y, float z);
public static void Translate (float x, float y, float z)
{
cogl_translate (x, y, z);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_rotate (float angle, float x, float y, float z);
public static void Rotate (float angle, float x, float y, float z)
{
cogl_rotate (angle, x, y, z);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_clear (IntPtr color, ulong buffers);
public static void Clear (Color color, ulong buffers)
{
cogl_clear (color == null ? IntPtr.Zero : color.Handle, buffers);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_get_bitmasks (out int red, out int green, out int blue, out int alpha);
public static void GetBitmasks (out int red, out int green, out int blue, out int alpha)
{
cogl_get_bitmasks (out red, out green, out blue, out alpha);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_enable_depth_test (bool setting);
public static void EnableDepthTest (bool setting)
{
cogl_enable_depth_test (setting);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_enable_backface_culling (bool setting);
public static void EnableBackfaceCulling (bool setting)
{
cogl_enable_backface_culling (setting);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_set_fog (IntPtr color, FogMode mode, float density, float z_near, float z_far);
public static void SetFog (Color color, FogMode mode, float density, float zNear, float zFar)
{
cogl_set_fog (color == null ? IntPtr.Zero : color.Handle, mode, density, zNear, zFar);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_disable_fog ();
public static void DisableFog ()
{
cogl_disable_fog ();
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_set_source (IntPtr material);
public static void SetSource (IntPtr coglMaterial)
{
cogl_set_source (coglMaterial);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_set_source_texture (IntPtr texture);
public static void SetSourceTexture (IntPtr coglTexture)
{
cogl_set_source_texture (coglTexture);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_set_source_color (IntPtr color);
public static void SetSourceColor (Color color)
{
cogl_set_source_color (color == null ? IntPtr.Zero : color.Handle);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_set_source_color4ub (byte red, byte green, byte blue, byte alpha);
public static void SetSourceColor4ub (byte red, byte green, byte blue, byte alpha)
{
cogl_set_source_color4ub (red, green, blue, alpha);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_set_source_color4f (float red, float green, float blue, float alpha);
public static void SetSourceColor4f (float red, float green, float blue, float alpha)
{
cogl_set_source_color4f (red, green, blue, alpha);
}
public static void SetSourceColor4f (double red, double green, double blue, double alpha)
{
cogl_set_source_color4f ((float)red, (float)green, (float)blue, (float)alpha);
}
[DllImport ("libclutter-win32-1.0-0.dll")]
private static extern void cogl_flush_gl_state (int flags);
public static void FlushGlState (int flags)
{
cogl_flush_gl_state (flags);
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace FileWrapper
{
[Flags]
enum WrapperOptions
{
None = 0,
Append = 1,
Binary = 2,
Literal = 4,
Manually = 8,
Recursively = 16,
ClearOutputDir = 32,
}
struct MyFileInfo
{
public FileInfo Info;
public DirectoryInfo Root;
public string SubPath
{
get
{
return Info.DirectoryName.Replace(Root.FullName, String.Empty).TrimStart(Path.DirectorySeparatorChar);
}
}
}
class Program
{
public static List<string> OptionStrings = new List<string> { "/a", "/b", "/s", "/m", "/r", "/c" };
public static List<WrapperOptions> OptionValues = new List<WrapperOptions> { WrapperOptions.Append, WrapperOptions.Binary, WrapperOptions.Literal, WrapperOptions.Manually, WrapperOptions.Recursively, WrapperOptions.ClearOutputDir };
public static uint LineCharCount = 150;
static uint ConvertInt(uint b1, uint b2, uint b3, uint b4)
{
return b1 | b2 << 8 | b3 << 16 | b4 << 24;
}
static void PrintHelp()
{
string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
Console.WriteLine("Welcome to FileWrapper {0}", version);
Console.WriteLine("Format: FileWrapper (outFile or outDir) [options] (inputFiles or inputDirs)");
Console.WriteLine("/a append to out file");
Console.WriteLine("/b binary mode");
Console.WriteLine("/s string literal mode");
Console.WriteLine("/m manually register");
Console.WriteLine("/r recursively");
Console.WriteLine("/c clear output dir");
Console.WriteLine("/? or /help show help");
Console.WriteLine("Default is /b /m");
}
static void Main(string[] args)
{
bool isHelp = args.Any(s => s == "/?" || s == "/help");
if (args.Length == 0 || isHelp)
{
PrintHelp();
}
else if (args.Length < 2)
{
Console.WriteLine("Error arguments!");
PrintHelp();
}
else
{
string outputFile = args[0];
var options = WrapperOptions.None;
var inputFiles = new List<string>();
for (int i = 1; i < args.Length; ++i)
{
int index = OptionStrings.IndexOf(args[i]);
if (index >= 0)
{
options |= OptionValues[index];
}
else
{
if (args[i].Contains('/'))
{
Console.WriteLine("Error arguments!");
PrintHelp();
return;
}
inputFiles.Add(args[i]);
}
}
if (options.HasFlag(WrapperOptions.Binary) && options.HasFlag(WrapperOptions.Literal))
{
Console.WriteLine("Cannot use -s and -b together!");
PrintHelp();
}
else
{
if (options == WrapperOptions.None)
{
options = WrapperOptions.Binary | WrapperOptions.Manually;
}
if (Path.HasExtension(outputFile))
{
SearchOption searchOption = options.HasFlag(WrapperOptions.Recursively)
? SearchOption.AllDirectories
: SearchOption.TopDirectoryOnly;
var allFiles = GetAllInputFiles(inputFiles, searchOption);
WrapperToFile(outputFile, options, allFiles);
}
else
{
SearchOption searchOption = options.HasFlag(WrapperOptions.Recursively)
? SearchOption.AllDirectories
: SearchOption.TopDirectoryOnly;
var allFiles = GetAllInputFiles(inputFiles, searchOption);
WrapperToDirectory(outputFile, options, allFiles);
}
}
}
Console.WriteLine("Success!");
}
static List<MyFileInfo> GetAllInputFiles(List<string> inputFiles, SearchOption searchOption)
{
List<MyFileInfo> result = new List<MyFileInfo>();
foreach (var inputFile in inputFiles)
{
if (Path.HasExtension(inputFile))
{
string dir = Path.GetDirectoryName(inputFile);
string ext = Path.GetFileName(inputFile);
var files = Directory.EnumerateFiles(dir, ext, searchOption);
foreach (var file in files)
{
result.Add(new MyFileInfo() { Info = new FileInfo(file), Root = new DirectoryInfo(Path.GetDirectoryName(inputFile)) });
}
}
else
{
//is path
var files = Directory.EnumerateFiles(inputFile, "*.*", searchOption);
foreach (var file in files)
{
result.Add(new MyFileInfo() { Info = new FileInfo(file), Root = new DirectoryInfo(Path.GetDirectoryName(inputFile)) });
}
}
}
return result;
}
static void WrapperToDirectory(string outputDir, WrapperOptions options, IEnumerable<MyFileInfo> inputFiles)
{
if (Directory.Exists(outputDir))
{
if (options.HasFlag(WrapperOptions.ClearOutputDir))
{
Directory.Delete(outputDir, true);
}
Directory.CreateDirectory(outputDir);
}
foreach (var myFileInfo in inputFiles)
{
string newOutDir = Path.Combine(outputDir, myFileInfo.SubPath);
if (!Directory.Exists(newOutDir))
{
Directory.CreateDirectory(newOutDir);
}
string newOutputFile = Path.Combine(newOutDir, myFileInfo.Info.Name.Replace('.', '_') + ".cpp");
// newOutputFile = Path.ChangeExtension(newOutputFile, ".cpp");
WrapperToFile(newOutputFile, options, new List<MyFileInfo>() { myFileInfo });
}
}
static void WrapperToFile(string outputFile, WrapperOptions options, IEnumerable<MyFileInfo> inputFiles)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
if (options.HasFlag(WrapperOptions.Append))
{
if (File.Exists(outputFile))
{
string temp = File.ReadAllText(outputFile);
sw.Write(temp);
}
}
else
{
string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
sw.WriteLine("//This file was created by FileWrapper {0}", version);
sw.WriteLine("//DO NOT EDIT");
sw.WriteLine("#include \"MedusaPreCompiled.h\"");
sw.WriteLine("#include \"Core/IO/MemoryFileAutoRegister.h\"");
}
foreach (var inputFile in inputFiles)
{
if (options.HasFlag(WrapperOptions.Binary))
{
WrapperBinary(sw, inputFile.Info.FullName, options.HasFlag(WrapperOptions.Manually));
}
else
{
WrapperString(sw, inputFile.Info.FullName, options.HasFlag(WrapperOptions.Manually));
}
}
sw.Close();
String result = sb.ToString();
if (options.HasFlag(WrapperOptions.Append))
{
System.IO.File.WriteAllText(outputFile, result);
}
else
{
if (File.Exists(outputFile))
{
string temp = File.ReadAllText(outputFile);
if (temp != result)
{
System.IO.File.WriteAllText(outputFile, result);
}
}
else
{
System.IO.File.WriteAllText(outputFile, result);
}
}
}
static void WrapperBinary(StringWriter sw, string file, bool isManually)
{
var info = new FileInfo(file);
string fieldName = "_" + info.Name.Replace('.', '_');
sw.WriteLine("#pragma region {0}", info.Name);
sw.WriteLine("MEDUSA_CONTENT_BEGIN;");
sw.WriteLine("const static uint {0}[] = {{", fieldName);
byte[] bytes = File.ReadAllBytes(file);
int size = bytes.Length;
var sb = new StringBuilder();
for (int i = 0; i < size; i += 4)
{
uint r;
if (i + 3 < size)
{
r = ConvertInt(bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]);
}
else
{
int d = size - 1 - i;
switch (d)
{
case 0:
r = ConvertInt(bytes[i], 0, 0, 0);
break;
case 1:
r = ConvertInt(bytes[i], bytes[i + 1], 0, 0);
break;
case 2:
r = ConvertInt(bytes[i], bytes[i + 1], bytes[i + 2], 0);
break;
default:
throw new Exception("Error");
}
}
string str = "0x" + Convert.ToString(r, 16) + ",";
sb.Append(str);
if (sb.Length >= LineCharCount)
{
sw.WriteLine(sb);
sb.Clear();
}
}
//last line
if (sb.Length > 0)
{
sw.WriteLine(sb);
}
sw.WriteLine("};");
if (isManually)
{
sw.WriteLine("//const static MemoryFileAutoRegister mRegister{0}(\"{1}\",{2},{3});", fieldName, info.Name, fieldName, size);
sw.WriteLine("static void Register{0}(){{MemoryFileAutoRegister::Register(\"{1}\",{2},{3});}}", fieldName, info.Name, fieldName, size);
}
else
{
sw.WriteLine("const static MemoryFileAutoRegister mRegister{0}(\"{1}\",{2},{3});", fieldName, info.Name, fieldName, size);
sw.WriteLine("//static void Register{0}(){{MemoryFileAutoRegister::Register(\"{1}\",{2},{3});}}", fieldName, info.Name, fieldName, size);
}
sw.WriteLine("MEDUSA_CONTENT_END;");
sw.WriteLine("#pragma endregion {0}", info.Name);
sw.WriteLine();
}
static void WrapperString(StringWriter sw, string file, bool isManually)
{
string[] allLines = File.ReadAllLines(file);
var info = new FileInfo(file);
string fieldName = "_" + info.Name.Replace('.', '_');
sw.WriteLine("#pragma region {0}", info.Name);
sw.WriteLine("MEDUSA_CONTENT_BEGIN;");
sw.WriteLine("const static char {0}[] = \"\\", fieldName);
foreach (var allLine in allLines)
{
var newLine = allLine.Replace("\"", "\\\"");
sw.WriteLine(newLine + "\\n\\");
}
sw.WriteLine("\";");
if (isManually)
{
sw.WriteLine("//const static MemoryFileAutoRegister mRegister{0}(FileIdRef(\"{1}\"),{2});", fieldName, info.Name, fieldName);
sw.WriteLine("static void Register{0}(){{MemoryFileAutoRegister::Register(FileIdRef(\"{1}\"),{2});}}", fieldName, info.Name, fieldName);
}
else
{
sw.WriteLine("const static MemoryFileAutoRegister mRegister{0}(FileIdRef(\"{1}\"),{2});", fieldName, info.Name, fieldName);
sw.WriteLine("//static void Register{0}(){{MemoryFileAutoRegister::Register(FileIdRef(\"{1}\"),{2});}}", fieldName, info.Name, fieldName);
}
sw.WriteLine("MEDUSA_CONTENT_END;");
sw.WriteLine("#pragma endregion {0}", info.Name);
sw.WriteLine();
}
}
}
| |
// AST.cs HDO, 2006-08-28
// ------
// Abstract syntax tree for MiniCpp.
//=====================================|========================================
#undef TEST_AST
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
public class SrcPos
{
public int line;
public int col;
public SrcPos()
{
this.line = MiniCppLex.tokenLine;
this.col = MiniCppLex.tokenCol;
} // SrcPos
} // SrcPos
// === Expressions ===
public abstract class Expr
{
public enum Kind
{
litOperandKind, varOperandKind,
unaryOperatorKind, binaryOperatorKind,
arrIdxOperatorKind, funcCallOperatorKind, newOperatorKind
};
public SrcPos srcPos;
public Kind kind;
public Type type;
public Expr next; /*for actual parameter lists*/
protected Expr(Kind kind, SrcPos sp)
{
if (sp == null)
sp = new SrcPos();
this.srcPos = sp;
this.kind = kind;
} // Expr
public override String ToString()
{
if (next == null)
return "";
else
return ", " + next.ToString();
} // ToString
} // Expr
// --- Operands ---
public abstract class Operand : Expr
{
protected Operand(Kind kind, SrcPos sp)
: base(kind, sp)
{
} // Operand
} // Operand
public class LitOperand : Operand
{
public int val;
public double dblVal;
public LitOperand(Type type, double val)
: base(Kind.litOperandKind, null)
{
this.type = type;
this.dblVal = val;
} // ConstOperand
public LitOperand(Type type, int val)
: base(Kind.litOperandKind, null)
{
this.type = type;
this.val = val;
} // ConstOperand
public override String ToString()
{
if (type == Type.boolType)
{
if (val == 0)
return "false";
else
return "true";
}
else if (type == Type.intType)
{
return /* "(" + type + ")" + */ val.ToString() +
base.ToString();
}
else if (type == Type.doubleType)
{
return dblVal.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) +
base.ToString();
}
else if (type == Type.voidPtrType)
{ // val == 0
return /* "(" + type + ")" + */ val.ToString() +
base.ToString();
}
else
return "???";
} // ToString
} // LitOperand
public class VarOperand : Operand
{
public Symbol sy;
public VarOperand(Symbol sy)
: base(Kind.varOperandKind, null)
{
this.type = sy.type;
this.sy = sy;
if (sy.kind != Symbol.Kind.undefKind &&
sy.kind != Symbol.Kind.constKind &&
sy.kind != Symbol.Kind.varKind &&
sy.kind != Symbol.Kind.parKind)
Errors.SemError(MiniCppLex.tokenLine, MiniCppLex.tokenCol,
"invalid symbol kind");
} // VarOperand
public override String ToString()
{
return sy.ToString() +
base.ToString();
} // ToString
} // VarOperand
// --- Operators ---
public abstract class Operator : Expr
{
protected Operator(Kind kind, SrcPos sp)
: base(kind, sp)
{
} // Operator
} // Operator
public class UnaryOperator : Operator
{
public enum Operation { undefOp, notOp, posOp, negOp };
public Operation op;
public Expr e;
public UnaryOperator(SrcPos sp, Operation op, Expr e)
: base(Expr.Kind.unaryOperatorKind, sp)
{
this.op = op;
this.e = e;
this.type = e.type;
if (op == Operation.undefOp)
{
Errors.SemError(sp.line, sp.col, "invalid operator");
return;
} // if
if (type == Type.undefType)
return;
if (op == Operation.notOp)
{
if (type != Type.boolType)
Errors.SemError(sp.line, sp.col, "expr of type bool expected");
}
else
{ // op == Operation.posOp || op == Operation.negOp)
if (type != Type.intType)
Errors.SemError(sp.line, sp.col, "expr of type int expected");
} // else
} // UnaryOperator
private String OperatorFor(Operation op)
{
switch (op)
{
case Operation.notOp:
return "not";
case Operation.posOp:
return "+";
case Operation.negOp:
return "-";
default:
return "???";
} // switch
} // OperatorFor
public override String ToString()
{
return OperatorFor(op) + " " + e.ToString() +
base.ToString();
} // ToString
} // UnaryOperator
public class BinaryOperator : Operator
{
public enum Operation
{
undefOp,
orOp, andOp,
eqOp, neOp, ltOp, leOp, gtOp, geOp,
addOp, subOp, mulOp, divOp, modOp
};
public Operation op;
public Expr left, right;
public BinaryOperator(SrcPos sp, Operation op, Expr left, Expr right)
: base(Expr.Kind.binaryOperatorKind, sp)
{
this.op = op;
this.left = left;
this.right = right;
if (op == Operation.undefOp)
Errors.SemError(sp.line, sp.col, "invalid operator");
if (left.type == Type.undefType || right.type == Type.undefType)
{
this.type = Type.undefType;
return;
} // if
if (op == Operation.orOp || op == Operation.andOp)
{
if (left.type != Type.boolType || right.type != Type.boolType)
{
Errors.SemError(sp.line, sp.col, "bool operands needed");
this.type = Type.undefType;
}
else
this.type = Type.boolType;
}
else if (op == Operation.eqOp || op == Operation.neOp ||
op == Operation.ltOp || op == Operation.leOp ||
op == Operation.gtOp || op == Operation.geOp)
{
if (left.type != right.type)
{
Errors.SemError(sp.line, sp.col, "type mismatch in operands");
this.type = Type.undefType;
}
else
this.type = Type.boolType;
}
else
{ // addOp, subOp, mulOp, divOp, modOp
if (left.type == Type.intType && right.type == Type.intType)
{
this.type = Type.intType;
}
else if (left.type == Type.doubleType && right.type == Type.doubleType)
{
this.type = Type.doubleType;
}
else
{
Errors.SemError(sp.line, sp.col, "operands of type integer or double expected");
this.type = Type.undefType;
}
} // else
} // BinaryOperator
private String OperatorFor(Operation op)
{
switch (op)
{
case Operation.orOp:
return "||";
case Operation.andOp:
return "&&";
case Operation.eqOp:
return "==";
case Operation.neOp:
return "!=";
case Operation.ltOp:
return "<";
case Operation.leOp:
return "<=";
case Operation.gtOp:
return ">";
case Operation.geOp:
return ">=";
case Operation.addOp:
return "+";
case Operation.subOp:
return "-";
case Operation.mulOp:
return "*";
case Operation.divOp:
return "/";
case Operation.modOp:
return "%";
default:
return "???";
} // switch
} // OperatorFor
public override String ToString()
{
return "(" + left.ToString() + ") " + OperatorFor(op) + " (" + right.ToString() + ")" +
base.ToString();
} // ToString
} // BinaryOperator
public class ArrIdxOperator : Operator
{
public VarOperand arr;
public Expr idx;
public ArrIdxOperator(SrcPos sp, VarOperand arr, Expr idx)
: base(Expr.Kind.arrIdxOperatorKind, sp)
{
this.arr = arr;
this.idx = idx;
this.type = Type.undefType;
if (arr.sy.kind == Symbol.Kind.undefKind)
return;
if (arr.sy.kind != Symbol.Kind.parKind &&
arr.sy.kind != Symbol.Kind.varKind)
{
Errors.SemError(sp.line, sp.col, "invalid symbol kind");
return;
} // if
if (idx.type == Type.undefType)
return;
if (arr.type != Type.boolPtrType &&
arr.type != Type.intPtrType)
{
Errors.SemError(sp.line, sp.col, "invalid array type");
return;
} // if
if (idx.type != Type.intType && idx.type != Type.doubleType)
{
Errors.SemError(sp.line, sp.col, "invalid index type");
return;
} // if
this.type = arr.type.BaseTypeOf();
} // ArrIdxOperator
public override String ToString()
{
return arr.ToString() + "[" + idx.ToString() + "]" +
base.ToString();
} // ToString
} // ArrIdxOperator
public class FuncCallOperator : Operator
{
public Symbol func;
public Expr apl;
public FuncCallOperator(SrcPos sp, Symbol func, Expr apl)
: base(Expr.Kind.funcCallOperatorKind, sp)
{
this.func = func;
this.apl = apl;
this.type = func.type;
if (func.kind == Symbol.Kind.undefKind)
return;
if (func.kind != Symbol.Kind.funcKind)
Errors.SemError(sp.line, sp.col, "symbol is no function");
Symbol fp = func.symbols;
if (fp == null && !func.defined && func.hadFuncDecl)
fp = func.funcDeclParList;
Expr ap = apl;
while (fp != null && fp.kind == Symbol.Kind.parKind &&
ap != null)
{
if (fp.kind != Symbol.Kind.undefKind && ap.type != Type.undefType &&
fp.type != ap.type)
{
Errors.SemError(sp.line, sp.col, "mismatch in type of parameters");
return;
} // if
fp = fp.next;
ap = ap.next;
} // while
if (((fp == null) || ((fp != null) && (fp.kind != Symbol.Kind.parKind))) &&
(ap == null))
{ } // both lists are empty
else
Errors.SemError(sp.line, sp.col, "mismatch in number of parameters");
} // FuncCallOperator
public override String ToString()
{
return func.ToString() + "(" + (apl == null ? "" : apl.ToString()) + ")" +
base.ToString();
} // ToString
} // FuncCallOperator
public class NewOperator : Operator
{
public Type elemType;
public Expr noe;
public NewOperator(SrcPos sp, Type elemType, Expr noe)
: base(Expr.Kind.newOperatorKind, sp)
{
this.elemType = elemType;
this.noe = noe;
this.type = Type.undefType;
if (elemType == Type.undefType || noe.type == Type.undefType)
return;
if (elemType == Type.boolPtrType || elemType == Type.boolPtrType)
{
Errors.SemError(sp.line, sp.col, "invalid type");
return;
} // if
if (noe.type != Type.intType && noe.type != Type.doubleType)
{
Errors.SemError(sp.line, sp.col, "invalid type");
return;
} // if
this.type = elemType.PtrTypeOf();
} // NewOperator
public override String ToString()
{
return "new " + elemType.ToString() + "[" + noe.ToString() + "]" +
base.ToString();
} // ToString
} // NewOperator
// === Statements ===
public abstract class Stat
{
public enum Kind
{
emptyStatKind, blockStatKind,
incStatKind, decStatKind, assignStatKind, callStatKind,
ifStatKind, whileStatKind, breakStatKind,
inputStatKind, outputStatKind, deleteStatKind, returnStatKind,
switchStatKind, caseStatKind
};
public SrcPos srcPos;
public Kind kind;
public Stat next;
protected Stat(Kind kind, SrcPos sp)
{
if (sp == null)
sp = new SrcPos();
this.srcPos = sp;
this.kind = kind;
} // Stat
} // Stat
public class EmptyStat : Stat
{
public EmptyStat(SrcPos sp)
: base(Stat.Kind.emptyStatKind, sp)
{
} // EmptyStat
} // EmptyStat
public class BlockStat : Stat
{
// local Symbols are added to function scope
public Stat statList;
public BlockStat(SrcPos sp, Stat statList)
: base(Stat.Kind.blockStatKind, sp)
{
this.statList = statList;
} // BlockStat
} // BlockStat
public class IncStat : Stat
{
public VarOperand vo;
public IncStat(SrcPos sp, VarOperand vo)
: base(Stat.Kind.incStatKind, sp)
{
this.vo = vo;
if (vo.sy.kind != Symbol.Kind.undefKind &&
vo.sy.kind != Symbol.Kind.varKind)
Errors.SemError(sp.line, sp.col, "no variable");
if (vo.sy.type != Type.undefType &&
vo.sy.type != Type.intType)
Errors.SemError(sp.line, sp.col, "invalid type");
} // IncStat
} // IncStat
public class DecStat : Stat
{
public VarOperand vo;
public DecStat(SrcPos sp, VarOperand vo)
: base(Stat.Kind.decStatKind, sp)
{
this.vo = vo;
if (vo.sy.kind != Symbol.Kind.undefKind &&
vo.sy.kind != Symbol.Kind.varKind)
Errors.SemError(sp.line, sp.col, "no variable");
if (vo.sy.type != Type.undefType &&
vo.sy.type != Type.intType)
Errors.SemError(sp.line, sp.col, "invalid type");
} // DecStat
} // DecStat
public class AssignStat : Stat
{
public Expr lhs;
public Expr rhs;
public AssignStat(SrcPos sp, Expr lhs, Expr rhs)
: base(Stat.Kind.assignStatKind, sp)
{
this.lhs = lhs;
this.rhs = rhs;
if (lhs is VarOperand)
{
VarOperand vo = lhs as VarOperand;
if (vo.sy.kind != Symbol.Kind.undefKind &&
vo.sy.kind != Symbol.Kind.parKind &&
vo.sy.kind != Symbol.Kind.varKind)
Errors.SemError(sp.line, sp.col, "lhs: no variable");
}
else if (lhs is ArrIdxOperator)
{
; // nothing to check
}
else
{
Errors.SemError(sp.line, sp.col, "lhs: invalid expression");
} // else
if (lhs.type == Type.undefType ||
rhs.type == Type.undefType ||
lhs.type == rhs.type)
return;
if (lhs.type.IsPtrType() &&
rhs.kind == Expr.Kind.litOperandKind &&
((LitOperand)rhs).type.kind == Type.Kind.intKind &&
((LitOperand)rhs).val == 0)
{
rhs.type = Type.voidPtrType; // change type of oprand form int to void*
return;
} // if
Errors.SemError(sp.line, sp.col, "type mismatch");
} // AssignStat
} // AssignStat
public class CallStat : Stat
{
public Symbol func;
public Expr apl;
public CallStat(SrcPos sp, Symbol func, Expr apl)
: base(Stat.Kind.callStatKind, sp)
{
this.func = func;
this.apl = apl;
if (func.kind == Symbol.Kind.undefKind)
return;
if (func.kind != Symbol.Kind.funcKind)
Errors.SemError(sp.line, sp.col, "symbol is no function");
Symbol fp = func.symbols;
if (fp == null && !func.defined && func.hadFuncDecl)
fp = func.funcDeclParList;
Expr ap = apl;
while (fp != null && fp.kind == Symbol.Kind.parKind &&
ap != null)
{
if (fp.kind != Symbol.Kind.undefKind && ap.type != Type.undefType &&
fp.type != ap.type)
{
Errors.SemError(sp.line, sp.col, "mismatch in type of parameters");
return;
} // if
fp = fp.next;
ap = ap.next;
} // while
if (((fp == null) || ((fp != null) && (fp.kind != Symbol.Kind.parKind))) &&
(ap == null))
{ } // both lists are empty
else
Errors.SemError(sp.line, sp.col, "mismatch in number of parameters");
} // CallStat
} // CallStat
public class IfStat : Stat
{
public Expr cond;
public Stat thenStat;
public Stat elseStat;
public IfStat(SrcPos sp, Expr cond, Stat thenStat, Stat elseStat)
: base(Stat.Kind.ifStatKind, sp)
{
this.cond = cond;
this.thenStat = thenStat;
this.elseStat = elseStat;
if (cond.type != Type.undefType && cond.type != Type.boolType)
Errors.SemError(sp.line, sp.col, "invalid condition type");
} // IfStat
} // IfStat
public class WhileStat : Stat
{
public Expr cond;
public Stat body;
public WhileStat(SrcPos sp, Expr cond, Stat body)
: base(Stat.Kind.whileStatKind, sp)
{
this.cond = cond;
this.body = body;
if (cond.type != Type.undefType && cond.type != Type.boolType)
Errors.SemError(sp.line, sp.col, "invalid condition type");
} // WhileStat
} // WhileStat
public class SwitchStat : Stat
{
public Expr expr;
public Stat caseStat;
public Stat defaultStat;
public SwitchStat(SrcPos sp, Expr e, Stat caseStat, Stat defaultStat)
: base(Stat.Kind.switchStatKind, sp)
{
this.expr = e;
this.caseStat = caseStat;
this.defaultStat = defaultStat;
Dictionary<int, Stat> caseDic = new Dictionary<int, Stat>();
var s = caseStat;
while (s != null)
{
CaseStat curCase = s as CaseStat;
if (curCase == null)
{
Errors.SemError(sp.line, sp.col, "expected a case statement");
}
else
{
if (caseDic.ContainsKey(curCase.val))
{
Errors.SemError(sp.line, sp.col, "duplicate case for " + curCase.val);
}
else
{
caseDic.Add(curCase.val, curCase);
}
}
s = s.next;
}
if (e.type != Type.undefType && e.type != Type.intType)
Errors.SemError(sp.line, sp.col, "invalid type for switch");
} // SwitchStat
} // SwitchStat
public class CaseStat : Stat
{
public int val;
public Stat stat;
public CaseStat(SrcPos sp, int val, Stat stat)
: base(Stat.Kind.caseStatKind, sp)
{
this.val = val;
this.stat = stat;
} // CaseStat
} // CaseStat
public class BreakStat : Stat
{
public BreakStat(SrcPos sp)
: base(Stat.Kind.breakStatKind, sp)
{
} // BreakStat
} // BreakStat
public class InputStat : Stat
{
public VarOperand vo;
public InputStat(SrcPos sp, VarOperand vo)
: base(Stat.Kind.inputStatKind, sp)
{
this.vo = vo;
if (vo.sy.kind != Symbol.Kind.undefKind &&
vo.sy.kind != Symbol.Kind.parKind && vo.sy.kind != Symbol.Kind.varKind)
Errors.SemError(sp.line, sp.col, "invalid symbol kind");
if (vo.sy.type != Type.undefType &&
vo.sy.type != Type.boolType &&
vo.sy.type != Type.intType &&
vo.sy.type != Type.doubleType )
Errors.SemError(sp.line, sp.col, "invalid type");
} // InputStat
} // InputStat
public class OutputStat : Stat
{
public ArrayList values; // either Expr, String or special String "\n"
public OutputStat(SrcPos sp, ArrayList values)
: base(Stat.Kind.outputStatKind, sp)
{
this.values = values;
foreach (Object o in values)
{
if (o is Expr)
{
Expr e = o as Expr;
if (e != null &&
e.type != Type.undefType &&
e.type != Type.boolType &&
e.type != Type.intType &&
e.type != Type.doubleType )
Errors.SemError(sp.line, sp.col, "invalid type");
}
else if (o is String)
{
// nothing to check
}
else
{
Errors.SemError(sp.line, sp.col, "invalid value");
} // else
} // foreach
} // OutputSta
} // OutputStat
public class DeleteStat : Stat
{
public VarOperand vo;
public DeleteStat(SrcPos sp, VarOperand vo)
: base(Stat.Kind.deleteStatKind, sp)
{
this.vo = vo;
if (vo.sy.type == Type.undefType)
return;
if (!vo.sy.type.IsPtrType())
Errors.SemError(sp.line, sp.col, "invalid type");
} // DeleteStat
} // DeleteStat
public class ReturnStat : Stat
{
public Expr e;
public ReturnStat(SrcPos sp, Symbol funcSy, Expr e)
: base(Stat.Kind.returnStatKind, sp)
{
this.e = e;
if (funcSy.type == Type.undefType)
return;
if (funcSy.type == Type.voidType)
{
if (e != null)
Errors.SemError(sp.line, sp.col, "invalid return value for void func");
return;
} // if
if (e == null)
{
Errors.SemError(sp.line, sp.col, "missing return value");
return;
} // if
if (funcSy.type != e.type && e.type != Type.undefType)
Errors.SemError(sp.line, sp.col, "mismatch in return value and func type");
} // ReturnStat
} // ReturnStat
// === AST: abstract syntax tree ===
public class AST
{
#if TEST_AST
public static void Main(String[] args) {
Console.WriteLine("START: AST");
Console.WriteLine("END");
Console.WriteLine("type [CR] to continue ...");
Console.ReadLine();
} // Main
#endif
} // AST
// End of AST.cs
//=====================================|========================================
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.TpvFinal
{
public partial class ElegirMoneda
{
private global::Gtk.VBox vbox1;
private global::Valle.GtkUtilidades.MiLabel lblTitulo;
private global::Gtk.HBox hbox1;
private global::Gtk.VBox pneBillestes;
private global::Gtk.HButtonBox hbuttonbox1;
private global::Gtk.Button btn500;
private global::Gtk.Button btn200;
private global::Gtk.Button btn100;
private global::Gtk.HButtonBox hbuttonbox2;
private global::Gtk.Button btn50;
private global::Gtk.Button btn20;
private global::Gtk.Button btn10;
private global::Gtk.HButtonBox hbuttonbox3;
private global::Gtk.Button btn5;
private global::Gtk.Button btnManual;
private global::Gtk.VBox vbox3;
private global::Gtk.Image image69;
private global::Gtk.Label label1;
private global::Gtk.Button btnJusto;
private global::Gtk.VBox vbox4;
private global::Gtk.Image imgJusto;
private global::Gtk.Label label2;
private global::Gtk.HBox hbox2;
private global::Gtk.Label lblImporte;
private global::Gtk.Button btnSalir;
private global::Gtk.Button btnBackSp;
private global::Gtk.VBox pneMonedas;
private global::Gtk.HButtonBox hbuttonbox4;
private global::Gtk.Button btn2;
private global::Gtk.Button btnVenteC;
private global::Gtk.HButtonBox hbuttonbox5;
private global::Gtk.Button btn1;
private global::Gtk.Button btn10C;
private global::Gtk.HButtonBox hbuttonbox6;
private global::Gtk.Button btn50C;
private global::Gtk.Button btn5C;
private global::Gtk.HButtonBox hbuttonbox7;
private global::Gtk.Button btnCancelar;
private global::Gtk.Button btnAceptar;
protected virtual void Init ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.TpvFinal.ElegirMoneda
this.WidthRequest = 700;
this.Name = "Valle.TpvFinal.ElegirMoneda";
this.Title = global::Mono.Unix.Catalog.GetString ("ElegirMoneda");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
this.Resizable = false;
this.AllowGrow = false;
this.SkipTaskbarHint = true;
// Container child Valle.TpvFinal.ElegirMoneda.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
this.vbox1.BorderWidth = ((uint)(12));
// Container child vbox1.Gtk.Box+BoxChild
this.lblTitulo = new global::Valle.GtkUtilidades.MiLabel ();
this.lblTitulo.HeightRequest = 25;
this.lblTitulo.Events = ((global::Gdk.EventMask)(256));
this.lblTitulo.Name = "lblTitulo";
this.vbox1.Add (this.lblTitulo);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lblTitulo]));
w1.Position = 0;
w1.Expand = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.pneBillestes = new global::Gtk.VBox ();
this.pneBillestes.Name = "pneBillestes";
this.pneBillestes.Spacing = 6;
// Container child pneBillestes.Gtk.Box+BoxChild
this.hbuttonbox1 = new global::Gtk.HButtonBox ();
this.hbuttonbox1.Name = "hbuttonbox1";
this.hbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btn500 = new global::Gtk.Button ();
this.btn500.WidthRequest = 120;
this.btn500.HeightRequest = 100;
this.btn500.CanFocus = true;
this.btn500.Name = "btn500";
this.btn500.UseUnderline = true;
// Container child btn500.Gtk.Container+ContainerChild
global::Gtk.Alignment w2 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w3 = new global::Gtk.HBox ();
w3.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w4 = new global::Gtk.Image ();
w4.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.500E.jpeg");
w3.Add (w4);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w6 = new global::Gtk.Label ();
w3.Add (w6);
w2.Add (w3);
this.btn500.Add (w2);
this.hbuttonbox1.Add (this.btn500);
global::Gtk.ButtonBox.ButtonBoxChild w10 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btn500]));
w10.Expand = false;
w10.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btn200 = new global::Gtk.Button ();
this.btn200.CanFocus = true;
this.btn200.Name = "btn200";
this.btn200.UseUnderline = true;
// Container child btn200.Gtk.Container+ContainerChild
global::Gtk.Alignment w11 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w12 = new global::Gtk.HBox ();
w12.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w13 = new global::Gtk.Image ();
w13.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.200E.jpeg");
w12.Add (w13);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w15 = new global::Gtk.Label ();
w12.Add (w15);
w11.Add (w12);
this.btn200.Add (w11);
this.hbuttonbox1.Add (this.btn200);
global::Gtk.ButtonBox.ButtonBoxChild w19 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btn200]));
w19.Position = 1;
w19.Expand = false;
w19.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btn100 = new global::Gtk.Button ();
this.btn100.CanFocus = true;
this.btn100.Name = "btn100";
this.btn100.UseUnderline = true;
// Container child btn100.Gtk.Container+ContainerChild
global::Gtk.Alignment w20 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w21 = new global::Gtk.HBox ();
w21.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w22 = new global::Gtk.Image ();
w22.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.100E.jpeg");
w21.Add (w22);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w24 = new global::Gtk.Label ();
w21.Add (w24);
w20.Add (w21);
this.btn100.Add (w20);
this.hbuttonbox1.Add (this.btn100);
global::Gtk.ButtonBox.ButtonBoxChild w28 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btn100]));
w28.Position = 2;
w28.Expand = false;
w28.Fill = false;
this.pneBillestes.Add (this.hbuttonbox1);
global::Gtk.Box.BoxChild w29 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbuttonbox1]));
w29.Position = 0;
w29.Expand = false;
w29.Fill = false;
// Container child pneBillestes.Gtk.Box+BoxChild
this.hbuttonbox2 = new global::Gtk.HButtonBox ();
this.hbuttonbox2.Name = "hbuttonbox2";
this.hbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btn50 = new global::Gtk.Button ();
this.btn50.WidthRequest = 120;
this.btn50.HeightRequest = 100;
this.btn50.CanFocus = true;
this.btn50.Name = "btn50";
this.btn50.UseUnderline = true;
// Container child btn50.Gtk.Container+ContainerChild
global::Gtk.Alignment w30 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w31 = new global::Gtk.HBox ();
w31.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w32 = new global::Gtk.Image ();
w32.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.50E.jpeg");
w31.Add (w32);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w34 = new global::Gtk.Label ();
w31.Add (w34);
w30.Add (w31);
this.btn50.Add (w30);
this.hbuttonbox2.Add (this.btn50);
global::Gtk.ButtonBox.ButtonBoxChild w38 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btn50]));
w38.Expand = false;
w38.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btn20 = new global::Gtk.Button ();
this.btn20.CanFocus = true;
this.btn20.Name = "btn20";
this.btn20.UseUnderline = true;
// Container child btn20.Gtk.Container+ContainerChild
global::Gtk.Alignment w39 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w40 = new global::Gtk.HBox ();
w40.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w41 = new global::Gtk.Image ();
w41.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.20E.jpeg");
w40.Add (w41);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w43 = new global::Gtk.Label ();
w40.Add (w43);
w39.Add (w40);
this.btn20.Add (w39);
this.hbuttonbox2.Add (this.btn20);
global::Gtk.ButtonBox.ButtonBoxChild w47 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btn20]));
w47.Position = 1;
w47.Expand = false;
w47.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btn10 = new global::Gtk.Button ();
this.btn10.CanFocus = true;
this.btn10.Name = "btn10";
this.btn10.UseUnderline = true;
// Container child btn10.Gtk.Container+ContainerChild
global::Gtk.Alignment w48 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w49 = new global::Gtk.HBox ();
w49.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w50 = new global::Gtk.Image ();
w50.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.10E.jpeg");
w49.Add (w50);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w52 = new global::Gtk.Label ();
w49.Add (w52);
w48.Add (w49);
this.btn10.Add (w48);
this.hbuttonbox2.Add (this.btn10);
global::Gtk.ButtonBox.ButtonBoxChild w56 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btn10]));
w56.Position = 2;
w56.Expand = false;
w56.Fill = false;
this.pneBillestes.Add (this.hbuttonbox2);
global::Gtk.Box.BoxChild w57 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbuttonbox2]));
w57.Position = 1;
w57.Expand = false;
w57.Fill = false;
// Container child pneBillestes.Gtk.Box+BoxChild
this.hbuttonbox3 = new global::Gtk.HButtonBox ();
this.hbuttonbox3.Name = "hbuttonbox3";
this.hbuttonbox3.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild
this.btn5 = new global::Gtk.Button ();
this.btn5.WidthRequest = 120;
this.btn5.HeightRequest = 100;
this.btn5.CanFocus = true;
this.btn5.Name = "btn5";
this.btn5.UseUnderline = true;
// Container child btn5.Gtk.Container+ContainerChild
global::Gtk.Alignment w58 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w59 = new global::Gtk.HBox ();
w59.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w60 = new global::Gtk.Image ();
w60.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.5E.jpeg");
w59.Add (w60);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w62 = new global::Gtk.Label ();
w59.Add (w62);
w58.Add (w59);
this.btn5.Add (w58);
this.hbuttonbox3.Add (this.btn5);
global::Gtk.ButtonBox.ButtonBoxChild w66 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3[this.btn5]));
w66.Expand = false;
w66.Fill = false;
// Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild
this.btnManual = new global::Gtk.Button ();
this.btnManual.CanFocus = true;
this.btnManual.Name = "btnManual";
// Container child btnManual.Gtk.Container+ContainerChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.image69 = new global::Gtk.Image ();
this.image69.Name = "image69";
this.image69.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-edit", global::Gtk.IconSize.Dialog);
this.vbox3.Add (this.image69);
global::Gtk.Box.BoxChild w67 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.image69]));
w67.Position = 0;
// Container child vbox3.Gtk.Box+BoxChild
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Manual</big>");
this.label1.UseMarkup = true;
this.vbox3.Add (this.label1);
global::Gtk.Box.BoxChild w68 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label1]));
w68.Position = 1;
w68.Expand = false;
w68.Fill = false;
this.btnManual.Add (this.vbox3);
this.btnManual.Label = null;
this.hbuttonbox3.Add (this.btnManual);
global::Gtk.ButtonBox.ButtonBoxChild w70 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3[this.btnManual]));
w70.Position = 1;
w70.Expand = false;
w70.Fill = false;
// Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild
this.btnJusto = new global::Gtk.Button ();
this.btnJusto.CanFocus = true;
this.btnJusto.Name = "btnJusto1";
// Container child btnJusto1.Gtk.Container+ContainerChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 6;
// Container child vbox4.Gtk.Box+BoxChild
this.imgJusto = new global::Gtk.Image ();
this.imgJusto.Name = "imgJusto";
this.imgJusto.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.justo.jpeg");
this.vbox4.Add (this.imgJusto);
global::Gtk.Box.BoxChild w71 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.imgJusto]));
w71.Position = 0;
// Container child vbox4.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Justo</big>");
this.label2.UseMarkup = true;
this.vbox4.Add (this.label2);
global::Gtk.Box.BoxChild w72 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label2]));
w72.Position = 1;
w72.Expand = false;
w72.Fill = false;
this.btnJusto.Add (this.vbox4);
this.btnJusto.Label = null;
this.hbuttonbox3.Add (this.btnJusto);
global::Gtk.ButtonBox.ButtonBoxChild w74 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3[this.btnJusto]));
w74.Position = 2;
w74.Expand = false;
w74.Fill = false;
this.pneBillestes.Add (this.hbuttonbox3);
global::Gtk.Box.BoxChild w75 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbuttonbox3]));
w75.Position = 2;
w75.Expand = false;
w75.Fill = false;
// Container child pneBillestes.Gtk.Box+BoxChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.lblImporte = new global::Gtk.Label ();
this.lblImporte.Name = "lblImporte";
this.lblImporte.UseMarkup = true;
this.lblImporte.Wrap = true;
this.hbox2.Add (this.lblImporte);
global::Gtk.Box.BoxChild w76 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.lblImporte]));
w76.Position = 0;
// Container child hbox2.Gtk.Box+BoxChild
this.btnSalir = new global::Gtk.Button ();
this.btnSalir.WidthRequest = 120;
this.btnSalir.HeightRequest = 100;
this.btnSalir.CanFocus = true;
this.btnSalir.Name = "btnSalir";
// Container child btnSalir.Gtk.Container+ContainerChild
global::Gtk.Alignment w77 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w78 = new global::Gtk.HBox ();
w78.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w79 = new global::Gtk.Image ();
w79.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.~APP21MB.ICO");
w78.Add (w79);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w81 = new global::Gtk.Label ();
w78.Add (w81);
w77.Add (w78);
this.btnSalir.Add (w77);
this.hbox2.Add (this.btnSalir);
global::Gtk.Box.BoxChild w85 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.btnSalir]));
w85.Position = 1;
w85.Expand = false;
w85.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.btnBackSp = new global::Gtk.Button ();
this.btnBackSp.WidthRequest = 120;
this.btnBackSp.HeightRequest = 100;
this.btnBackSp.CanFocus = true;
this.btnBackSp.Name = "btnBackSp";
// Container child btnBackSp.Gtk.Container+ContainerChild
global::Gtk.Alignment w86 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w87 = new global::Gtk.HBox ();
w87.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w88 = new global::Gtk.Image ();
w88.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-undo", global::Gtk.IconSize.Dialog);
w87.Add (w88);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w90 = new global::Gtk.Label ();
w87.Add (w90);
w86.Add (w87);
this.btnBackSp.Add (w86);
this.hbox2.Add (this.btnBackSp);
global::Gtk.Box.BoxChild w94 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.btnBackSp]));
w94.Position = 2;
w94.Expand = false;
w94.Fill = false;
this.pneBillestes.Add (this.hbox2);
global::Gtk.Box.BoxChild w95 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbox2]));
w95.Position = 3;
w95.Expand = false;
w95.Fill = false;
this.hbox1.Add (this.pneBillestes);
global::Gtk.Box.BoxChild w96 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.pneBillestes]));
w96.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.pneMonedas = new global::Gtk.VBox ();
this.pneMonedas.Name = "pneMonedas";
this.pneMonedas.Spacing = 6;
// Container child pneMonedas.Gtk.Box+BoxChild
this.hbuttonbox4 = new global::Gtk.HButtonBox ();
this.hbuttonbox4.Name = "hbuttonbox4";
this.hbuttonbox4.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox4.Gtk.ButtonBox+ButtonBoxChild
this.btn2 = new global::Gtk.Button ();
this.btn2.WidthRequest = 120;
this.btn2.HeightRequest = 100;
this.btn2.CanFocus = true;
this.btn2.Name = "btn2";
this.btn2.UseUnderline = true;
// Container child btn2.Gtk.Container+ContainerChild
global::Gtk.Alignment w97 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w98 = new global::Gtk.HBox ();
w98.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w99 = new global::Gtk.Image ();
w99.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.dosE.jpeg");
w98.Add (w99);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w101 = new global::Gtk.Label ();
w98.Add (w101);
w97.Add (w98);
this.btn2.Add (w97);
this.hbuttonbox4.Add (this.btn2);
global::Gtk.ButtonBox.ButtonBoxChild w105 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox4[this.btn2]));
w105.Expand = false;
w105.Fill = false;
// Container child hbuttonbox4.Gtk.ButtonBox+ButtonBoxChild
this.btnVenteC = new global::Gtk.Button ();
this.btnVenteC.CanFocus = true;
this.btnVenteC.Name = "btnVenteC";
this.btnVenteC.UseUnderline = true;
// Container child btnVenteC.Gtk.Container+ContainerChild
global::Gtk.Alignment w106 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w107 = new global::Gtk.HBox ();
w107.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w108 = new global::Gtk.Image ();
w108.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.20C.jpeg");
w107.Add (w108);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w110 = new global::Gtk.Label ();
w107.Add (w110);
w106.Add (w107);
this.btnVenteC.Add (w106);
this.hbuttonbox4.Add (this.btnVenteC);
global::Gtk.ButtonBox.ButtonBoxChild w114 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox4[this.btnVenteC]));
w114.Position = 1;
w114.Expand = false;
w114.Fill = false;
this.pneMonedas.Add (this.hbuttonbox4);
global::Gtk.Box.BoxChild w115 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox4]));
w115.Position = 0;
w115.Expand = false;
w115.Fill = false;
// Container child pneMonedas.Gtk.Box+BoxChild
this.hbuttonbox5 = new global::Gtk.HButtonBox ();
this.hbuttonbox5.Name = "hbuttonbox5";
this.hbuttonbox5.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox5.Gtk.ButtonBox+ButtonBoxChild
this.btn1 = new global::Gtk.Button ();
this.btn1.WidthRequest = 120;
this.btn1.HeightRequest = 100;
this.btn1.CanFocus = true;
this.btn1.Name = "btn1";
this.btn1.UseUnderline = true;
// Container child btn1.Gtk.Container+ContainerChild
global::Gtk.Alignment w116 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w117 = new global::Gtk.HBox ();
w117.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w118 = new global::Gtk.Image ();
w118.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.UnE.jpeg");
w117.Add (w118);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w120 = new global::Gtk.Label ();
w117.Add (w120);
w116.Add (w117);
this.btn1.Add (w116);
this.hbuttonbox5.Add (this.btn1);
global::Gtk.ButtonBox.ButtonBoxChild w124 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox5[this.btn1]));
w124.Expand = false;
w124.Fill = false;
// Container child hbuttonbox5.Gtk.ButtonBox+ButtonBoxChild
this.btn10C = new global::Gtk.Button ();
this.btn10C.CanFocus = true;
this.btn10C.Name = "btn10C";
this.btn10C.UseUnderline = true;
// Container child btn10C.Gtk.Container+ContainerChild
global::Gtk.Alignment w125 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w126 = new global::Gtk.HBox ();
w126.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w127 = new global::Gtk.Image ();
w127.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.10C.jpeg");
w126.Add (w127);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w129 = new global::Gtk.Label ();
w126.Add (w129);
w125.Add (w126);
this.btn10C.Add (w125);
this.hbuttonbox5.Add (this.btn10C);
global::Gtk.ButtonBox.ButtonBoxChild w133 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox5[this.btn10C]));
w133.Position = 1;
w133.Expand = false;
w133.Fill = false;
this.pneMonedas.Add (this.hbuttonbox5);
global::Gtk.Box.BoxChild w134 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox5]));
w134.Position = 1;
w134.Expand = false;
w134.Fill = false;
// Container child pneMonedas.Gtk.Box+BoxChild
this.hbuttonbox6 = new global::Gtk.HButtonBox ();
this.hbuttonbox6.Name = "hbuttonbox6";
this.hbuttonbox6.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox6.Gtk.ButtonBox+ButtonBoxChild
this.btn50C = new global::Gtk.Button ();
this.btn50C.WidthRequest = 120;
this.btn50C.HeightRequest = 100;
this.btn50C.CanFocus = true;
this.btn50C.Name = "btn50C";
this.btn50C.UseUnderline = true;
// Container child btn50C.Gtk.Container+ContainerChild
global::Gtk.Alignment w135 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w136 = new global::Gtk.HBox ();
w136.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w137 = new global::Gtk.Image ();
w137.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.50C.jpeg");
w136.Add (w137);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w139 = new global::Gtk.Label ();
w136.Add (w139);
w135.Add (w136);
this.btn50C.Add (w135);
this.hbuttonbox6.Add (this.btn50C);
global::Gtk.ButtonBox.ButtonBoxChild w143 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox6[this.btn50C]));
w143.Expand = false;
w143.Fill = false;
// Container child hbuttonbox6.Gtk.ButtonBox+ButtonBoxChild
this.btn5C = new global::Gtk.Button ();
this.btn5C.CanFocus = true;
this.btn5C.Name = "btn5C";
// Container child btn5C.Gtk.Container+ContainerChild
global::Gtk.Alignment w144 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w145 = new global::Gtk.HBox ();
w145.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w146 = new global::Gtk.Image ();
w146.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.TpvFinal.iconos.5C.jpeg");
w145.Add (w146);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w148 = new global::Gtk.Label ();
w145.Add (w148);
w144.Add (w145);
this.btn5C.Add (w144);
this.hbuttonbox6.Add (this.btn5C);
global::Gtk.ButtonBox.ButtonBoxChild w152 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox6[this.btn5C]));
w152.Position = 1;
w152.Expand = false;
w152.Fill = false;
this.pneMonedas.Add (this.hbuttonbox6);
global::Gtk.Box.BoxChild w153 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox6]));
w153.Position = 2;
w153.Expand = false;
w153.Fill = false;
// Container child pneMonedas.Gtk.Box+BoxChild
this.hbuttonbox7 = new global::Gtk.HButtonBox ();
this.hbuttonbox7.Name = "hbuttonbox7";
this.hbuttonbox7.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1));
// Container child hbuttonbox7.Gtk.ButtonBox+ButtonBoxChild
this.btnCancelar = new global::Gtk.Button ();
this.btnCancelar.WidthRequest = 120;
this.btnCancelar.HeightRequest = 100;
this.btnCancelar.CanFocus = true;
this.btnCancelar.Name = "btnCancelar";
this.btnCancelar.UseUnderline = true;
// Container child btnCancelar.Gtk.Container+ContainerChild
global::Gtk.Alignment w154 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w155 = new global::Gtk.HBox ();
w155.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w156 = new global::Gtk.Image ();
w156.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog);
w155.Add (w156);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w158 = new global::Gtk.Label ();
w155.Add (w158);
w154.Add (w155);
this.btnCancelar.Add (w154);
this.hbuttonbox7.Add (this.btnCancelar);
global::Gtk.ButtonBox.ButtonBoxChild w162 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox7[this.btnCancelar]));
w162.Expand = false;
w162.Fill = false;
// Container child hbuttonbox7.Gtk.ButtonBox+ButtonBoxChild
this.btnAceptar = new global::Gtk.Button ();
this.btnAceptar.CanFocus = true;
this.btnAceptar.Name = "btnAceptar";
// Container child btnAceptar.Gtk.Container+ContainerChild
global::Gtk.Alignment w163 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f);
// Container child GtkAlignment.Gtk.Container+ContainerChild
global::Gtk.HBox w164 = new global::Gtk.HBox ();
w164.Spacing = 2;
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Image w165 = new global::Gtk.Image ();
w165.Pixbuf = global::Stetic.IconLoader.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Dialog);
w164.Add (w165);
// Container child GtkHBox.Gtk.Container+ContainerChild
global::Gtk.Label w167 = new global::Gtk.Label ();
w164.Add (w167);
w163.Add (w164);
this.btnAceptar.Add (w163);
this.hbuttonbox7.Add (this.btnAceptar);
global::Gtk.ButtonBox.ButtonBoxChild w171 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox7[this.btnAceptar]));
w171.Position = 1;
w171.Expand = false;
w171.Fill = false;
this.pneMonedas.Add (this.hbuttonbox7);
global::Gtk.Box.BoxChild w172 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox7]));
w172.Position = 3;
w172.Expand = false;
w172.Fill = false;
this.hbox1.Add (this.pneMonedas);
global::Gtk.Box.BoxChild w173 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.pneMonedas]));
w173.Position = 1;
this.vbox1.Add (this.hbox1);
global::Gtk.Box.BoxChild w174 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1]));
w174.Position = 1;
w174.Expand = false;
w174.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 702;
this.DefaultHeight = 525;
this.pneMonedas.Hide ();
this.btn500.Clicked += new global::System.EventHandler (this.OnBtn500Clicked);
this.btn200.Clicked += new global::System.EventHandler (this.OnBtn200Clicked);
this.btn100.Clicked += new global::System.EventHandler (this.OnBtn100Clicked);
this.btn50.Clicked += new global::System.EventHandler (this.OnBtn50Clicked);
this.btn20.Clicked += new global::System.EventHandler (this.OnBtn20Clicked);
this.btn10.Clicked += new global::System.EventHandler (this.OnBtn10Clicked);
this.btn5.Clicked += new global::System.EventHandler (this.OnBtn5Clicked);
this.btnManual.Clicked += new global::System.EventHandler (this.OnBtnManualClicked);
this.btnJusto.Clicked += new global::System.EventHandler (this.OnBtnJusto1Clicked);
this.btnSalir.Clicked += new global::System.EventHandler (this.OnBtnSalirClicked);
this.btnBackSp.Clicked += new global::System.EventHandler (this.OnBtnBackSpClicked);
this.btn2.Clicked += new global::System.EventHandler (this.OnBtn2Clicked);
this.btnVenteC.Clicked += new global::System.EventHandler (this.OnBtn21Clicked);
this.btn1.Clicked += new global::System.EventHandler (this.OnBtn1Clicked);
this.btn10C.Clicked += new global::System.EventHandler (this.OnBtn11Clicked);
this.btn50C.Clicked += new global::System.EventHandler (this.OnBtn51Clicked);
this.btn5C.Clicked += new global::System.EventHandler (this.OnBtn6Clicked);
this.btnCancelar.Clicked += new global::System.EventHandler (this.OnBtnCancelarClicked);
this.btnAceptar.Clicked += new global::System.EventHandler (this.OnBtnAceptarClicked);
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
/* VertexPainterWindow
* - Jason Booth
*
* Uses Unity 5.0+ MeshRenderer.additionalVertexStream so that you can paint per-instance vertex colors on your meshes.
* A component is added to your mesh to serialize this data and set it at load time. This is more effecient than making
* duplicate meshes, and certainly less painful than saving them as separate asset files on disk. However, if you only have
* one copy of the vertex information in your game and want to burn it into the original mesh, you can use the save feature
* to save a new version of your mesh with the data burned into the verticies, avoiding the need for the runtime component.
*
* In other words, bake it if you need to instance the paint job - however, if you want tons of the same instances painted
* uniquely in your scene, keep the component version and skip the baking..
*
* One possible optimization is to have the component free the array after updating the mesh when in play mode..
*
* Also supports burning data into the UV channels, in case you want some additional channels to work with, which also
* happen to be full 32bit floats. You can set a viewable range; so if your floats go from 0-120, it will remap it to
* 0-1 for display in the shader. That way you can always see your values, even when they go out of color ranges.
*
* Note that as of this writing Unity has a bug in the additionalVertexStream function. The docs claim the data applied here
* will supply or overwrite the data in the mesh, however, this is not true. Rather, it will only replace the data that's
* there - if your mesh has no color information, it will not upload the color data in additionalVertexStream, which is sad
* because the original mesh doesn't need this data. As a workaround, if your mesh does not have color channels on the verts,
* they will be created for you.
*
* There is another bug in additionalVertexStream, in that the mesh keeps disapearing in edit mode. So the component
* which holds the data caches the mesh and keeps assigning it in the Update call, but only when running in the editor
* and not in play mode.
*
* Really, the additionalVertexStream mesh should be owned by the MeshRenderer and saved as part of the objects instance
* data. That's essentially what the VertexInstaceStream component does, but it's annoying and wasteful of memory to do
* it this way since it doesn't need to be on the CPU at all. Enlighten somehow does this with the UVs it generates
* this way, but appears to be handled specially. Oh, Unity..
*/
namespace JBooth.VertexPainterPro
{
public partial class VertexPainterWindow : EditorWindow
{
enum Tab
{
Paint = 0,
Deform,
Flow,
Utility,
Custom
}
string[] tabNames =
{
"Paint",
"Deform",
"Flow",
"Utility",
"Custom"
};
static string sSwatchKey = "VertexPainter_Swatches";
ColorSwatches swatches = null;
Tab tab = Tab.Paint;
bool hideMeshWireframe = false;
bool DrawClearButton(string label)
{
if (GUILayout.Button(label, GUILayout.Width(46)))
{
return (EditorUtility.DisplayDialog("Confirm", "Clear " + label + " data?", "ok", "cancel"));
}
return false;
}
static Dictionary<string, bool> rolloutStates = new Dictionary<string, bool>();
bool DrawRollup(string text, bool defaultState = true)
{
GUI.skin.box.normal.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black;
var skin = GUI.skin.button;
GUI.skin.button = GUI.skin.box;
if (!rolloutStates.ContainsKey(text))
{
rolloutStates[text] = defaultState;
}
if (GUILayout.Button(text, new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)}))
{
rolloutStates[text] = !rolloutStates[text];
}
GUI.skin.button = skin;
return rolloutStates[text];
}
Vector2 scroll;
void OnGUI()
{
if (Selection.activeGameObject == null)
{
EditorGUILayout.LabelField("No objects selected. Please select an object with a MeshFilter and Renderer");
return;
}
if (swatches == null)
{
swatches = ColorSwatches.CreateInstance<ColorSwatches>();
if (EditorPrefs.HasKey(sSwatchKey))
{
JsonUtility.FromJsonOverwrite(EditorPrefs.GetString(sSwatchKey), swatches);
}
if (swatches == null)
{
swatches = ColorSwatches.CreateInstance<ColorSwatches>();
EditorPrefs.SetString(sSwatchKey, JsonUtility.ToJson(swatches, false));
}
}
DrawChannelGUI();
var ot = tab;
tab = (Tab)GUILayout.Toolbar((int)tab, tabNames);
if (ot != tab)
{
UpdateDisplayMode();
}
scroll = EditorGUILayout.BeginScrollView(scroll);
if (tab == Tab.Paint)
{
DrawPaintGUI();
}
else if (tab == Tab.Deform)
{
DrawDeformGUI();
}
else if (tab == Tab.Flow)
{
DrawFlowGUI();
}
else if (tab == Tab.Utility)
{
DrawUtilityGUI();
}
else if (tab == Tab.Custom)
{
DrawCustomGUI();
}
EditorGUILayout.EndScrollView();
}
void DrawChannelGUI()
{
EditorGUILayout.Separator();
GUI.skin.box.normal.textColor = Color.white;
if (DrawRollup("Vertex Painter"))
{
bool oldEnabled = enabled;
if (Event.current.isKey && Event.current.keyCode == KeyCode.Escape && Event.current.type == EventType.KeyUp)
{
enabled = !enabled;
}
enabled = GUILayout.Toggle(enabled, "Active (ESC)");
if (enabled != oldEnabled)
{
InitMeshes();
UpdateDisplayMode();
}
var oldShow = showVertexShader;
EditorGUILayout.BeginHorizontal();
showVertexShader = GUILayout.Toggle(showVertexShader, "Show Vertex Data (ctrl-V)");
if (oldShow != showVertexShader)
{
UpdateDisplayMode();
}
bool emptyStreams = false;
for (int i = 0; i < jobs.Length; ++i)
{
if (!jobs[i].HasStream())
emptyStreams = true;
}
if (emptyStreams)
{
if (GUILayout.Button("Add Streams"))
{
for (int i = 0; i < jobs.Length; ++i)
{
jobs[i].EnforceStream();
}
UpdateDisplayMode();
}
}
EditorGUILayout.EndHorizontal();
brushVisualization = (BrushVisualization)EditorGUILayout.EnumPopup("Brush Visualization", brushVisualization);
showVertexPoints = GUILayout.Toggle(showVertexPoints, "Show Brush Influence");
bool oldHideMeshWireframe = hideMeshWireframe;
hideMeshWireframe = !GUILayout.Toggle(!hideMeshWireframe, "Show Wireframe (ctrl-W)");
if (hideMeshWireframe != oldHideMeshWireframe)
{
for (int i = 0; i < jobs.Length; ++i)
{
EditorUtility.SetSelectedWireframeHidden(jobs[i].renderer, hideMeshWireframe);
}
}
multMouse2X = GUILayout.Toggle(multMouse2X, "2X mouse position");
bool hasColors = false;
bool hasUV0 = false;
bool hasUV1 = false;
bool hasUV2 = false;
bool hasUV3 = false;
bool hasPositions = false;
bool hasNormals = false;
bool hasStream = false;
for (int i = 0; i < jobs.Length; ++i)
{
var stream = jobs[i]._stream;
if (stream != null)
{
int vertexCount = jobs[i].verts.Length;
hasStream = true;
hasColors = (stream.colors != null && stream.colors.Length == vertexCount);
hasUV0 = (stream.uv0 != null && stream.uv0.Count == vertexCount);
hasUV1 = (stream.uv1 != null && stream.uv1.Count == vertexCount);
hasUV2 = (stream.uv2 != null && stream.uv2.Count == vertexCount);
hasUV3 = (stream.uv3 != null && stream.uv3.Count == vertexCount);
hasPositions = (stream.positions != null && stream.positions.Length == vertexCount);
hasNormals = (stream.normals != null && stream.normals.Length == vertexCount);
}
}
if (hasStream && (hasColors || hasUV0 || hasUV1 || hasUV2 || hasUV3 || hasPositions || hasNormals))
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Clear Channel:");
if (hasColors && DrawClearButton("Colors"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
var stream = jobs[i].stream;
stream.colors = null;
stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (hasUV0 && DrawClearButton("UV0"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
var stream = jobs[i].stream;
stream.uv0 = null;
stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (hasUV1 && DrawClearButton("UV1"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
var stream = jobs[i].stream;
stream.uv1 = null;
stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (hasUV2 && DrawClearButton("UV2"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
var stream = jobs[i].stream;
stream.uv2 = null;
stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (hasUV3 && DrawClearButton("UV3"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
var stream = jobs[i].stream;
stream.uv3 = null;
stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (hasPositions && DrawClearButton("Pos"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
jobs[i].stream.positions = null;
Mesh m = jobs[i].stream.GetModifierMesh();
if (m != null)
m.vertices = jobs[i].meshFilter.sharedMesh.vertices;
jobs[i].stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (hasNormals && DrawClearButton("Norm"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Clear");
jobs[i].stream.normals = null;
jobs[i].stream.tangents = null;
jobs[i].stream.Apply();
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
EditorGUILayout.EndHorizontal();
}
else if (hasStream)
{
if (GUILayout.Button("Remove Unused Stream Components"))
{
RevertMat();
for (int i = 0; i < jobs.Length; ++i)
{
if (jobs[i].HasStream())
{
DestroyImmediate(jobs[i].stream);
}
}
UpdateDisplayMode();
}
}
}
EditorGUILayout.Separator();
GUILayout.Box("", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(1)});
EditorGUILayout.Separator();
}
void DrawBrushSettingsGUI()
{
brushSize = EditorGUILayout.Slider("Brush Size", brushSize, 0.01f, 30.0f);
brushFlow = EditorGUILayout.Slider("Brush Flow", brushFlow, 0.1f, 128.0f);
brushFalloff = EditorGUILayout.Slider("Brush Falloff", brushFalloff, 0.1f, 4.0f);
if (tab == Tab.Paint && flowTarget != FlowTarget.ColorBA && flowTarget != FlowTarget.ColorRG)
{
flowRemap01 = EditorGUILayout.Toggle("use 0->1 mapping", flowRemap01);
}
EditorGUILayout.Separator();
GUILayout.Box("", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(1)});
EditorGUILayout.Separator();
}
void DrawCustomGUI()
{
if (DrawRollup("Brush Settings"))
{
customBrush = EditorGUILayout.ObjectField("Brush", customBrush, typeof(VertexPainterCustomBrush), false) as VertexPainterCustomBrush;
DrawBrushSettingsGUI();
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Fill"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Fill");
FillMesh(jobs[i]);
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
EditorGUILayout.EndHorizontal();
if (customBrush != null)
{
customBrush.DrawGUI();
}
}
void DrawPaintGUI()
{
GUILayout.Box("Brush Settings", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)});
var oldBM = brushMode;
brushMode = (BrushTarget)EditorGUILayout.EnumPopup("Target Channel", brushMode);
if (oldBM != brushMode)
{
UpdateDisplayMode();
}
if (brushMode == BrushTarget.Color || brushMode == BrushTarget.UV0_AsColor || brushMode == BrushTarget.UV1_AsColor
|| brushMode == BrushTarget.UV2_AsColor || brushMode == BrushTarget.UV3_AsColor)
{
brushColorMode = (BrushColorMode)EditorGUILayout.EnumPopup("Blend Mode", (System.Enum)brushColorMode);
if (brushColorMode == BrushColorMode.Overlay || brushColorMode == BrushColorMode.Normal)
{
brushColor = EditorGUILayout.ColorField("Brush Color", brushColor);
if (GUILayout.Button("Reset Palette", EditorStyles.miniButton, GUILayout.Width(80), GUILayout.Height(16)))
{
if (swatches != null)
{
DestroyImmediate(swatches);
}
swatches = ColorSwatches.CreateInstance<ColorSwatches>();
EditorPrefs.SetString(sSwatchKey, JsonUtility.ToJson(swatches, false));
}
GUILayout.BeginHorizontal();
for (int i = 0; i < swatches.colors.Length; ++i)
{
if (GUILayout.Button("", EditorStyles.textField, GUILayout.Width(16), GUILayout.Height(16)))
{
brushColor = swatches.colors[i];
}
EditorGUI.DrawRect(new Rect(GUILayoutUtility.GetLastRect().x + 1, GUILayoutUtility.GetLastRect().y + 1, 14, 14), swatches.colors[i]);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
for (int i = 0; i < swatches.colors.Length; i++)
{
if (GUILayout.Button("+", EditorStyles.miniButton, GUILayout.Width(16), GUILayout.Height(12)))
{
swatches.colors[i] = brushColor;
EditorPrefs.SetString(sSwatchKey, JsonUtility.ToJson(swatches, false));
}
}
GUILayout.EndHorizontal();
}
}
else if (brushMode == BrushTarget.ValueR || brushMode == BrushTarget.ValueG || brushMode == BrushTarget.ValueB || brushMode == BrushTarget.ValueA)
{
brushValue = (int)EditorGUILayout.Slider("Brush Value", (float)brushValue, 0.0f, 256.0f);
}
else
{
floatBrushValue = EditorGUILayout.FloatField("Brush Value", floatBrushValue);
var oldUVRange = uvVisualizationRange;
uvVisualizationRange = EditorGUILayout.Vector2Field("Visualize Range", uvVisualizationRange);
if (oldUVRange != uvVisualizationRange)
{
UpdateDisplayMode();
}
}
DrawBrushSettingsGUI();
//GUILayout.Box("", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(1)});
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Fill"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Fill");
FillMesh(jobs[i]);
}
Undo.CollapseUndoOperations(Undo.GetCurrentGroup());
}
if (GUILayout.Button("Random"))
{
for (int i = 0; i < jobs.Length; ++i)
{
Undo.RecordObject(jobs[i].stream, "Vertex Painter Fill");
RandomMesh(jobs[i]);
}
}
EditorGUILayout.EndHorizontal();
}
void DrawDeformGUI()
{
GUILayout.Box("Brush Settings", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)});
pull = (Event.current.shift);
vertexMode = (VertexMode)EditorGUILayout.EnumPopup("Vertex Mode", vertexMode);
vertexContraint = (VertexContraint)EditorGUILayout.EnumPopup("Vertex Constraint", vertexContraint);
DrawBrushSettingsGUI();
EditorGUILayout.LabelField(pull ? "Pull (shift)" : "Push (shift)");
}
void DrawFlowGUI()
{
GUILayout.Box("Brush Settings", new GUILayoutOption[]{GUILayout.ExpandWidth(true), GUILayout.Height(20)});
var oldV = flowVisualization;
flowVisualization = (FlowVisualization)EditorGUILayout.EnumPopup("Visualize", flowVisualization);
if (flowVisualization != oldV)
{
UpdateDisplayMode();
}
var ft = flowTarget;
flowTarget = (FlowTarget)EditorGUILayout.EnumPopup("Target", flowTarget);
if (flowTarget != ft)
{
UpdateDisplayMode();
}
flowBrushType = (FlowBrushType)EditorGUILayout.EnumPopup("Mode", flowBrushType);
DrawBrushSettingsGUI();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.Space();
if (GUILayout.Button("Reset"))
{
Vector2 norm = new Vector2(0.5f, 0.5f);
foreach (PaintJob job in jobs)
{
PrepBrushMode(job);
switch (flowTarget)
{
case FlowTarget.ColorRG:
job.stream.SetColorRG(norm, job.verts.Length); break;
case FlowTarget.ColorBA:
job.stream.SetColorBA(norm, job.verts.Length); break;
case FlowTarget.UV0_XY:
job.stream.SetUV0_XY(norm, job.verts.Length); break;
case FlowTarget.UV0_ZW:
job.stream.SetUV0_ZW(norm, job.verts.Length); break;
case FlowTarget.UV1_XY:
job.stream.SetUV1_XY(norm, job.verts.Length); break;
case FlowTarget.UV1_ZW:
job.stream.SetUV1_ZW(norm, job.verts.Length); break;
case FlowTarget.UV2_XY:
job.stream.SetUV2_XY(norm, job.verts.Length); break;
case FlowTarget.UV2_ZW:
job.stream.SetUV2_ZW(norm, job.verts.Length); break;
case FlowTarget.UV3_XY:
job.stream.SetUV3_XY(norm, job.verts.Length); break;
case FlowTarget.UV3_ZW:
job.stream.SetUV3_ZW(norm, job.verts.Length); break;
}
}
}
EditorGUILayout.Space();
EditorGUILayout.EndHorizontal();
}
List<IVertexPainterUtility> utilities = new List<IVertexPainterUtility>();
void InitPluginUtilities()
{
if (utilities == null || utilities.Count == 0)
{
var interfaceType = typeof(IVertexPainterUtility);
var all = System.AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => interfaceType.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
.Select(x => System.Activator.CreateInstance(x));
foreach (var o in all)
{
IVertexPainterUtility u = o as IVertexPainterUtility;
if (u != null)
{
utilities.Add(u);
}
}
utilities = utilities.OrderBy(o=>o.GetName()).ToList();
}
}
void DrawUtilityGUI()
{
InitPluginUtilities();
for (int i = 0; i < utilities.Count; ++i)
{
var u = utilities[i];
if (DrawRollup(u.GetName(), false))
{
u.OnGUI(jobs);
}
}
}
void OnFocus()
{
if (painting)
{
EndStroke();
}
SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
SceneView.onSceneGUIDelegate += this.OnSceneGUI;
Undo.undoRedoPerformed -= this.OnUndo;
Undo.undoRedoPerformed += this.OnUndo;
this.titleContent = new GUIContent("Vertex Paint");
Repaint();
}
void OnInspectorUpdate()
{
// unfortunate...
Repaint ();
}
void OnSelectionChange()
{
InitMeshes();
this.Repaint();
}
void OnDestroy()
{
bool show = showVertexShader;
showVertexShader = false;
UpdateDisplayMode();
showVertexShader = show;
DestroyImmediate(VertexInstanceStream.vertexShaderMat);
SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Data.Common;
using System.Data.SqlTypes;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public static class ParametersTest
{
private static string s_connString = DataTestUtility.TcpConnStr;
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void CodeCoverageSqlClient()
{
SqlParameterCollection opc = new SqlCommand().Parameters;
Assert.True(opc.Count == 0, string.Format("FAILED: Expected count: {0}. Actual count: {1}.", 0, opc.Count));
Assert.False(((IList)opc).IsReadOnly, "FAILED: Expected collection to NOT be read only.");
Assert.False(((IList)opc).IsFixedSize, "FAILED: Expected collection to NOT be fixed size.");
Assert.False(((IList)opc).IsSynchronized, "FAILED: Expected collection to NOT be synchronized.");
DataTestUtility.AssertEqualsWithDescription("List`1", ((IList)opc).SyncRoot.GetType().Name, "FAILED: Incorrect SyncRoot Name");
{
string failValue;
DataTestUtility.AssertThrowsWrapper<IndexOutOfRangeException>(() => failValue = opc[0].ParameterName, "Invalid index 0 for this SqlParameterCollection with Count=0.");
DataTestUtility.AssertThrowsWrapper<IndexOutOfRangeException>(() => failValue = opc["@p1"].ParameterName, "An SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection.");
}
DataTestUtility.AssertThrowsWrapper<ArgumentNullException>(() => opc.Add(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects.");
opc.Add((object)new SqlParameter());
IEnumerator enm = opc.GetEnumerator();
Assert.True(enm.MoveNext(), "FAILED: Expected MoveNext to be true");
DataTestUtility.AssertEqualsWithDescription("Parameter1", ((SqlParameter)enm.Current).ParameterName, "FAILED: Incorrect ParameterName");
opc.Add(new SqlParameter());
DataTestUtility.AssertEqualsWithDescription("Parameter2", opc[1].ParameterName, "FAILED: Incorrect ParameterName");
opc.Add(new SqlParameter(null, null));
opc.Add(null, SqlDbType.Int, 0, null);
DataTestUtility.AssertEqualsWithDescription("Parameter4", opc["Parameter4"].ParameterName, "FAILED: Incorrect ParameterName");
opc.Add(new SqlParameter("Parameter5", SqlDbType.NVarChar, 20));
opc.Add(new SqlParameter(null, SqlDbType.NVarChar, 20, "a"));
opc.RemoveAt(opc[3].ParameterName);
DataTestUtility.AssertEqualsWithDescription(-1, opc.IndexOf(null), "FAILED: Incorrect index for null value");
SqlParameter p = opc[0];
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => opc.Add((object)p), "The SqlParameter is already contained by another SqlParameterCollection.");
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => new SqlCommand().Parameters.Add(p), "The SqlParameter is already contained by another SqlParameterCollection.");
DataTestUtility.AssertThrowsWrapper<ArgumentNullException>(() => opc.Remove(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects.");
string pname = p.ParameterName;
p.ParameterName = pname;
p.ParameterName = pname.ToUpper();
p.ParameterName = pname.ToLower();
p.ParameterName = "@p1";
p.ParameterName = pname;
opc.Clear();
opc.Add(p);
opc.Clear();
opc.AddWithValue("@p1", null);
DataTestUtility.AssertEqualsWithDescription(-1, opc.IndexOf(p.ParameterName), "FAILED: Incorrect index for parameter name");
opc[0] = p;
DataTestUtility.AssertEqualsWithDescription(0, opc.IndexOf(p.ParameterName), "FAILED: Incorrect index for parameter name");
Assert.True(opc.Contains(p.ParameterName), "FAILED: Expected collection to contain provided parameter.");
Assert.True(opc.Contains(opc[0]), "FAILED: Expected collection to contain provided parameter.");
opc[0] = p;
opc[p.ParameterName] = new SqlParameter(p.ParameterName, null);
opc[p.ParameterName] = new SqlParameter();
opc.RemoveAt(0);
new SqlCommand().Parameters.Clear();
new SqlCommand().Parameters.CopyTo(new object[0], 0);
Assert.False(new SqlCommand().Parameters.GetEnumerator().MoveNext(), "FAILED: Expected MoveNext to be false");
DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => new SqlCommand().Parameters.Add(0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");
DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => new SqlCommand().Parameters.Insert(0, 0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");
DataTestUtility.AssertThrowsWrapper<InvalidCastException>(() => new SqlCommand().Parameters.Remove(0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");
DataTestUtility.AssertThrowsWrapper<ArgumentException>(() => new SqlCommand().Parameters.Remove(new SqlParameter()), "Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection.");
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void Test_SqlParameter_Constructor()
{
using (var conn = new SqlConnection(s_connString))
{
var dataTable = new DataTable();
var adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT CustomerID, ContactTitle FROM dbo.Customers WHERE ContactTitle = @ContactTitle", conn);
var selectParam = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30, ParameterDirection.Input, true, 0, 0, "ContactTitle", DataRowVersion.Current, "Owner");
adapter.SelectCommand.Parameters.Add(selectParam);
adapter.UpdateCommand = new SqlCommand("UPDATE dbo.Customers SET ContactTitle = @ContactTitle WHERE CustomerID = @CustomerID", conn);
var titleParam = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30, ParameterDirection.Input, true, 0, 0, "ContactTitle", DataRowVersion.Current, null);
var idParam = new SqlParameter("@CustomerID", SqlDbType.NChar, 5, ParameterDirection.Input, false, 0, 0, "CustomerID", DataRowVersion.Current, null);
adapter.UpdateCommand.Parameters.Add(titleParam);
adapter.UpdateCommand.Parameters.Add(idParam);
adapter.Fill(dataTable);
object titleData = dataTable.Rows[0]["ContactTitle"];
Assert.Equal("Owner", (string)titleData);
titleData = "Test Data";
adapter.Update(dataTable);
adapter.Fill(dataTable);
Assert.Equal("Test Data", (string)titleData);
titleData = "Owner";
adapter.Update(dataTable);
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void Test_WithEnumValue_ShouldInferToUnderlyingType()
{
using (var conn = new SqlConnection(s_connString))
{
conn.Open();
var cmd = new SqlCommand("select @input", conn);
cmd.Parameters.AddWithValue("@input", MyEnum.B);
object value = cmd.ExecuteScalar();
Assert.Equal((MyEnum)value, MyEnum.B);
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void Test_WithOutputEnumParameter_ShouldReturnEnum()
{
using (var conn = new SqlConnection(s_connString))
{
conn.Open();
var cmd = new SqlCommand("set @output = @input", conn);
cmd.Parameters.AddWithValue("@input", MyEnum.B);
var outputParam = cmd.CreateParameter();
outputParam.ParameterName = "@output";
outputParam.DbType = DbType.Int32;
outputParam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outputParam);
cmd.ExecuteNonQuery();
Assert.Equal((MyEnum)outputParam.Value, MyEnum.B);
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void Test_WithDecimalValue_ShouldReturnDecimal()
{
using (var conn = new SqlConnection(s_connString))
{
conn.Open();
var cmd = new SqlCommand("select @foo", conn);
cmd.Parameters.AddWithValue("@foo", new SqlDecimal(0.5));
var result = (decimal)cmd.ExecuteScalar();
Assert.Equal(result, (decimal)0.5);
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void Test_WithGuidValue_ShouldReturnGuid()
{
using (var conn = new SqlConnection(s_connString))
{
conn.Open();
var expectedGuid = Guid.NewGuid();
var cmd = new SqlCommand("select @input", conn);
cmd.Parameters.AddWithValue("@input", expectedGuid);
var result = cmd.ExecuteScalar();
Assert.Equal(expectedGuid, (Guid)result);
}
}
[ConditionalFact(typeof(DataTestUtility),nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestParametersWithDatatablesTVPInsert()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
builder.InitialCatalog = "tempdb";
int x = 4, y = 5;
DataTable table = new DataTable { Columns = { { "x", typeof(int) }, { "y", typeof(int) } }, Rows = { { x, y } } };
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
ExecuteSqlIgnoreExceptions(connection, "drop proc dbo.UpdatePoint");
ExecuteSqlIgnoreExceptions(connection, "drop table dbo.PointTable");
ExecuteSqlIgnoreExceptions(connection, "drop type dbo.PointTableType");
ExecuteSqlIgnoreExceptions(connection, "CREATE TYPE dbo.PointTableType AS TABLE (x INT, y INT)");
ExecuteSqlIgnoreExceptions(connection, "CREATE TABLE dbo.PointTable (x INT, y INT)");
ExecuteSqlIgnoreExceptions(connection, "CREATE PROCEDURE dbo.UpdatePoint @TVP dbo.PointTableType READONLY AS SET NOCOUNT ON INSERT INTO dbo.PointTable(x, y) SELECT * FROM @TVP");
using (SqlCommand cmd = connection.CreateCommand())
{
// Update Data Using TVPs
cmd.CommandText = "dbo.UpdatePoint";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = cmd.Parameters.AddWithValue("@TVP", table);
parameter.TypeName = "dbo.PointTableType";
cmd.ExecuteNonQuery();
// Verify if the data was updated
cmd.CommandText = "select * from dbo.PointTable";
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTable dbData = new DataTable();
dbData.Load(reader);
Assert.Equal(1, dbData.Rows.Count);
Assert.Equal(x, dbData.Rows[0][0]);
Assert.Equal(y, dbData.Rows[0][1]);
}
}
}
}
private static void ExecuteSqlIgnoreExceptions(DbConnection connection, string query)
{
using (DbCommand cmd = connection.CreateCommand())
{
try
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
catch { /* Ignore exception if the command execution fails*/ }
}
}
private enum MyEnum
{
A = 1,
B = 2
}
}
}
| |
// <copyright file="ArrayExtensions.SequenceEquals.StandardTypes.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Diagnostics.CodeAnalysis;
namespace IX.StandardExtensions.Extensions;
/// <summary>
/// Extensions for array types.
/// </summary>
public static partial class ArrayExtensions
{
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this byte[]? left,
byte[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this sbyte[]? left,
sbyte[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this short[]? left,
short[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this ushort[]? left,
ushort[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this char[]? left,
char[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this int[]? left,
int[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this uint[]? left,
uint[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this long[]? left,
long[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this ulong[]? left,
ulong[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
[SuppressMessage(
"ReSharper",
"CompareOfFloatsByEqualityOperator",
Justification = "This is raw comparison and equation, we're not interested in the results of possible tolerance.")]
public static bool SequenceEquals(
this float[]? left,
float[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <param name="tolerance">The tolerance under which to consider values equal.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is within tolerance to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this float[]? left,
float[]? right,
float tolerance)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
tolerance = Math.Abs(tolerance);
for (var i = 0; i < left.Length; i++)
{
if (Math.Abs(left[i] - right[i]) > tolerance)
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
[SuppressMessage(
"ReSharper",
"CompareOfFloatsByEqualityOperator",
Justification = "This is raw comparison and equation, we're not interested in the results of possible tolerance.")]
public static bool SequenceEquals(
this double[]? left,
double[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <param name="tolerance">The tolerance under which to consider values equal.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is within tolerance to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this double[]? left,
double[]? right,
double tolerance)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
tolerance = Math.Abs(tolerance);
for (var i = 0; i < left.Length; i++)
{
if (Math.Abs(left[i] - right[i]) > tolerance)
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this decimal[]? left,
decimal[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this DateTime[]? left,
DateTime[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this bool[]? left,
bool[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this TimeSpan[]? left,
TimeSpan[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two arrays have all members in sequence equal to one another.
/// </summary>
/// <param name="left">The left operand array.</param>
/// <param name="right">The right operand array.</param>
/// <returns>
/// <see langword="true"/> if the two arrays have the same length and each element at each position
/// in one array is equal to the equivalent in the other, <see langword="false"/> otherwise.
/// </returns>
[SuppressMessage(
"CodeQuality",
"IDE0079:Remove unnecessary suppression",
Justification = "Some developers use ReSharper.")]
[SuppressMessage(
"ReSharper",
"LoopCanBeConvertedToQuery",
Justification = "We don't want this. Instead, we want maximum performance out of the array.")]
public static bool SequenceEquals(
this string[]? left,
string[]? right)
{
if (left == null)
{
return right == null;
}
if (right == null)
{
return false;
}
if (left.Length != right.Length)
{
return false;
}
for (var i = 0; i < left.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Rename;
namespace Microsoft.DotNet.CodeFormatting.Rules
{
[GlobalSemanticRule(PrivateFieldNamingRule.Name, PrivateFieldNamingRule.Description, GlobalSemanticRuleOrder.PrivateFieldNamingRule)]
internal partial class PrivateFieldNamingRule : IGlobalSemanticFormattingRule
{
internal const string Name = "FieldNames";
internal const string Description = "Prefix private fields with _ and statics with s_";
#region CommonRule
private abstract class CommonRule
{
protected abstract SyntaxNode AddPrivateFieldAnnotations(SyntaxNode syntaxNode, out int count);
/// <summary>
/// This method exists to work around DevDiv 1086632 in Roslyn. The Rename action is
/// leaving a set of annotations in the tree. These annotations slow down further processing
/// and eventually make the rename operation unusable. As a temporary work around we manually
/// remove these from the tree.
/// </summary>
protected abstract SyntaxNode RemoveRenameAnnotations(SyntaxNode syntaxNode);
public async Task<Solution> ProcessAsync(Document document, SyntaxNode syntaxRoot, CancellationToken cancellationToken)
{
int count;
var newSyntaxRoot = AddPrivateFieldAnnotations(syntaxRoot, out count);
if (count == 0)
{
return document.Project.Solution;
}
var documentId = document.Id;
var solution = document.Project.Solution;
solution = solution.WithDocumentSyntaxRoot(documentId, newSyntaxRoot);
solution = await RenameFields(solution, documentId, count, cancellationToken);
return solution;
}
private async Task<Solution> RenameFields(Solution solution, DocumentId documentId, int count, CancellationToken cancellationToken)
{
Solution oldSolution = null;
for (int i = 0; i < count; i++)
{
oldSolution = solution;
var semanticModel = await solution.GetDocument(documentId).GetSemanticModelAsync(cancellationToken);
var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken);
var declaration = root.GetAnnotatedNodes(s_markerAnnotation).ElementAt(i);
// Make note, VB represents "fields" marked as "WithEvents" as properties, so don't be
// tempted to treat this as a IFieldSymbol. We only need the name, so ISymbol is enough.
var fieldSymbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken);
var newName = GetNewFieldName(fieldSymbol);
// Can happen with pathologically bad field names like _
if (newName == fieldSymbol.Name)
{
continue;
}
solution = await Renamer.RenameSymbolAsync(solution, fieldSymbol, newName, solution.Workspace.Options, cancellationToken).ConfigureAwait(false);
solution = await CleanSolutionAsync(solution, oldSolution, cancellationToken);
}
return solution;
}
private static string GetNewFieldName(ISymbol fieldSymbol)
{
var name = fieldSymbol.Name.Trim('_');
if (name.Length > 2 && char.IsLetter(name[0]) && name[1] == '_')
{
name = name.Substring(2);
}
// Some .NET code uses "ts_" prefix for thread static
if (name.Length > 3 && name.StartsWith("ts_", StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(3);
}
if (name.Length == 0)
{
return fieldSymbol.Name;
}
if (name.Length > 2 && char.IsUpper(name[0]) && char.IsLower(name[1]))
{
name = char.ToLower(name[0]) + name.Substring(1);
}
if (fieldSymbol.IsStatic)
{
// Check for ThreadStatic private fields.
if (fieldSymbol.GetAttributes().Any(a => a.AttributeClass.Name.Equals("ThreadStaticAttribute", StringComparison.Ordinal)))
{
return "t_" + name;
}
else
{
return "s_" + name;
}
}
return "_" + name;
}
private async Task<Solution> CleanSolutionAsync(Solution newSolution, Solution oldSolution, CancellationToken cancellationToken)
{
var solution = newSolution;
foreach (var projectChange in newSolution.GetChanges(oldSolution).GetProjectChanges())
{
foreach (var documentId in projectChange.GetChangedDocuments())
{
solution = await CleanSolutionDocument(solution, documentId, cancellationToken);
}
}
return solution;
}
private async Task<Solution> CleanSolutionDocument(Solution solution, DocumentId documentId, CancellationToken cancellationToken)
{
var document = solution.GetDocument(documentId);
var syntaxNode = await document.GetSyntaxRootAsync(cancellationToken);
if (syntaxNode == null)
{
return solution;
}
var newNode = RemoveRenameAnnotations(syntaxNode);
return solution.WithDocumentSyntaxRoot(documentId, newNode);
}
}
#endregion
private const string s_renameAnnotationName = "Rename";
private readonly static SyntaxAnnotation s_markerAnnotation = new SyntaxAnnotation("PrivateFieldToRename");
// Used to avoid the array allocation on calls to WithAdditionalAnnotations
private readonly static SyntaxAnnotation[] s_markerAnnotationArray;
static PrivateFieldNamingRule()
{
s_markerAnnotationArray = new[] { s_markerAnnotation };
}
private readonly CSharpRule _csharpRule = new CSharpRule();
private readonly VisualBasicRule _visualBasicRule = new VisualBasicRule();
public bool SupportsLanguage(string languageName)
{
return
languageName == LanguageNames.CSharp ||
languageName == LanguageNames.VisualBasic;
}
public Task<Solution> ProcessAsync(Document document, SyntaxNode syntaxRoot, CancellationToken cancellationToken)
{
switch (document.Project.Language)
{
case LanguageNames.CSharp:
return _csharpRule.ProcessAsync(document, syntaxRoot, cancellationToken);
case LanguageNames.VisualBasic:
return _visualBasicRule.ProcessAsync(document, syntaxRoot, cancellationToken);
default:
throw new NotSupportedException();
}
}
private static bool IsGoodPrivateFieldName(string name, bool isInstance)
{
if (isInstance)
{
return name.Length > 0 && name[0] == '_';
}
else
{
return name.Length > 1 && (name[0] == 's' || name[0] == 't') && name[1] == '_';
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Events
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Handle;
/// <summary>
/// Ignite events.
/// </summary>
internal sealed class Events : PlatformTargetAdapter, IEvents
{
/// <summary>
/// Opcodes.
/// </summary>
private enum Op
{
RemoteQuery = 1,
RemoteListen = 2,
StopRemoteListen = 3,
WaitForLocal = 4,
LocalQuery = 5,
// ReSharper disable once UnusedMember.Local
RecordLocal = 6,
EnableLocal = 8,
DisableLocal = 9,
GetEnabledEvents = 10,
IsEnabled = 12,
LocalListen = 13,
StopLocalListen = 14,
RemoteQueryAsync = 15,
WaitForLocalAsync = 16
}
/** Map from user func to local wrapper, needed for invoke/unsubscribe. */
private readonly Dictionary<object, Dictionary<int, LocalHandledEventFilter>> _localFilters
= new Dictionary<object, Dictionary<int, LocalHandledEventFilter>>();
/** Cluster group. */
private readonly IClusterGroup _clusterGroup;
/// <summary>
/// Initializes a new instance of the <see cref="Events" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="clusterGroup">Cluster group.</param>
public Events(IPlatformTargetInternal target, IClusterGroup clusterGroup)
: base(target)
{
Debug.Assert(clusterGroup != null);
_clusterGroup = clusterGroup;
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _clusterGroup; }
}
/** */
private Ignite Ignite
{
get { return (Ignite) ClusterGroup.Ignite; }
}
/** <inheritDoc /> */
public ICollection<T> RemoteQuery<T>(IEventFilter<T> filter, TimeSpan? timeout = null, params int[] types)
where T : IEvent
{
IgniteArgumentCheck.NotNull(filter, "filter");
return DoOutInOp((int) Op.RemoteQuery,
writer => WriteRemoteQuery(filter, timeout, types, writer),
reader => ReadEvents<T>(reader));
}
/** <inheritDoc /> */
public Task<ICollection<T>> RemoteQueryAsync<T>(IEventFilter<T> filter, TimeSpan? timeout = null,
params int[] types) where T : IEvent
{
IgniteArgumentCheck.NotNull(filter, "filter");
// ReSharper disable once RedundantTypeArgumentsOfMethod (won't compile in VS2010)
return DoOutOpAsync<ICollection<T>>((int) Op.RemoteQueryAsync,
w => WriteRemoteQuery(filter, timeout, types, w), convertFunc: ReadEvents<T>);
}
/** <inheritDoc /> */
public ICollection<T> RemoteQuery<T>(IEventFilter<T> filter, TimeSpan? timeout = null,
IEnumerable<int> types = null) where T : IEvent
{
return RemoteQuery(filter, timeout, TypesToArray(types));
}
/** <inheritDoc /> */
public Task<ICollection<T>> RemoteQueryAsync<T>(IEventFilter<T> filter, TimeSpan? timeout = null,
IEnumerable<int> types = null) where T : IEvent
{
return RemoteQueryAsync(filter, timeout, TypesToArray(types));
}
/** <inheritDoc /> */
[ExcludeFromCodeCoverage]
public Guid? RemoteListen<T>(int bufSize = 1, TimeSpan? interval = null, bool autoUnsubscribe = true,
IEventFilter<T> localListener = null, IEventFilter<T> remoteFilter = null, params int[] types)
where T : IEvent
{
IgniteArgumentCheck.Ensure(bufSize > 0, "bufSize", "should be > 0");
IgniteArgumentCheck.Ensure(interval == null || interval.Value.TotalMilliseconds > 0, "interval", "should be null or >= 0");
return DoOutInOp((int) Op.RemoteListen,
writer =>
{
writer.WriteInt(bufSize);
writer.WriteLong((long) (interval == null ? 0 : interval.Value.TotalMilliseconds));
writer.WriteBoolean(autoUnsubscribe);
writer.WriteBoolean(localListener != null);
if (localListener != null)
{
var listener = new RemoteListenEventFilter(Ignite, e => localListener.Invoke((T) e));
writer.WriteLong(Ignite.HandleRegistry.Allocate(listener));
}
writer.WriteBoolean(remoteFilter != null);
if (remoteFilter != null)
writer.Write(remoteFilter);
WriteEventTypes(types, writer);
},
reader => Marshaller.StartUnmarshal(reader).ReadGuid());
}
/** <inheritDoc /> */
[ExcludeFromCodeCoverage]
public Guid? RemoteListen<T>(int bufSize = 1, TimeSpan? interval = null, bool autoUnsubscribe = true,
IEventFilter<T> localListener = null, IEventFilter<T> remoteFilter = null, IEnumerable<int> types = null)
where T : IEvent
{
return RemoteListen(bufSize, interval, autoUnsubscribe, localListener, remoteFilter, TypesToArray(types));
}
/** <inheritDoc /> */
[ExcludeFromCodeCoverage]
public void StopRemoteListen(Guid opId)
{
DoOutOp((int) Op.StopRemoteListen, writer =>
{
Marshaller.StartMarshal(writer).WriteGuid(opId);
});
}
/** <inheritDoc /> */
public IEvent WaitForLocal(params int[] types)
{
return WaitForLocal<IEvent>(null, types);
}
/** <inheritDoc /> */
public Task<IEvent> WaitForLocalAsync(params int[] types)
{
return WaitForLocalAsync<IEvent>(null, types);
}
/** <inheritDoc /> */
public IEvent WaitForLocal(IEnumerable<int> types)
{
return WaitForLocal(TypesToArray(types));
}
/** <inheritDoc /> */
public Task<IEvent> WaitForLocalAsync(IEnumerable<int> types)
{
return WaitForLocalAsync<IEvent>(null, TypesToArray(types));
}
/** <inheritDoc /> */
public T WaitForLocal<T>(IEventFilter<T> filter, params int[] types) where T : IEvent
{
var hnd = GetFilterHandle(filter);
try
{
return DoOutInOp((int) Op.WaitForLocal,
writer =>
{
writer.WriteObject(hnd);
WriteEventTypes(types, writer);
},
reader => EventReader.Read<T>(Marshaller.StartUnmarshal(reader)));
}
finally
{
if (hnd != null)
Ignite.HandleRegistry.Release(hnd.Value);
}
}
/** <inheritDoc /> */
public Task<T> WaitForLocalAsync<T>(IEventFilter<T> filter, params int[] types) where T : IEvent
{
var hnd = GetFilterHandle(filter);
try
{
var task = DoOutOpAsync((int) Op.WaitForLocalAsync, writer =>
{
writer.WriteObject(hnd);
WriteEventTypes(types, writer);
}, convertFunc: EventReader.Read<T>);
if (hnd != null)
{
// Dispose handle as soon as future ends.
task.ContWith(x => Ignite.HandleRegistry.Release(hnd.Value));
}
return task;
}
catch (Exception)
{
if (hnd != null)
Ignite.HandleRegistry.Release(hnd.Value);
throw;
}
}
/** <inheritDoc /> */
public T WaitForLocal<T>(IEventFilter<T> filter, IEnumerable<int> types) where T : IEvent
{
return WaitForLocal(filter, TypesToArray(types));
}
/** <inheritDoc /> */
public Task<T> WaitForLocalAsync<T>(IEventFilter<T> filter, IEnumerable<int> types) where T : IEvent
{
return WaitForLocalAsync(filter, TypesToArray(types));
}
/** <inheritDoc /> */
public ICollection<IEvent> LocalQuery(params int[] types)
{
return DoOutInOp((int) Op.LocalQuery,
writer => WriteEventTypes(types, writer),
reader => ReadEvents<IEvent>(reader));
}
/** <inheritDoc /> */
public ICollection<IEvent> LocalQuery(IEnumerable<int> types)
{
return LocalQuery(TypesToArray(types));
}
/** <inheritDoc /> */
public void RecordLocal(IEvent evt)
{
throw new NotSupportedException("IGNITE-1410");
}
/** <inheritDoc /> */
public void LocalListen<T>(IEventListener<T> listener, params int[] types) where T : IEvent
{
IgniteArgumentCheck.NotNull(listener, "listener");
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
foreach (var type in types)
LocalListen(listener, type);
}
/** <inheritDoc /> */
public void LocalListen<T>(IEventListener<T> listener, IEnumerable<int> types) where T : IEvent
{
LocalListen(listener, TypesToArray(types));
}
/** <inheritDoc /> */
public bool StopLocalListen<T>(IEventListener<T> listener, params int[] types) where T : IEvent
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (_localFilters.TryGetValue(listener, out filters))
{
var success = false;
// Should do this inside lock to avoid race with subscription
// ToArray is required because we are going to modify underlying dictionary during enumeration
foreach (var filter in GetLocalFilters(listener, types).ToArray())
success |= (DoOutInOp((int) Op.StopLocalListen, filter.Handle) == True);
return success;
}
}
// Looks for a predefined filter (IgniteConfiguration.LocalEventListeners).
var ids = Ignite.Configuration.LocalEventListenerIds;
int predefinedListenerId;
if (ids != null && ids.TryGetValue(listener, out predefinedListenerId))
{
return DoOutInOp((int) Op.StopLocalListen, w =>
{
w.WriteInt(predefinedListenerId);
w.WriteIntArray(types);
}, s => s.ReadBool());
}
return false;
}
/** <inheritDoc /> */
public bool StopLocalListen<T>(IEventListener<T> listener, IEnumerable<int> types) where T : IEvent
{
return StopLocalListen(listener, TypesToArray(types));
}
/** <inheritDoc /> */
public void EnableLocal(IEnumerable<int> types)
{
EnableLocal(TypesToArray(types));
}
/** <inheritDoc /> */
public void EnableLocal(params int[] types)
{
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
DoOutOp((int)Op.EnableLocal, writer => WriteEventTypes(types, writer));
}
/** <inheritDoc /> */
public void DisableLocal(params int[] types)
{
IgniteArgumentCheck.NotNullOrEmpty(types, "types");
DoOutOp((int)Op.DisableLocal, writer => WriteEventTypes(types, writer));
}
/** <inheritDoc /> */
public void DisableLocal(IEnumerable<int> types)
{
DisableLocal(TypesToArray(types));
}
/** <inheritDoc /> */
public ICollection<int> GetEnabledEvents()
{
return DoInOp((int)Op.GetEnabledEvents, reader => ReadEventTypes(reader));
}
/** <inheritDoc /> */
public bool IsEnabled(int type)
{
return DoOutInOp((int) Op.IsEnabled, type) == True;
}
/// <summary>
/// Gets the filter handle.
/// </summary>
private long? GetFilterHandle<T>(IEventFilter<T> filter) where T : IEvent
{
return filter != null
? Ignite.HandleRegistry.Allocate(new LocalEventFilter<T>(Marshaller, filter))
: (long?) null;
}
/// <summary>
/// Reads events from a binary stream.
/// </summary>
/// <typeparam name="T">Event type.</typeparam>
/// <param name="reader">Reader.</param>
/// <returns>Resulting list or null.</returns>
private ICollection<T> ReadEvents<T>(IBinaryStream reader) where T : IEvent
{
return ReadEvents<T>(Marshaller.StartUnmarshal(reader));
}
/// <summary>
/// Reads events from a binary reader.
/// </summary>
/// <typeparam name="T">Event type.</typeparam>
/// <param name="binaryReader">Reader.</param>
/// <returns>Resulting list or null.</returns>
private static ICollection<T> ReadEvents<T>(BinaryReader binaryReader) where T : IEvent
{
var count = binaryReader.GetRawReader().ReadInt();
if (count == -1)
return null;
var result = new List<T>(count);
for (var i = 0; i < count; i++)
result.Add(EventReader.Read<T>(binaryReader));
return result;
}
/// <summary>
/// Gets local filters by user listener and event type.
/// </summary>
/// <param name="listener">Listener.</param>
/// <param name="types">Types.</param>
/// <returns>Collection of local listener wrappers.</returns>
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField",
Justification = "This private method should be always called within a lock on localFilters")]
private IEnumerable<LocalHandledEventFilter> GetLocalFilters(object listener, int[] types)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
return Enumerable.Empty<LocalHandledEventFilter>();
if (types.Length == 0)
return filters.Values;
return types.Select(type =>
{
LocalHandledEventFilter filter;
return filters.TryGetValue(type, out filter) ? filter : null;
}).Where(x => x != null);
}
/// <summary>
/// Adds an event listener for local events.
/// </summary>
/// <typeparam name="T">Type of events.</typeparam>
/// <param name="listener">Predicate that is called on each received event.</param>
/// <param name="type">Event type for which this listener will be notified</param>
private void LocalListen<T>(IEventListener<T> listener, int type) where T : IEvent
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (!_localFilters.TryGetValue(listener, out filters))
{
filters = new Dictionary<int, LocalHandledEventFilter>();
_localFilters[listener] = filters;
}
LocalHandledEventFilter localFilter;
if (!filters.TryGetValue(type, out localFilter))
{
localFilter = CreateLocalListener(listener, type);
filters[type] = localFilter;
}
DoOutOp((int) Op.LocalListen, (IBinaryStream s) =>
{
s.WriteLong(localFilter.Handle);
s.WriteInt(type);
});
}
}
/// <summary>
/// Creates a user filter wrapper.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="listener">Listener.</param>
/// <param name="type">Event type.</param>
/// <returns>Created wrapper.</returns>
private LocalHandledEventFilter CreateLocalListener<T>(IEventListener<T> listener, int type) where T : IEvent
{
var result = new LocalHandledEventFilter(
stream => InvokeLocalListener(stream, listener),
unused =>
{
lock (_localFilters)
{
Dictionary<int, LocalHandledEventFilter> filters;
if (_localFilters.TryGetValue(listener, out filters))
{
filters.Remove(type);
if (filters.Count == 0)
_localFilters.Remove(listener);
}
}
});
result.Handle = Ignite.HandleRegistry.Allocate(result);
return result;
}
/// <summary>
/// Invokes local filter using data from specified stream.
/// </summary>
/// <typeparam name="T">Event object type.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="listener">The listener.</param>
/// <returns>Filter invocation result.</returns>
private bool InvokeLocalListener<T>(IBinaryStream stream, IEventListener<T> listener) where T : IEvent
{
var evt = EventReader.Read<T>(Marshaller.StartUnmarshal(stream));
return listener.Invoke(evt);
}
/// <summary>
/// Writes the event types.
/// </summary>
/// <param name="types">Types.</param>
/// <param name="writer">Writer.</param>
private static void WriteEventTypes(int[] types, IBinaryRawWriter writer)
{
if (types != null && types.Length == 0)
types = null; // empty array means no type filtering
writer.WriteIntArray(types);
}
/// <summary>
/// Writes the event types.
/// </summary>
/// <param name="reader">Reader.</param>
private int[] ReadEventTypes(IBinaryStream reader)
{
return Marshaller.StartUnmarshal(reader).ReadIntArray();
}
/// <summary>
/// Converts types enumerable to array.
/// </summary>
private static int[] TypesToArray(IEnumerable<int> types)
{
if (types == null)
return null;
return types as int[] ?? types.ToArray();
}
/// <summary>
/// Writes the remote query.
/// </summary>
/// <param name="filter">The filter.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="types">The types.</param>
/// <param name="writer">The writer.</param>
private static void WriteRemoteQuery<T>(IEventFilter<T> filter, TimeSpan? timeout, int[] types,
IBinaryRawWriter writer)
where T : IEvent
{
writer.WriteObject(filter);
writer.WriteLong((long)(timeout == null ? 0 : timeout.Value.TotalMilliseconds));
WriteEventTypes(types, writer);
}
/// <summary>
/// Local user filter wrapper.
/// </summary>
private class LocalEventFilter<T> : IInteropCallback where T : IEvent
{
/** */
private readonly Marshaller _marshaller;
/** */
private readonly IEventFilter<T> _listener;
/// <summary>
/// Initializes a new instance of the <see cref="LocalEventFilter{T}"/> class.
/// </summary>
public LocalEventFilter(Marshaller marshaller, IEventFilter<T> listener)
{
_marshaller = marshaller;
_listener = listener;
}
/** <inheritdoc /> */
public int Invoke(IBinaryStream stream)
{
var evt = EventReader.Read<T>(_marshaller.StartUnmarshal(stream));
return _listener.Invoke(evt) ? 1 : 0;
}
}
/// <summary>
/// Local user filter wrapper with handle.
/// </summary>
private class LocalHandledEventFilter : Handle<Func<IBinaryStream, bool>>, IInteropCallback
{
/** */
public long Handle;
/** <inheritdoc /> */
public int Invoke(IBinaryStream stream)
{
return Target(stream) ? 1 : 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="LocalHandledEventFilter"/> class.
/// </summary>
/// <param name="invokeFunc">The invoke function.</param>
/// <param name="releaseAction">The release action.</param>
public LocalHandledEventFilter(
Func<IBinaryStream, bool> invokeFunc, Action<Func<IBinaryStream, bool>> releaseAction)
: base(invokeFunc, releaseAction)
{
// No-op.
}
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.LogConsistency;
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
using TestExtensions;
using Orleans.EventSourcing.Common;
using Tester;
using Orleans.Hosting;
namespace Tests.GeoClusterTests
{
/// <summary>
/// A fixture that provides a collection of semantic tests for log-consistency providers
/// (concurrent reading and updating, update propagation, conflict resolution)
/// on a multicluster with the desired number of clusters
/// </summary>
public class LogConsistencyTestFixture : IDisposable
{
TestingClusterHost _hostedMultiCluster;
public TestingClusterHost MultiCluster
{
get { return _hostedMultiCluster ?? (_hostedMultiCluster = new TestingClusterHost()); }
}
public void EnsurePreconditionsMet()
{
TestUtils.CheckForAzureStorage();
}
public class ClientWrapper : Tests.GeoClusterTests.TestingClusterHost.ClientWrapperBase
{
public static readonly Func<string, int, string, Action<IClientBuilder>, ClientWrapper> Factory =
(name, gwPort, clusterId, clientConfigurator) => new ClientWrapper(name, gwPort, clusterId, clientConfigurator);
public ClientWrapper(string name, int gatewayport, string clusterId, Action<IClientBuilder> clientConfigurator)
: base(name, gatewayport, clusterId, clientConfigurator)
{
systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
public string GetGrainRef(string grainclass, int i)
{
return this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass).ToString();
}
public void SetALocal(string grainclass, int i, int a)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.SetALocal(a).GetResult();
}
public void SetAGlobal(string grainclass, int i, int a)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.SetAGlobal(a).GetResult();
}
public Tuple<int, bool> SetAConditional(string grainclass, int i, int a)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.SetAConditional(a).GetResult();
}
public void IncrementAGlobal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.IncrementAGlobal().GetResult();
}
public void IncrementALocal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.IncrementALocal().GetResult();
}
public int GetAGlobal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetAGlobal().GetResult();
}
public int GetALocal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetALocal().GetResult();
}
public void AddReservationLocal(string grainclass, int i, int x)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.AddReservationLocal(x).GetResult();
}
public void RemoveReservationLocal(string grainclass, int i, int x)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.RemoveReservationLocal(x).GetResult();
}
public int[] GetReservationsGlobal(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetReservationsGlobal().GetResult();
}
public void Synchronize(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
grainRef.SynchronizeGlobalState().GetResult();
}
public void InjectClusterConfiguration(params string[] clusters)
{
systemManagement.InjectMultiClusterConfiguration(clusters).GetResult();
}
IManagementGrain systemManagement;
public long GetConfirmedVersion(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetConfirmedVersion().GetResult();
}
public IEnumerable<ConnectionIssue> GetUnresolvedConnectionIssues(string grainclass, int i)
{
var grainRef = this.GrainFactory.GetGrain<UnitTests.GrainInterfaces.ILogTestGrain>(i, grainclass);
return grainRef.GetUnresolvedConnectionIssues().GetResult();
}
}
public void StartClustersIfNeeded(int numclusters, ITestOutputHelper output)
{
this.output = output;
if (MultiCluster.Clusters.Count != numclusters)
{
if (MultiCluster.Clusters.Count > 0)
MultiCluster.StopAllClientsAndClusters();
output.WriteLine("Creating {0} clusters and clients...", numclusters);
this.numclusters = numclusters;
Assert.True(numclusters >= 2);
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
random = new Random();
System.Threading.ThreadPool.SetMaxThreads(8, 8);
// Create clusters and clients
Cluster = new string[numclusters];
Client = new ClientWrapper[numclusters];
for (int i = 0; i < numclusters; i++)
{
var clustername = Cluster[i] = ((char)('A' + i)).ToString();
MultiCluster.NewGeoCluster<LogConsistencyProviderSiloConfigurator>(globalserviceid, clustername, 1);
Client[i] = this.MultiCluster.NewClient(clustername, 0, ClientWrapper.Factory);
}
output.WriteLine("Clusters and clients are ready (elapsed = {0})", stopwatch.Elapsed);
// wait for configuration to stabilize
MultiCluster.WaitForLivenessToStabilizeAsync().WaitWithThrow(TimeSpan.FromMinutes(1));
Client[0].InjectClusterConfiguration(Cluster);
MultiCluster.WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
stopwatch.Stop();
output.WriteLine("Multicluster is ready (elapsed = {0}).", stopwatch.Elapsed);
}
else
{
output.WriteLine("Reusing existing {0} clusters and clients.", numclusters);
}
}
private ITestOutputHelper output;
public virtual void Dispose()
{
_hostedMultiCluster?.Dispose();
}
protected ClientWrapper[] Client;
protected string[] Cluster;
protected Random random;
protected int numclusters;
private const int Xyz = 333;
private void AssertEqual<T>(T expected, T actual, string grainIdentity)
{
if (! expected.Equals(actual))
{
// need to write grain identity to output so we can search for it in the trace
output.WriteLine($"identity of offending grain: {grainIdentity}");
Assert.Equal(expected, actual);
}
}
public async Task RunChecksOnGrainClass(string grainClass, bool may_update_in_all_clusters, int phases, ITestOutputHelper output)
{
var random = new SafeRandom();
Func<int> GetRandom = () => random.Next();
Func<Task> checker1 = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// force creation of replicas
for (int i = 0; i < numclusters; i++)
AssertEqual(0, Client[i].GetALocal(grainClass, x), grainIdentity);
// write global on client 0
Client[0].SetAGlobal(grainClass, x, Xyz);
// read global on other clients
for (int i = 1; i < numclusters; i++)
{
int r = Client[i].GetAGlobal(grainClass, x);
AssertEqual(Xyz, r, grainIdentity);
}
// check local stability
for (int i = 0; i < numclusters; i++)
AssertEqual(Xyz, Client[i].GetALocal(grainClass, x), grainIdentity);
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(1, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<Task> checker2 = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// increment on replica 0
Client[0].IncrementAGlobal(grainClass, x);
// expect on other replicas
for (int i = 1; i < numclusters; i++)
{
int r = Client[i].GetAGlobal(grainClass, x);
AssertEqual(1, r, grainIdentity);
}
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(1, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<Task> checker2b = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// force first creation on replica 1
AssertEqual(0, Client[1].GetAGlobal(grainClass, x), grainIdentity);
// increment on replica 0
Client[0].IncrementAGlobal(grainClass, x);
// expect on other replicas
for (int i = 1; i < numclusters; i++)
{
int r = Client[i].GetAGlobal(grainClass, x);
AssertEqual(1, r, grainIdentity);
}
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(1, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<int, Task> checker3 = (int numupdates) => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// concurrently chaotically increment (numupdates) times
Parallel.For(0, numupdates, i =>
{
var target = may_update_in_all_clusters ? i % numclusters : 0;
Client[target].IncrementALocal(grainClass, x);
});
if (may_update_in_all_clusters)
{
for (int i = 1; i < numclusters; i++)
Client[i].Synchronize(grainClass, x); // push all changes
}
// push & get all
AssertEqual(numupdates, Client[0].GetAGlobal(grainClass, x), grainIdentity);
for (int i = 1; i < numclusters; i++)
AssertEqual(numupdates, Client[i].GetAGlobal(grainClass, x), grainIdentity); // get all
// check versions
for (int i = 0; i < numclusters; i++)
AssertEqual(numupdates, Client[i].GetConfirmedVersion(grainClass, x), grainIdentity);
});
Func<Task> checker4 = () => Task.Run(() =>
{
int x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
var t = new List<Task>();
for (int i = 0; i < numclusters; i++)
{
int c = i;
t.Add(Task.Run(() => AssertEqual(true, Client[c].GetALocal(grainClass, x) == 0, grainIdentity)));
}
for (int i = 0; i < numclusters; i++)
{
int c = i;
t.Add(Task.Run(() => AssertEqual(true, Client[c].GetAGlobal(grainClass, x) == 0, grainIdentity)));
}
return Task.WhenAll(t);
});
Func<Task> checker5 = () => Task.Run(() =>
{
var x = GetRandom();
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
Task.WaitAll(
Task.Run(() =>
{
Client[0].AddReservationLocal(grainClass, x, 0);
Client[0].RemoveReservationLocal(grainClass, x, 0);
Client[0].Synchronize(grainClass, x);
}),
Task.Run(() =>
{
Client[1].AddReservationLocal(grainClass, x, 1);
Client[1].RemoveReservationLocal(grainClass, x, 1);
Client[1].AddReservationLocal(grainClass, x, 2);
Client[1].Synchronize(grainClass, x);
})
);
var result = Client[0].GetReservationsGlobal(grainClass, x);
AssertEqual(1, result.Length, grainIdentity);
AssertEqual(2, result[0], grainIdentity);
});
Func<int, Task> checker6 = async (int preload) =>
{
var x = GetRandom();
if (preload % 2 == 0)
Client[1].GetAGlobal(grainClass, x);
if ((preload / 2) % 2 == 0)
Client[0].GetAGlobal(grainClass, x);
bool[] done = new bool[numclusters - 1];
var t = new List<Task>();
// create listener tasks
for (int i = 1; i < numclusters; i++)
{
int c = i;
t.Add(Task.Run(async () =>
{
while (Client[c].GetALocal(grainClass, x) != 1)
await Task.Delay(100);
done[c - 1] = true;
}));
}
// send notification
Client[0].SetALocal(grainClass, x, 1);
await Task.WhenAny(
Task.Delay(20000),
Task.WhenAll(t)
);
Assert.True(done.All(b => b), string.Format("checker6({0}): update did not propagate within 20 sec", preload));
};
Func<int, Task> checker7 = (int variation) => Task.Run(async () =>
{
int x = GetRandom();
if (variation % 2 == 0)
Client[1].GetAGlobal(grainClass, x);
if ((variation / 2) % 2 == 0)
Client[0].GetAGlobal(grainClass, x);
var grainIdentity = string.Format("grainref={0}", Client[0].GetGrainRef(grainClass, x));
// write conditional on client 0, should always succeed
{
var result = Client[0].SetAConditional(grainClass, x, Xyz);
AssertEqual(0, result.Item1, grainIdentity);
AssertEqual(true, result.Item2, grainIdentity);
AssertEqual(1, Client[0].GetConfirmedVersion(grainClass, x), grainIdentity);
}
if ((variation / 4) % 2 == 1)
await Task.Delay(100);
// write conditional on Client[1], may or may not succeed based on timing
{
var result = Client[1].SetAConditional(grainClass, x, 444);
if (result.Item1 == 0) // was stale, thus failed
{
AssertEqual(false, result.Item2, grainIdentity);
// must have updated as a result
AssertEqual(1, Client[1].GetConfirmedVersion(grainClass, x), grainIdentity);
// check stability
AssertEqual(Xyz, Client[0].GetALocal(grainClass, x), grainIdentity);
AssertEqual(Xyz, Client[1].GetALocal(grainClass, x), grainIdentity);
AssertEqual(Xyz, Client[0].GetAGlobal(grainClass, x), grainIdentity);
AssertEqual(Xyz, Client[1].GetAGlobal(grainClass, x), grainIdentity);
}
else // was up-to-date, thus succeeded
{
AssertEqual(true, result.Item2, grainIdentity);
AssertEqual(1, result.Item1, grainIdentity);
// version is now 2
AssertEqual(2, Client[1].GetConfirmedVersion(grainClass, x), grainIdentity);
// check stability
AssertEqual(444, Client[1].GetALocal(grainClass, x), grainIdentity);
AssertEqual(444, Client[0].GetAGlobal(grainClass, x), grainIdentity);
AssertEqual(444, Client[1].GetAGlobal(grainClass, x), grainIdentity);
}
}
});
output.WriteLine("Running individual short tests");
// first, run short ones in sequence
await checker1();
await checker2();
await checker2b();
await checker3(4);
await checker3(20);
await checker4();
if (may_update_in_all_clusters)
await checker5();
await checker6(0);
await checker6(1);
await checker6(2);
await checker6(3);
if (may_update_in_all_clusters)
{
await checker7(0);
await checker7(4);
await checker7(7);
// run tests under blocked notification to force race one way
MultiCluster.SetProtocolMessageFilterForTesting(Cluster[0], msg => ! (msg is INotificationMessage));
await checker7(0);
await checker7(1);
await checker7(2);
await checker7(3);
MultiCluster.SetProtocolMessageFilterForTesting(Cluster[0], _ => true);
}
output.WriteLine("Running individual longer tests");
// then, run slightly longer tests
if (phases != 0)
{
await checker3(20);
await checker3(phases);
}
output.WriteLine("Running many concurrent test instances");
var tasks = new List<Task>();
for (int i = 0; i < phases; i++)
{
tasks.Add(checker1());
tasks.Add(checker2());
tasks.Add(checker2b());
tasks.Add(checker3(4));
tasks.Add(checker4());
if (may_update_in_all_clusters)
tasks.Add(checker5());
tasks.Add(checker6(0));
tasks.Add(checker6(1));
tasks.Add(checker6(2));
tasks.Add(checker6(3));
if (may_update_in_all_clusters)
{
tasks.Add(checker7(0));
tasks.Add(checker7(1));
tasks.Add(checker7(2));
tasks.Add(checker7(3));
tasks.Add(checker7(4));
tasks.Add(checker7(5));
tasks.Add(checker7(6));
tasks.Add(checker7(7));
}
}
await Task.WhenAll(tasks);
}
}
internal class LogConsistencyProviderSiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddCustomStorageBasedLogConsistencyProvider("StateStorage");
hostBuilder.AddCustomStorageBasedLogConsistencyProvider("LogStorage");
hostBuilder.AddCustomStorageBasedLogConsistencyProvider("CustomStorage");
hostBuilder.AddCustomStorageBasedLogConsistencyProvider("CustomStoragePrimaryCluster", "A");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using BlackFox.Binary;
using BlackFox.U2F.Codec;
using BlackFox.U2F.Gnubby.Simulated;
using BlackFox.U2F.Server.data;
using BlackFox.U2F.Server.messages;
using Common.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.X509;
namespace BlackFox.U2F.Server.impl
{
public class U2FServerReferenceImpl : IU2FServer
{
private const int BITS_IN_A_BYTE = 8;
private const string TYPE_PARAM = "typ";
private const string CHALLENGE_PARAM = "challenge";
private const string ORIGIN_PARAM = "origin";
private const string CHANNEL_ID_PARAM = "cid_pubkey";
private const string UNUSED_CHANNEL_ID = "";
private static readonly DerObjectIdentifier transportExtensionOid =
new DerObjectIdentifier("1.3.6.1.4.1.45724.2.1.1");
private static readonly ILog log = LogManager.GetLogger(typeof (U2FServerReferenceImpl));
private readonly ICollection<string> allowedOrigins;
private readonly IChallengeGenerator challengeGenerator;
private readonly IServerCrypto cryto;
private readonly IServerDataStore dataStore;
public U2FServerReferenceImpl(IChallengeGenerator challengeGenerator, IServerDataStore dataStore, IServerCrypto cryto,
ICollection<string> origins)
{
// Object Identifier for the attestation certificate transport extension fidoU2FTransports
// The number of bits in a byte. It is used to know at which index in a BitSet to look for
// specific transport values
// TODO: use these for channel id checks in verifyBrowserData
this.challengeGenerator = challengeGenerator;
this.dataStore = dataStore;
this.cryto = cryto;
allowedOrigins = CanonicalizeOrigins(origins);
}
public RegisterRequest GetRegistrationRequest(string accountName, string appId)
{
log.Info(">> getRegistrationRequest " + accountName);
var challenge = challengeGenerator.GenerateChallenge(accountName);
var sessionData = new EnrollSessionData(accountName, appId, challenge);
var sessionId = dataStore.StoreSessionData(sessionData);
var challengeBase64 = WebSafeBase64Converter.ToBase64String(challenge);
log.Info("-- Output --");
log.Info(" sessionId: " + sessionId);
log.Info(" challenge: " + challenge.ToHexString());
log.Info("<< getRegistrationRequest " + accountName);
return new RegisterRequest(U2FConsts.U2Fv2, challengeBase64, appId, sessionId);
}
/// <exception cref="U2FException" />
public SecurityKeyData ProcessRegistrationResponse(RegisterResponse registrationResponse,
long currentTimeInMillis)
{
log.Info(">> processRegistrationResponse");
var sessionId = registrationResponse.SessionId;
var browserDataBase64 = registrationResponse.Bd;
var rawRegistrationDataBase64 = registrationResponse.RegistrationData;
var sessionData = dataStore.GetEnrollSessionData(sessionId);
if (sessionData == null)
{
throw new U2FException("Unknown session_id");
}
var appId = sessionData.AppId;
var rawBrowserData = WebSafeBase64Converter.FromBase64String(browserDataBase64);
var browserData = Encoding.UTF8.GetString(rawBrowserData, 0, rawBrowserData.Length);
var rawRegistrationData = WebSafeBase64Converter.FromBase64String(rawRegistrationDataBase64);
log.Info("-- Input --");
log.Info(" sessionId: " + sessionId);
log.Info(" challenge: " + sessionData.Challenge.ToHexString());
log.Info(" accountName: " + sessionData.AccountName);
log.Info(" browserData: " + browserData);
log.Info(" rawRegistrationData: " + rawRegistrationData.ToHexString());
var registerResponse = RawMessageCodec.DecodeKeyRegisterResponse(rawRegistrationData.Segment());
var userPublicKey = registerResponse.UserPublicKey;
var keyHandle = registerResponse.KeyHandle;
var attestationCertificate = registerResponse.AttestationCertificate;
var signature = registerResponse.Signature;
IList<SecurityKeyDataTransports> transports = null;
try
{
transports = ParseTransportsExtension(attestationCertificate);
}
catch (CertificateParsingException e1)
{
log.Warn("Could not parse transports extension " + e1.Message);
}
log.Info("-- Parsed rawRegistrationResponse --");
log.Info(" userPublicKey: " + userPublicKey.ToHexString
());
log.Info(" keyHandle: " + keyHandle.ToHexString());
log.Info(" attestationCertificate: " + SecurityKeyData.SafeCertificateToString(attestationCertificate));
log.Info(" transports: " + transports);
log.Info(" attestationCertificate bytes: " + attestationCertificate.GetEncoded().ToHexString());
log.Info(" signature: " + signature.ToHexString());
var appIdSha256 = cryto.ComputeSha256(Encoding.UTF8.GetBytes(appId));
var browserDataSha256 = cryto.ComputeSha256(Encoding.UTF8.GetBytes(browserData));
var signedBytes = RawMessageCodec.EncodeKeyRegisterSignedBytes(appIdSha256, browserDataSha256, keyHandle,
userPublicKey);
var trustedCertificates = dataStore.GetTrustedCertificates();
if (!trustedCertificates.Contains(attestationCertificate))
{
log.Warn("Attestion cert is not trusted");
}
VerifyBrowserData(browserData, "navigator.id.finishEnrollment", sessionData);
log.Info("Verifying signature of bytes " + signedBytes.ToHexString());
if (!cryto.VerifySignature(attestationCertificate, signedBytes, signature))
{
throw new U2FException("Signature is invalid");
}
// The first time we create the SecurityKeyData, we set the counter value to -1.
// We don't actually know what the counter value of the real device is - but it will
// be something bigger than -1, so subsequent signatures will check out ok.
var securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle, userPublicKey,
attestationCertificate, -1);
/* initial counter value */
dataStore.AddSecurityKeyData(sessionData.AccountName, securityKeyData);
log.Info("<< processRegistrationResponse");
return securityKeyData;
}
public IList<SignRequest> GetSignRequests(string accountName, string appId)
{
log.Info(">> getSignRequest " + accountName);
var securityKeyDataList = dataStore.GetSecurityKeyData(accountName);
var result = new List<SignRequest>();
foreach (var securityKeyData in securityKeyDataList)
{
var challenge = challengeGenerator.GenerateChallenge(accountName);
var sessionData = new SignSessionData(accountName, appId, challenge, securityKeyData.PublicKey);
var sessionId = dataStore.StoreSessionData(sessionData);
var keyHandle = securityKeyData.KeyHandle;
log.Info("-- Output --");
log.Info(" sessionId: " + sessionId);
log.Info(" challenge: " + challenge.ToHexString());
log.Info(" keyHandle: " + keyHandle.ToHexString());
var challengeBase64 = WebSafeBase64Converter.ToBase64String(challenge);
var keyHandleBase64 = WebSafeBase64Converter.ToBase64String(keyHandle);
log.Info("<< getSignRequest " + accountName);
result.Add(new SignRequest(U2FConsts.U2Fv2, challengeBase64, appId, keyHandleBase64, sessionId));
}
return result;
}
public SecurityKeyData ProcessSignResponse(SignResponse signResponse)
{
log.Info(">> processSignResponse");
var sessionId = signResponse.SessionId;
var browserDataBase64 = signResponse.Bd;
var rawSignDataBase64 = signResponse.Sign;
var sessionData = dataStore.GetSignSessionData(sessionId);
if (sessionData == null)
{
throw new U2FException("Unknown session_id");
}
var appId = sessionData.AppId;
var securityKeyData = dataStore
.GetSecurityKeyData(sessionData.AccountName)
.FirstOrDefault(k => sessionData.GetPublicKey().SequenceEqual(k.PublicKey));
if (securityKeyData == null)
{
throw new U2FException("No security keys registered for this user");
}
var browserDataBytes = WebSafeBase64Converter.FromBase64String(browserDataBase64);
var browserData = Encoding.UTF8.GetString(browserDataBytes, 0, browserDataBytes.Length);
var rawSignData = WebSafeBase64Converter.FromBase64String(rawSignDataBase64);
log.Info("-- Input --");
log.Info(" sessionId: " + sessionId);
log.Info(" publicKey: " + securityKeyData.PublicKey.ToHexString());
log.Info(" challenge: " + sessionData.Challenge.ToHexString());
log.Info(" accountName: " + sessionData.AccountName);
log.Info(" browserData: " + browserData);
log.Info(" rawSignData: " + rawSignData.ToHexString());
VerifyBrowserData(browserData, "navigator.id.getAssertion", sessionData);
var authenticateResponse = RawMessageCodec.DecodeKeySignResponse(rawSignData.Segment());
var userPresence = authenticateResponse.UserPresence;
var counter = authenticateResponse.Counter;
var signature = authenticateResponse.Signature;
log.Info("-- Parsed rawSignData --");
log.Info(" userPresence: " + userPresence.ToString("X2"));
log.Info(" counter: " + counter);
log.Info(" signature: " + signature.ToHexString());
if (userPresence != UserPresenceVerifierConstants.UserPresentFlag)
{
throw new U2FException("User presence invalid during authentication");
}
if (counter <= securityKeyData.Counter)
{
throw new U2FException("Counter value smaller than expected!");
}
var appIdSha256 = cryto.ComputeSha256(Encoding.UTF8.GetBytes(appId));
var browserDataSha256 = cryto.ComputeSha256(Encoding.UTF8.GetBytes(browserData));
var signedBytes = RawMessageCodec.EncodeKeySignSignedBytes(appIdSha256, userPresence, counter,
browserDataSha256);
log.Info("Verifying signature of bytes " + signedBytes.ToHexString());
if (!cryto.VerifySignature(cryto.DecodePublicKey(securityKeyData.PublicKey), signedBytes, signature))
{
throw new U2FException("Signature is invalid");
}
dataStore.UpdateSecurityKeyCounter(sessionData.AccountName, securityKeyData.PublicKey, counter);
log.Info("<< processSignResponse");
return securityKeyData;
}
public IList<SecurityKeyData
> GetAllSecurityKeys(string accountName)
{
return dataStore.GetSecurityKeyData(accountName);
}
/// <exception cref="U2FException" />
public void RemoveSecurityKey(string accountName, byte[] publicKey)
{
dataStore.RemoveSecurityKey(accountName, publicKey);
}
/// <summary>
/// Parses a transport extension from an attestation certificate and returns
/// a List of HardwareFeatures supported by the security key.
/// </summary>
/// <remarks>
/// Parses a transport extension from an attestation certificate and returns
/// a List of HardwareFeatures supported by the security key. The specification of
/// the HardwareFeatures in the certificate should match their internal definition in
/// device_auth.proto
/// <p>
/// The expected transport extension value is a BIT STRING containing the enabled
/// transports:
/// </p>
/// <p>
/// FIDOU2FTransports ::= BIT STRING {
/// bluetoothRadio(0), -- Bluetooth Classic
/// bluetoothLowEnergyRadio(1),
/// uSB(2),
/// nFC(3)
/// }
/// </p>
/// <p>
/// Note that the BIT STRING must be wrapped in an OCTET STRING.
/// An extension that encodes BT, BLE, and NFC then looks as follows:
/// </p>
/// <p>
/// SEQUENCE (2 elem)
/// OBJECT IDENTIFIER 1.3.6.1.4.1.45724.2.1.1
/// OCTET STRING (1 elem)
/// BIT STRING (4 bits) 1101
/// </p>
/// </remarks>
/// <param name="cert">the certificate to parse for extension</param>
/// <returns>
/// the supported transports as a List of HardwareFeatures or null if no extension
/// was found
/// </returns>
/// <exception cref="CertificateParsingException" />
public static IList<SecurityKeyDataTransports> ParseTransportsExtension(X509Certificate cert)
{
var extValue = cert.GetExtensionValue(transportExtensionOid);
var transportsList = new List<SecurityKeyDataTransports>();
if (extValue == null)
{
// No transports extension found.
return null;
}
// Read out the OctetString
var asn1Object = extValue.ToAsn1Object();
if (!(asn1Object is DerOctetString))
{
throw new CertificateParsingException("No Octet String found in transports extension");
}
var octet = (DerOctetString) asn1Object;
// Read out the BitString
try
{
using (var ais = new Asn1InputStream(octet.GetOctets()))
{
asn1Object = ais.ReadObject();
}
}
catch (IOException e)
{
throw new CertificateParsingException("Not able to read object in transports extension", e);
}
if (!(asn1Object is DerBitString))
{
throw new CertificateParsingException("No BitString found in transports extension");
}
var bitString = (DerBitString) asn1Object;
var values = bitString.GetBytes();
var bitSet = new BitArray(values);
// We might have more defined transports than used by the extension
for (var i = 0; i < BITS_IN_A_BYTE; i++)
{
if (bitSet.Get(BITS_IN_A_BYTE - i - 1))
{
transportsList.Add((SecurityKeyDataTransports) i);
}
}
return transportsList;
}
/// <exception cref="U2FException" />
private void VerifyBrowserData(string browserData, string messageType, EnrollSessionData sessionData)
{
JObject browserDataObject;
try
{
browserDataObject = JObject.Parse(browserData);
}
catch (JsonReaderException e)
{
throw new U2FException("browserdata has wrong format", e);
}
VerifyBrowserData(browserDataObject, messageType, sessionData);
}
/// <exception cref="U2FException" />
private void VerifyBrowserData(JObject browserData, string messageType, EnrollSessionData sessionData)
{
// check that the right "typ" parameter is present in the browserdata JSON
var typeProperty = browserData.Property(TYPE_PARAM);
if (typeProperty == null)
{
throw new U2FException($"bad browserdata: missing '{TYPE_PARAM}' param");
}
var type = typeProperty.Value.ToString();
if (messageType != type)
{
throw new U2FException("bad browserdata: bad type " + type);
}
var originProperty = browserData.Property(ORIGIN_PARAM);
if (originProperty != null)
{
VerifyOrigin(originProperty.Value.ToString());
}
// check that the right challenge is in the browserdata
var challengeProperty = browserData.Property(CHALLENGE_PARAM);
if (challengeProperty == null)
{
throw new U2FException($"bad browserdata: missing '{CHALLENGE_PARAM}' param");
}
var challengeFromBrowserData = WebSafeBase64Converter.FromBase64String(challengeProperty.Value.ToString());
if (!challengeFromBrowserData.SequenceEqual(sessionData.Challenge))
{
throw new U2FException("wrong challenge signed in browserdata");
}
}
// TODO: Deal with ChannelID
/// <exception cref="U2FException" />
private void VerifyOrigin(string origin)
{
if (!allowedOrigins.Contains(CanonicalizeOrigin(origin)))
{
throw new U2FException(origin + " is not a recognized home origin for this backend");
}
}
private static ICollection<string> CanonicalizeOrigins(IEnumerable<string> origins)
{
return origins.Select(CanonicalizeOrigin).ToList();
}
internal static string CanonicalizeOrigin(string url)
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
{
throw new U2FException($"Specified bad origin: {url}");
}
return uri.Scheme + "://" + GetAuthority(uri);
}
private static string GetAuthority(Uri uri)
{
var isDefaultPort =
(uri.Scheme == "http" && uri.Port == 80) ||
(uri.Scheme == "https" && uri.Port == 443);
return uri.DnsSafeHost + (isDefaultPort ? "" : ":" + uri.Port);
}
}
}
| |
using Internal.ReadLine.Abstractions;
using System;
using System.Collections.Generic;
using System.Text;
namespace Internal.ReadLine
{
internal class KeyHandler
{
private int _cursorPos;
private int _cursorLimit;
private StringBuilder _text;
private List<string> _history;
private int _historyIndex;
private ConsoleKeyInfo _keyInfo;
private Dictionary<string, Action> _keyActions;
private string[] _completions;
private int _completionStart;
private int _completionsIndex;
private IConsole Console2;
private bool IsStartOfLine() => _cursorPos == 0;
private bool IsEndOfLine() => _cursorPos == _cursorLimit;
private bool IsStartOfBuffer() => Console2.CursorLeft == 0;
private bool IsEndOfBuffer() => Console2.CursorLeft == Console2.BufferWidth - 1;
private bool IsInAutoCompleteMode() => _completions != null;
private void MoveCursorLeft()
{
if (IsStartOfLine())
return;
if (IsStartOfBuffer())
Console2.SetCursorPosition(Console2.BufferWidth - 1, Console2.CursorTop - 1);
else
Console2.SetCursorPosition(Console2.CursorLeft - 1, Console2.CursorTop);
_cursorPos--;
}
private void MoveCursorHome()
{
while (!IsStartOfLine())
MoveCursorLeft();
}
private string BuildKeyInput()
{
return (_keyInfo.Modifiers != ConsoleModifiers.Control && _keyInfo.Modifiers != ConsoleModifiers.Shift) ?
_keyInfo.Key.ToString() : _keyInfo.Modifiers.ToString() + _keyInfo.Key.ToString();
}
private void MoveCursorRight()
{
if (IsEndOfLine())
return;
if (IsEndOfBuffer())
Console2.SetCursorPosition(0, Console2.CursorTop + 1);
else
Console2.SetCursorPosition(Console2.CursorLeft + 1, Console2.CursorTop);
_cursorPos++;
}
private void MoveCursorEnd()
{
while (!IsEndOfLine())
MoveCursorRight();
}
private void ClearLine()
{
MoveCursorEnd();
while (!IsStartOfLine())
Backspace();
}
private void WriteNewString(string str)
{
ClearLine();
foreach (char character in str)
WriteChar(character);
}
private void WriteString(string str)
{
foreach (char character in str)
WriteChar(character);
}
private void WriteChar() => WriteChar(_keyInfo.KeyChar);
private void WriteChar(char c)
{
if (IsEndOfLine())
{
_text.Append(c);
Console2.Write(c.ToString());
_cursorPos++;
}
else
{
int left = Console2.CursorLeft;
int top = Console2.CursorTop;
string str = _text.ToString().Substring(_cursorPos);
_text.Insert(_cursorPos, c);
Console2.Write(c.ToString() + str);
Console2.SetCursorPosition(left, top);
MoveCursorRight();
}
_cursorLimit++;
}
private void Backspace()
{
if (IsStartOfLine())
return;
MoveCursorLeft();
int index = _cursorPos;
_text.Remove(index, 1);
string replacement = _text.ToString().Substring(index);
int left = Console2.CursorLeft;
int top = Console2.CursorTop;
Console2.Write(string.Format("{0} ", replacement));
Console2.SetCursorPosition(left, top);
_cursorLimit--;
}
private void Delete()
{
if (IsEndOfLine())
return;
int index = _cursorPos;
_text.Remove(index, 1);
string replacement = _text.ToString().Substring(index);
int left = Console2.CursorLeft;
int top = Console2.CursorTop;
Console2.Write(string.Format("{0} ", replacement));
Console2.SetCursorPosition(left, top);
_cursorLimit--;
}
private void TransposeChars()
{
// local helper functions
bool almostEndOfLine() => (_cursorLimit - _cursorPos) == 1;
int incrementIf(Func<bool> expression, int index) => expression() ? index + 1 : index;
int decrementIf(Func<bool> expression, int index) => expression() ? index - 1 : index;
if (IsStartOfLine()) { return; }
var firstIdx = decrementIf(IsEndOfLine, _cursorPos - 1);
var secondIdx = decrementIf(IsEndOfLine, _cursorPos);
var secondChar = _text[secondIdx];
_text[secondIdx] = _text[firstIdx];
_text[firstIdx] = secondChar;
var left = incrementIf(almostEndOfLine, Console2.CursorLeft);
var cursorPosition = incrementIf(almostEndOfLine, _cursorPos);
WriteNewString(_text.ToString());
Console2.SetCursorPosition(left, Console2.CursorTop);
_cursorPos = cursorPosition;
MoveCursorRight();
}
private void StartAutoComplete()
{
while (_cursorPos > _completionStart)
Backspace();
_completionsIndex = 0;
WriteString(_completions[_completionsIndex]);
}
private void NextAutoComplete()
{
while (_cursorPos > _completionStart)
Backspace();
_completionsIndex++;
if (_completionsIndex == _completions.Length)
_completionsIndex = 0;
WriteString(_completions[_completionsIndex]);
}
private void PreviousAutoComplete()
{
while (_cursorPos > _completionStart)
Backspace();
_completionsIndex--;
if (_completionsIndex == -1)
_completionsIndex = _completions.Length - 1;
WriteString(_completions[_completionsIndex]);
}
private void PrevHistory()
{
if (_historyIndex > 0)
{
_historyIndex--;
WriteNewString(_history[_historyIndex]);
}
}
private void NextHistory()
{
if (_historyIndex < _history.Count)
{
_historyIndex++;
if (_historyIndex == _history.Count)
ClearLine();
else
WriteNewString(_history[_historyIndex]);
}
}
private void ResetAutoComplete()
{
_completions = null;
_completionsIndex = 0;
}
public string Text
{
get
{
return _text.ToString();
}
}
public KeyHandler(IConsole console, List<string> history, IAutoCompleteHandler autoCompleteHandler)
{
Console2 = console;
_history = history ?? new List<string>();
_historyIndex = _history.Count;
_text = new StringBuilder();
_keyActions = new Dictionary<string, Action>();
_keyActions["LeftArrow"] = MoveCursorLeft;
_keyActions["Home"] = MoveCursorHome;
_keyActions["End"] = MoveCursorEnd;
_keyActions["ControlA"] = MoveCursorHome;
_keyActions["ControlB"] = MoveCursorLeft;
_keyActions["RightArrow"] = MoveCursorRight;
_keyActions["ControlF"] = MoveCursorRight;
_keyActions["ControlE"] = MoveCursorEnd;
_keyActions["Backspace"] = Backspace;
_keyActions["Delete"] = Delete;
_keyActions["ControlD"] = Delete;
_keyActions["ControlH"] = Backspace;
_keyActions["ControlL"] = ClearLine;
_keyActions["Escape"] = ClearLine;
_keyActions["UpArrow"] = PrevHistory;
_keyActions["ControlP"] = PrevHistory;
_keyActions["DownArrow"] = NextHistory;
_keyActions["ControlN"] = NextHistory;
_keyActions["ControlU"] = () =>
{
while (!IsStartOfLine())
Backspace();
};
_keyActions["ControlK"] = () =>
{
int pos = _cursorPos;
MoveCursorEnd();
while (_cursorPos > pos)
Backspace();
};
_keyActions["ControlW"] = () =>
{
while (!IsStartOfLine() && _text[_cursorPos - 1] != ' ')
Backspace();
};
_keyActions["ControlT"] = TransposeChars;
_keyActions["Tab"] = () =>
{
if (IsInAutoCompleteMode())
{
NextAutoComplete();
}
else
{
if (autoCompleteHandler == null || !IsEndOfLine())
return;
string text = _text.ToString();
_completionStart = text.LastIndexOfAny(autoCompleteHandler.Separators);
_completionStart = _completionStart == -1 ? 0 : _completionStart + 1;
_completions = autoCompleteHandler.GetSuggestions(text, _completionStart);
_completions = _completions?.Length == 0 ? null : _completions;
if (_completions == null)
return;
StartAutoComplete();
}
};
_keyActions["ShiftTab"] = () =>
{
if (IsInAutoCompleteMode())
{
PreviousAutoComplete();
}
};
}
public void Handle(ConsoleKeyInfo keyInfo)
{
_keyInfo = keyInfo;
// If in auto complete mode and Tab wasn't pressed
if (IsInAutoCompleteMode() && _keyInfo.Key != ConsoleKey.Tab)
ResetAutoComplete();
Action action;
_keyActions.TryGetValue(BuildKeyInput(), out action);
action = action ?? WriteChar;
action.Invoke();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Caching;
namespace Coevery.Mvc.Wrappers {
public abstract class HttpResponseBaseWrapper : HttpResponseBase {
private readonly HttpResponseBase _httpResponseBase;
protected HttpResponseBaseWrapper(HttpResponseBase httpResponse) {
_httpResponseBase = httpResponse;
}
public override void AddCacheDependency(params CacheDependency[] dependencies) {
_httpResponseBase.AddCacheDependency(dependencies);
}
public override void AddCacheItemDependencies(ArrayList cacheKeys) {
_httpResponseBase.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependencies(string[] cacheKeys) {
_httpResponseBase.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependency(string cacheKey) {
_httpResponseBase.AddCacheItemDependency(cacheKey);
}
public override void AddFileDependencies(string[] filenames) {
_httpResponseBase.AddFileDependencies(filenames);
}
public override void AddFileDependencies(ArrayList filenames) {
_httpResponseBase.AddFileDependencies(filenames);
}
public override void AddFileDependency(string filename) {
_httpResponseBase.AddFileDependency(filename);
}
public override void AddHeader(string name, string value) {
_httpResponseBase.AddHeader(name, value);
}
public override void AppendCookie(HttpCookie cookie) {
_httpResponseBase.AppendCookie(cookie);
}
public override void AppendHeader(string name, string value) {
_httpResponseBase.AppendHeader(name, value);
}
public override void AppendToLog(string param) {
_httpResponseBase.AppendToLog(param);
}
public override string ApplyAppPathModifier(string virtualPath) {
return _httpResponseBase.ApplyAppPathModifier(virtualPath);
}
public override void BinaryWrite(byte[] buffer) {
_httpResponseBase.BinaryWrite(buffer);
}
public override void Clear() {
_httpResponseBase.Clear();
}
public override void ClearContent() {
_httpResponseBase.ClearContent();
}
public override void ClearHeaders() {
_httpResponseBase.ClearHeaders();
}
public override void Close() {
_httpResponseBase.Close();
}
public override void DisableKernelCache() {
_httpResponseBase.DisableKernelCache();
}
public override void End() {
_httpResponseBase.End();
}
public override void Flush() {
_httpResponseBase.Flush();
}
public override void Pics(string value) {
_httpResponseBase.Pics(value);
}
public override void Redirect(string url) {
_httpResponseBase.Redirect(url);
}
public override void Redirect(string url, bool endResponse) {
_httpResponseBase.Redirect(url, endResponse);
}
public override void RemoveOutputCacheItem(string path) {
_httpResponseBase.RemoveOutputCacheItem(path);
}
public override void SetCookie(HttpCookie cookie) {
_httpResponseBase.SetCookie(cookie);
}
public override void TransmitFile(string filename) {
_httpResponseBase.TransmitFile(filename);
}
public override void TransmitFile(string filename, long offset, long length) {
_httpResponseBase.TransmitFile(filename, offset, length);
}
public override void Write(char ch) {
_httpResponseBase.Write(ch);
}
public override void Write(object obj) {
_httpResponseBase.Write(obj);
}
public override void Write(string s) {
_httpResponseBase.Write(s);
}
public override void Write(char[] buffer, int index, int count) {
_httpResponseBase.Write(buffer, index, count);
}
public override void WriteFile(string filename) {
_httpResponseBase.WriteFile(filename);
}
public override void WriteFile(string filename, bool readIntoMemory) {
_httpResponseBase.WriteFile(filename, readIntoMemory);
}
public override void WriteFile(IntPtr fileHandle, long offset, long size) {
_httpResponseBase.WriteFile(fileHandle, offset, size);
}
public override void WriteFile(string filename, long offset, long size) {
_httpResponseBase.WriteFile(filename, offset, size);
}
public override void WriteSubstitution(HttpResponseSubstitutionCallback callback) {
_httpResponseBase.WriteSubstitution(callback);
}
// Properties
public override bool Buffer {
get {
return _httpResponseBase.Buffer;
}
set {
_httpResponseBase.Buffer = value;
}
}
public override bool BufferOutput {
get {
return _httpResponseBase.BufferOutput;
}
set {
_httpResponseBase.BufferOutput = value;
}
}
public override HttpCachePolicyBase Cache {
get {
return _httpResponseBase.Cache;
}
}
public override string CacheControl {
get {
return _httpResponseBase.CacheControl;
}
set {
_httpResponseBase.CacheControl = value;
}
}
public override string Charset {
get {
return _httpResponseBase.Charset;
}
set {
_httpResponseBase.Charset = value;
}
}
public override Encoding ContentEncoding {
get {
return _httpResponseBase.ContentEncoding;
}
set {
_httpResponseBase.ContentEncoding = value;
}
}
public override string ContentType {
get {
return _httpResponseBase.ContentType;
}
set {
_httpResponseBase.ContentType = value;
}
}
public override HttpCookieCollection Cookies {
get {
return _httpResponseBase.Cookies;
}
}
public override int Expires {
get {
return _httpResponseBase.Expires;
}
set {
_httpResponseBase.Expires = value;
}
}
public override DateTime ExpiresAbsolute {
get {
return _httpResponseBase.ExpiresAbsolute;
}
set {
_httpResponseBase.ExpiresAbsolute = value;
}
}
public override Stream Filter {
get {
return _httpResponseBase.Filter;
}
set {
_httpResponseBase.Filter = value;
}
}
public override Encoding HeaderEncoding {
get {
return _httpResponseBase.HeaderEncoding;
}
set {
_httpResponseBase.HeaderEncoding = value;
}
}
public override NameValueCollection Headers {
get {
return _httpResponseBase.Headers;
}
}
public override bool IsClientConnected {
get {
return _httpResponseBase.IsClientConnected;
}
}
public override bool IsRequestBeingRedirected {
get {
return _httpResponseBase.IsRequestBeingRedirected;
}
}
public override TextWriter Output {
get {
return _httpResponseBase.Output;
}
}
public override Stream OutputStream {
get {
return _httpResponseBase.OutputStream;
}
}
public override string RedirectLocation {
get {
return _httpResponseBase.RedirectLocation;
}
set {
_httpResponseBase.RedirectLocation = value;
}
}
public override string Status {
get {
return _httpResponseBase.Status;
}
set {
_httpResponseBase.Status = value;
}
}
public override int StatusCode {
get {
return _httpResponseBase.StatusCode;
}
set {
_httpResponseBase.StatusCode = value;
}
}
public override string StatusDescription {
get {
return _httpResponseBase.StatusDescription;
}
set {
_httpResponseBase.StatusDescription = value;
}
}
public override int SubStatusCode {
get {
return _httpResponseBase.SubStatusCode;
}
set {
_httpResponseBase.SubStatusCode = value;
}
}
public override bool SuppressContent {
get {
return _httpResponseBase.SuppressContent;
}
set {
_httpResponseBase.SuppressContent = value;
}
}
public override bool TrySkipIisCustomErrors {
get {
return _httpResponseBase.TrySkipIisCustomErrors;
}
set {
_httpResponseBase.TrySkipIisCustomErrors = value;
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the ConLauraPacientesNutricion2012 class.
/// </summary>
[Serializable]
public partial class ConLauraPacientesNutricion2012Collection : ReadOnlyList<ConLauraPacientesNutricion2012, ConLauraPacientesNutricion2012Collection>
{
public ConLauraPacientesNutricion2012Collection() {}
}
/// <summary>
/// This is Read-only wrapper class for the CON_laura_pacientesNutricion2012 view.
/// </summary>
[Serializable]
public partial class ConLauraPacientesNutricion2012 : ReadOnlyRecord<ConLauraPacientesNutricion2012>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_laura_pacientesNutricion2012", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema);
colvarIdPaciente.ColumnName = "idPaciente";
colvarIdPaciente.DataType = DbType.Int32;
colvarIdPaciente.MaxLength = 0;
colvarIdPaciente.AutoIncrement = false;
colvarIdPaciente.IsNullable = false;
colvarIdPaciente.IsPrimaryKey = false;
colvarIdPaciente.IsForeignKey = false;
colvarIdPaciente.IsReadOnly = false;
schema.Columns.Add(colvarIdPaciente);
TableSchema.TableColumn colvarDni = new TableSchema.TableColumn(schema);
colvarDni.ColumnName = "dni";
colvarDni.DataType = DbType.Int32;
colvarDni.MaxLength = 0;
colvarDni.AutoIncrement = false;
colvarDni.IsNullable = false;
colvarDni.IsPrimaryKey = false;
colvarDni.IsForeignKey = false;
colvarDni.IsReadOnly = false;
schema.Columns.Add(colvarDni);
TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema);
colvarApellido.ColumnName = "apellido";
colvarApellido.DataType = DbType.String;
colvarApellido.MaxLength = 100;
colvarApellido.AutoIncrement = false;
colvarApellido.IsNullable = false;
colvarApellido.IsPrimaryKey = false;
colvarApellido.IsForeignKey = false;
colvarApellido.IsReadOnly = false;
schema.Columns.Add(colvarApellido);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
schema.Columns.Add(colvarNombre);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "sexo";
colvarSexo.DataType = DbType.String;
colvarSexo.MaxLength = 50;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = false;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarFechanacimiento = new TableSchema.TableColumn(schema);
colvarFechanacimiento.ColumnName = "fechanacimiento";
colvarFechanacimiento.DataType = DbType.DateTime;
colvarFechanacimiento.MaxLength = 0;
colvarFechanacimiento.AutoIncrement = false;
colvarFechanacimiento.IsNullable = false;
colvarFechanacimiento.IsPrimaryKey = false;
colvarFechanacimiento.IsForeignKey = false;
colvarFechanacimiento.IsReadOnly = false;
schema.Columns.Add(colvarFechanacimiento);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_laura_pacientesNutricion2012",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public ConLauraPacientesNutricion2012()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public ConLauraPacientesNutricion2012(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public ConLauraPacientesNutricion2012(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public ConLauraPacientesNutricion2012(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("IdPaciente")]
[Bindable(true)]
public int IdPaciente
{
get
{
return GetColumnValue<int>("idPaciente");
}
set
{
SetColumnValue("idPaciente", value);
}
}
[XmlAttribute("Dni")]
[Bindable(true)]
public int Dni
{
get
{
return GetColumnValue<int>("dni");
}
set
{
SetColumnValue("dni", value);
}
}
[XmlAttribute("Apellido")]
[Bindable(true)]
public string Apellido
{
get
{
return GetColumnValue<string>("apellido");
}
set
{
SetColumnValue("apellido", value);
}
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get
{
return GetColumnValue<string>("nombre");
}
set
{
SetColumnValue("nombre", value);
}
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public string Sexo
{
get
{
return GetColumnValue<string>("sexo");
}
set
{
SetColumnValue("sexo", value);
}
}
[XmlAttribute("Fechanacimiento")]
[Bindable(true)]
public DateTime Fechanacimiento
{
get
{
return GetColumnValue<DateTime>("fechanacimiento");
}
set
{
SetColumnValue("fechanacimiento", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdPaciente = @"idPaciente";
public static string Dni = @"dni";
public static string Apellido = @"apellido";
public static string Nombre = @"nombre";
public static string Sexo = @"sexo";
public static string Fechanacimiento = @"fechanacimiento";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
public CharacterController GetCharacterController()
{
return m_CharacterController;
}
public void SetFootStepsSound (List<AudioClip> footstepsSounds)
{
m_FootstepSounds = footstepsSounds.ToArray();
}
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
//RotateView();
// the jump state needs to read here to make sure it is not missed
/*if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}*/
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = m_Camera.transform.forward*m_Input.y + m_Camera.transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// 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;
/// <summary>
/// System.Collections.ICollection.CopyTo(System.Array,System.Int32)
/// </summary>
public class ICollectionCopyTo
{
const int Count = 1000;
static Random m_rand = new Random(-55);
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
byte[] array = new byte[Count];
TestLibrary.TestFramework.BeginScenario("PosTest1: Using Arraylist which implemented the CopyTo method in ICollection ");
try
{
((ICollection)arrayList).CopyTo(array, 0);
for (int i = 0; i < Count; i++)
{
if ((byte)(arrayList[i]) != array[i])
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
int index =m_rand.Next(1,1000);
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
byte[] array = new byte[Count+index];
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the start index is not zero...");
try
{
((ICollection)arrayList).CopyTo(array, index);
for (int i = 0; i < Count; i++)
{
if ((byte)(arrayList[i]) != array[i+index])
{
TestLibrary.TestFramework.LogError("002", "The result is not the value as expected");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
int index = m_rand.Next(1, 1000);
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
byte[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest1: Verify the array is a null reference");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected when array is a null reference");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
int index = m_rand.Next(1, 1000);
byte[] array = new byte[Count];
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest2: Verify the index is less than zero");
try
{
index = -index;
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected when index is "+index.ToString());
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
byte[] array = new byte[Count];
int index = array.Length;
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest3: Verify the index is equal the length of array");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("105", "The ArgumentException was not thrown as expected when index equal length of array");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
byte[] array = new byte[Count];
int index = array.Length +m_rand.Next(1, 1000);
List<object> arrayList = new List<object>();
Byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest4: Verify the index is greater than the length of array");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("107", "The ArgumentException was not thrown as expected. \n index is " + index.ToString() + "\n array length is " + array.Length.ToString());
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
Array array = new byte[Count,Count];
int index = m_rand.Next(1, 1000);
byte[] byteValue = new byte[Count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest5: Verify the array is multidimensional");
try
{
((ICollection)arrayList).CopyTo(array, array.Length);
TestLibrary.TestFramework.LogError("109", "The ArgumentException was not thrown as expected when the array is multidimensional");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
int count = Count + m_rand.Next(1, 1000);
byte[] array = new byte[Count];
int index = m_rand.Next(1,1000);
byte[] byteValue = new byte[count];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<object> arrayList = new List<object>();
for (int i = 0; i < count; i++)
{
arrayList.Add(byteValue[i]);
}
TestLibrary.TestFramework.BeginScenario("NegTest6: The number of elements in the ICollection is greater than the available space from index to the end of array");
try
{
((ICollection)arrayList).CopyTo(array, array.Length);
TestLibrary.TestFramework.LogError("111", "The ArgumentException was not thrown as expecteds");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
int index = m_rand.Next(1, 1000);
byte[] array = new byte[Count+index];
List<object> arrayList = new List<object>();
for (int i = 0; i < Count; i++)
{
arrayList.Add(new object());
}
TestLibrary.TestFramework.BeginScenario("NegTest7: Verify the type of the ICollection cannot be cast automatically to the type of array");
try
{
((ICollection)arrayList).CopyTo(array, index);
TestLibrary.TestFramework.LogError("113", "The InvalidCastException was not thrown as expected");
retVal = false;
}
catch (InvalidCastException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ICollectionCopyTo test = new ICollectionCopyTo();
TestLibrary.TestFramework.BeginTestCase("Test for method:System.Collections.ICollection.CopyTo(System.Array,System.Int32)");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace ICSimulator
{
public class BitValuePair
{
public int bits;
public ulong val
{
get { return ((ulong)1) << bits; }
set
{
bits = (int)Math.Ceiling(Math.Log(value, 2));
if ((int)Math.Floor(Math.Log(value, 2)) != bits)
throw new Exception("Only settable to powers of two!");
}
}
public BitValuePair(int bits)
{
this.bits = bits;
}
}
public abstract class ConfigGroup
{
/// <summary>
/// Special switch for complex parameter initialization
/// </summary>
protected abstract bool setSpecialParameter(string param, string val);
/// <summary>
/// Verify member parameters; called after all options are parsed.
/// </summary>
public abstract void finalize();
public void setParameter(string param, string val)
{
if (setSpecialParameter(param, val))
return;
try
{
FieldInfo fi = GetType().GetField(param);
Type t = fi.FieldType;
if (t == typeof(int))
fi.SetValue(this, int.Parse(val));
else if (t == typeof(ulong))
fi.SetValue(this, ulong.Parse(val));
else if (t == typeof(double))
fi.SetValue(this, double.Parse(val));
else if (t == typeof(bool))
fi.SetValue(this, bool.Parse(val));
else if (t == typeof(string))
fi.SetValue(this, val);
else if (t.BaseType == typeof(Enum))
fi.SetValue(this, Enum.Parse(t, val));
else if (t == typeof(BitValuePair))
((BitValuePair)fi.GetValue(this)).bits = int.Parse(val);
else
throw new Exception(String.Format("Unhandled parameter type {0}", t));
}
catch (NullReferenceException e)
{
Console.WriteLine("Parameter {0} not found!", param);
throw e;
}
}
}
public enum BinningMethod
{
NONE,
KMEANS,
EQUAL_PER,
DELTA
}
public enum Topology
{
HR_4drop,
HR_8drop,
HR_16drop,
HR_8_16drop,
HR_8_8drop,
HR_16_8drop,
HR_32_8drop,
HR_buffered,
SingleRing,
MeshOfRings,
Mesh,
BufRingNetwork,
BufRingNetworkMulti
}
public class Config : ConfigGroup
{
public static ProcessorConfig proc = new ProcessorConfig();
public static MemoryConfig memory = new MemoryConfig();
public static RouterConfig router = new RouterConfig();
// ----
// Buffered Rings (Ravindran et al, HPCA 1997)
public static int bufrings_n = 1; // number of virtual networks
public static int bufrings_locallat = 2; // cycles per local ring hop (router + link)
public static int bufrings_globallat = 3; // cycles per global ring hop (router + link)
public static int bufrings_localbuf = 4;
public static int bufrings_globalbuf = 4;
public static int bufrings_L2G = 4;
public static int bufrings_G2L = 4;
public static int bufrings_levels = 2;
public static int bufrings_branching = 4;
public static bool bufrings_inf_credit = false;
// ---- GraphLabs (and other traces that has barriers at the end
public static bool endOfTraceSync = false;
// ---- Synthetic HPCA 13
public static double non_local_chance = 1.0;
// ---- MICRO'11
// -- close-to-original hotnets
public static bool hotnets_closedloop_rate = false; // false = orig. paper, true = feedback loop
public static double hotnets_max_throttle = 0.75;
public static double hotnets_min_throttle = 0.45;
public static double hotnets_scale = 0.30;
public static int hotnets_ipc_quantum = 10000;
// also uses selftuned_quantum for either (i) rate adjustment step or (ii) throttling update step
public static double hotnets_starve_max = 0.8;
public static double hotnets_starve_min = 0.2;
public static double hotnets_starve_scale = 0.35;
public static int hotnets_starve_window = 128;
public static int hotnets_qlen_window = 1000;
// -- AFC
public static int afc_buf_per_vnet = 8;
public static int afc_vnets = 8;
public static bool afc_real_classes = false; // otherwise, randomize for even distribution
public static int afc_avg_window = 4;
public static double afc_ewma_history = 0.05;
public static double afc_buf_threshold = 0.6;
public static double afc_bless_threshold = 0.5;
public static bool afc_force = false; // force bufferless or buffered mode?
public static bool afc_force_buffered = true; // if force, force buffered or bufferless?
// -- self-tuned congestion control (simple netutil-based throttler)
public static int selftuned_quantum = 128; // update once per quantum
public static int selftuned_netutil_window = 64;
public static bool selftuned_bangbang = false; // true = bang-bang control, false = adj. throt rate
public static double selftuned_rate_delta = 0.01; // throt-rate delta
public static double selftuned_netutil_tolerance = 0.05; // tolerance on either side of target (hysteresis)
public static double selftuned_init_netutil_target = 0.7;
// -- self-tuned congestion control: hillclimbing based on above netutil-target-seeking
public static bool selftuned_seek_higher_ground = false; // hillclimb on IPC? (off by default)
public static int selftuned_ipc_window = 100000;
public static int selftuned_ipc_quantum = 100000;
public static double selftuned_drop_threshold = 0.9; //0.75;
public static double selftuned_target_decrease = 0.02;
public static double selftuned_target_increase = 0.02;
// ---- Global RR throttling
public static bool cluster_prios = false;
public static bool cluster_prios_injq = false; // extend prios into inj Q
public static double MPKI_max_thresh = 50;
public static double MPKI_min_thresh = 35;
public static double MPKI_high_node = 50;
public static int num_epoch=3;
public static double thresholdWeight=0.1;
public static bool canAddEmptyCluster = false;
public static int short_life_interval=10;
public static double throttling_threshold=2.0;
public static double netutil_throttling_threshold=0.5;
/* PARAMETERS THAT MATTER FOR Controller_Three_Level_Cluster_NoTrigger.cs
* This is the final controller for MICRO */
public static int throttle_sampling_period=100000;
public static int interval_length=1000;
public static double netutil_throttling_target=0.6;
//Thorttling rate for high and always throttled cluster
public static double RR_throttle_rate=0;
public static double max_throttle_rate=0.95;
//Low intensity cluster total MPKI cap
public static double free_total_MPKI = 150;
public static double cluster_MPKI_threshold = 50;
public static bool always_cluster_enabled=true;
public static bool low_cluster_filling_enabled=true;
public static double low_apps_mpki_thresh=30;
///////////////////////////////////////////////////
public static bool adaptive_cluster_mpki=false;
public static bool alpha=false;
public static bool adaptive_rate=false;
// ---- Cluster will try to map far node to the same cluster
public static bool distanceAwareCluster = true;
// ---- Static Controller
// static throttle rate
public static double sweep_th_rate = 0;
// specify which node to throttle when using static throttle controller
public static string throttle_node = "1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1";
// ---- Three level throttling controller
// # of sampling periods for each applications test.
public static int apps_test_freq=1;
public static double sampling_period_freq=10;
public static double sensitivity_threshold=0.05;
// apps with high mpki that exceeds cluster threshold will be always throttled
public static bool use_cluster_threshold=true;
public static bool use_ipc_delta=false;
// ---- Three level throttling controller
// NETGAIN
public static bool use_absolute=true;
public static double ipc_hurt_co=1;
public static bool gain_hurt_rr_only=false;
public static bool ipc_hurt_neg_only=false;
// ---- SIGCOMM'11
//
public static int workload_number = 0;
public static string lambdas = "";
public static string misses = "";
public static bool simplemap_mem = false;
public static int simple_MC_think = 200;
//public static ControllerType controller = ControllerType.NEIGHBOR_LOCAL; // This is for RC or HR locality
//public static ControllerType controller = ControllerType.SIMPLEMAP; // This is for mesh locality(Bless, Chipper, buffered)
public static ControllerType controller = ControllerType.NONE;
public static string controller_mix = "";
// STC:
// Every 'reprioritizePeriod', counters are calculated for each app as
// numerator/denom, factoring into past values based on historyWeight,
// packets are then put into bins for injection and routing decisions
public static double STC_history = 0;
public static ulong STC_period = 300000;
public static BinningMethod STC_binMethod = BinningMethod.KMEANS;
public static int STC_binCount = 8;
public static ulong STC_batchPeriod = 16000;
public static ulong STC_batchCount = 8;
// throttling:
// params for HotNets
public static int throttle_epoch = 1000;
public static int throttle_averaging_window = 128;
// also throt_min, throt_max, throt_scale, congested_alpha, congested_beta, congested_gamma below
// simple mapping (distribution):
public static double simplemap_lambda = 2.0;
public static int bounded_locality = -1;
public static int neighborhood_locality = -1;
public static int overlapping_squares = -1;
// ----
public static bool histogram_bins = true;
public static int barrier = 1;
// ---- ISCA'11
public static int ideal_router_width = 8;
public static int ideal_router_length = 4;
// ---
public static bool bochs_fe = false;
// ---- synth traces
public static double synth_reads_fraction = 0.8;
public static double synth_rate = 0.1;
public static bool bSynthBitComplement = false;
public static bool bSynthTranspose = false;
public static bool bSynthHotspot = false;
public static bool randomHotspot = false;
// ----
// ---- sampling methodology
public static int rand_seed = 0; // controlled seed for deterministic runs
public static ulong randomize_trace = 0; // range of starting counts (in insns)
public static int warmup_cyc = 0;
public static bool trace_wraparound = false;
public static ulong insns = 1000000000000; // insns for which stats are collected on each CPU
// for Weighted Speedup
public static string readlog = ""; // retire-time annotation log (one per trace, space-separated)
public static string writelog = ""; // name of single annotation log to write
public static int writelog_node = -1; // node from which to take annotation log
public static string logpath = "."; // path in which to find annotation logs
public static int writelog_delta = 100; // instruction delta at which to write retire-time annotations
// ----
// ---- golden packet / injection token
public static bool calf_new_inj_ej = false;
public static int gp_levels = 1;
public static double gp_epoch = 1.0;
public static int gp_rescuers = 0;
public static bool gp_rescuers_dummy = false;
public static bool gp_adaptive = false;
public static bool dor_only = false; // dimension-ordered routing only
public static bool edge_loop = false;
public static bool torus = false;
public static bool sortnet_twist = true;
public static bool sortnet_full = false;
// ----
// ---- promises
public static bool promise_wb_only = false;
public static bool coherence_noPromises = false; // promises not used; writebacks bypass NoC
// ----
// ---- new cache architecture
public static bool simple_nocoher = false; // simple no-coherence, no-memory (low overhead) model?
public static int cache_block = 5; // cache block size is universal
public static int coherent_cache_size = 14; // power of two
public static int coherent_cache_assoc = 2; // power of two
public static bool sh_cache = true; // have a shared cache layer?
public static int sh_cache_size = 18; // power of two: per slice
public static int sh_cache_assoc = 4; // power of two
public static bool sh_cache_perfect = true; // perfect shared cache?
public static int shcache_buf = 16; // reassembly buffer slots per shared cache slice
public static int shcache_lat = 15; // cycles
public static int cohcache_lat = 2; // cycles
public static int cacheop_lat = 1; // cycles -- passthrough lat for in-progress operations
// ----
// ---- CAL paper (true bufferless)
public static int cheap_of = 1; // oldest-first age divisor
public static int cheap_of_cap = -1; // if not -1, livelock limit at which we flush
public static bool naive_rx_buf = false;
public static bool naive_rx_buf_evict = false;
public static RxBufMode rxbuf_mode = RxBufMode.NONE;
public static int rxbuf_size = 8;
public static bool split_queues = true; // for validation with orig sim
public static int mshrs = 16;
public static bool rxbuf_cache_only = true;
public static bool ctrl_data_split = false;
public static bool ignore_livelock = true;
public static ulong livelock_thresh = 1000000;
// ----
// ---- SIGCOMM'10 paper (starvation congestion-control)
public static bool starve_control = false;
public static bool speriod_control = false;
public static bool net_age_arbitration = false;
public static bool tier1_disabled = false;
public static bool tier2_disabled = true;
public static bool tier3_disabled = false;
public static double srate_thresh = 0.45;
public static int srate_win = 1000;
public static bool srate_log = false;
public static bool starve_log = false;
public static bool netu_log = false;
public static bool nthrot_log = false;
public static int interleave_bits = 0;
public static bool valiant = false;
public static bool stnetu_log = false;
public static bool irate_log = false;
public static bool qlen_log = false;
public static bool aqlen_log = false;
public static bool sstate_log = false;
public static double static_throttle = 0.0;
public static bool starvehigh_new = true;
public static bool throt_ideal = false;
public static bool throt_starvee = false;
public static bool throt_stree = false;
public static int throt_stree_t = 0;
public static bool starvee_distributed = false;
public static bool ttime_log = false;
public static bool tier1_prob = true;
public static bool biasing_inject = false;
public static bool sources_log = false;
public static bool nbutil_log = false;
public static double bias_prob = 0.333;
public static bool bias_single = true;
public static string socket = "";
public static bool idealnet = false;
public static int ideallat = 10;
public static int idealcap = 16;
public static bool idealrr = false;
public static double throt_rate = 0.75;
public static double congested_alpha = 0.35;
public static double congested_omega = 15;
public static double congested_max = 0.9;
public static double throt_min = 0.45;
public static double throt_max = 0.75;
public static double throt_scale = 10;
public static double avg_scale = 1;
public static bool always_obey_tier3 = true;
public static bool use_qlen = true;
public static int l1count_Q = 100000;
// ----
// ---- SCARAB impl
public static int nack_linkLatency = 2;
public static int nack_nr = 16;
public static bool address_is_node = false;
public static bool opp_buffering = false;
public static bool nack_epoch = false;
// ----
public static bool progress = true;
public static string output = "output.txt";
public static string matlab = "";
public static string fairdata = "";
public static int simulationDuration = 1000;
public static bool stopOnEnd = false;
public static int network_nrX = 2;
public static int network_nrY = 2;
public static bool randomize_defl = true;
public static int network_loopback = -1;
public static int network_quantum = -1;
public static int entropy_quantum = 1000; // in cycles
// 741: BLESS-CC Congestion Avoidance Variables
public static int BLESSCC_DeflectionAvgRounds = 10;
public static double BLESSCC_DeflectionThreshold = 35.0;
// 741: BLESS-CC variables for distinguishing congestion from hot-spots
public static int BLESSCC_BitsForCongestion = 3;
public static double BLESSCC_CongestionDecrease = 0.1;
public static double BLESSCC_CongestionIncrease = 0.01;
public static int BLESSCC_MinimumRoundsBetween = 5;
// 741: BLESS-CC Valiant routing variables
public static int BLESSCC_ValiantRounds = 50;
public static int BLESSCC_ValiantProcessors = 4;
// 741: BLESS-CC Fairness variables
public static int BLESSCC_RateHistoryRounds = 20;
public static int BLESSCC_RateHistorySources = 1;
public static bool BLESSCC_FairnessInputOnly = false;
// 741: Link monitoring variables to prevent starvation
public static int BLESSCC_StarvationRounds = 1000;
// ------ CIF: experiment parameters, new version -----------------
public static string sources = "all uniformRandom";
public static string finish = "cycle 10000000";
public static string solo = "";
public static int N
{ get { return network_nrX * network_nrY; } }
//TODO: CATEGORIZE
public static string[] traceFilenames;
public static string TraceDirs = ""; ///<summary> Comma delimited list of dirs potentially containing traces </summary>
public static bool PerfectLastLevelCache = false;
public static bool RouterEvaluation = false;
public static ulong RouterEvaluationIterations = 1;
// Adaptive Routing
public static bool RandOrderRouting = false;
public static bool DeflectOrderRouting = false;
// Topology
public static bool RingClustered = false;
public static bool QuadParityPartition = false;
public static bool TorusSingleRing = false;
public static bool SourceBiasedInjection = false;
public static bool InverseBiasedInjection = false;
public static bool AgressiveInjection = false;
//Scalable RingClustered
public static bool ScalableRingClustered = false;
public static bool RC_mesh = true;
public static bool RC_Torus = false;
public static bool RC_x_Torus = false;
public static bool AllBiDirLink = false;
//Hierarchical Ring
public static bool HR_NoBias = false;
public static bool HR_SimpleBias = false; // flits get on the global ring only when the path it's taking is short. No bias at injection
public static bool HR_NoBuffer = false;
public static int G2LBufferDepth = 4;
public static int L2GBufferDepth = 1;
public static bool SingleDirRing = false;
public static Topology topology = Topology.Mesh;
public static int observerThreshold = 4;
public static bool NoPreference = false;
public static bool forcePreference = false;
public static bool simpleLivelock = false;
public static int starveThreshold = 1000;
public static int starveDelay = 10;
// Place holder number
public static int PlaceHolderNum = 0;
public static int meshEjectTrial = 1;
public static int RingEjectTrial = -1;
public static int RingInjectTrial = 1;
public static int EjectBufferSize = -1;
public static bool InfEjectBuffer = false;
public static int GlobalRingWidth = 2;
// Buffered Hierarchical ring
public static bool bBufferedRing = false;
public static int ringBufferSize = 4;
public static int HRBufferDepth = 4;
public void read(string[] args)
{
string[] traceArgs = null;
int traceArgOffset = 0;
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-workload")
{
string worksetFile = args[i + 1];
int index = int.Parse(args[i + 2]);
workload_number = index;
if (!File.Exists(args[i + 1]))
throw new Exception("Could not locate workset file " + worksetFile);
string[] lines = File.ReadAllLines(worksetFile);
if (TraceDirs == "")
TraceDirs = lines[0];
traceArgs = lines[index].Split();
traceArgOffset = 0;
i += 2;
}
else if (args[i] == "-traces")
{
traceArgs = args;
traceArgOffset = i + 1;
break;
}
else
{
setSystemParameter(args[i].Substring(1), args[i + 1]);
i++;
}
}
traceFilenames = new string[N];
if (traceArgs.Length - traceArgOffset < N)
throw new Exception(
String.Format("Not enough trace files given (got {0}, wanted {1})", traceArgs.Length - traceArgOffset, N));
for (int a = 0; a < N; a++)
{
traceFilenames[a] = traceArgs[traceArgOffset + a];
}
Simulator.stats = new Stats(Config.N);
finalize();
proc.finalize();
memory.finalize();
router.finalize();
}
public void readConfig(string filename)
{
Char[] delims = new Char[] { '=' }; //took out ' ' for better listing capabilities
StreamReader configReader = File.OpenText(filename);
if (configReader == null)
return;
string buf;
for (; ; )
{
buf = configReader.ReadLine();
if (buf == null)
break;
int comment = buf.IndexOf("//");
if (comment != -1)
buf = buf.Remove(comment).Trim();
if (buf == "")
continue;
string[] flags = buf.Split(delims, 2);
if (flags.Length < 2) continue;
setSystemParameter(flags[0].Trim(), flags[1].Trim());
}
}
public void setSystemParameter(string param, string val)
{
Console.WriteLine("{0} <= {1}", param, val);
if (param.Contains("."))
{
string name = param.Substring(0, param.IndexOf('.'));
string subparam = param.Substring(param.IndexOf('.') + 1);
FieldInfo fi = GetType().GetField(name);
if (!(fi.GetValue(this) is ConfigGroup))
{
throw new Exception(String.Format("Non-ConfigGroup indexed, of type {0}", fi.FieldType.ToString()));
}
((ConfigGroup)fi.GetValue(this)).setParameter(subparam, val);
}
else
setParameter(param, val);
}
protected override bool setSpecialParameter(string param, string val)
{
switch (param)
{
case "config":
readConfig(val); break;
default:
return false;
}
return true;
}
public static string ConfigHash()
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 =
new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] checksum = md5.ComputeHash(new System.Text.ASCIIEncoding().GetBytes(
Config.sources +
Config.router.algorithm +
Config.router.options +
Config.network_nrX + Config.network_nrY));
return BitConverter.ToString(checksum).Replace("-", "");
}
public override void finalize()
{
if (output == "" && matlab == "")
{
throw new Exception("No output specified.");
}
if (STC_binCount == 0)
STC_binCount = N;
}
}
}
| |
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Citrina
{
public class Account : IAccount
{
public Task<ApiRequest<bool?>> BanApi(int? ownerId = null)
{
var request = new Dictionary<string, string>
{
["owner_id"] = ownerId?.ToString(),
};
return RequestManager.CreateRequestAsync<bool?>("account.ban", null, request);
}
/// <summary>
/// Changes a user password after access is successfully restored with the [vk.com/dev/auth.restore|auth.restore] method.
/// </summary>
public Task<ApiRequest<AccountChangePasswordResponse>> ChangePasswordApi(string restoreSid = null, string changePasswordHash = null, string oldPassword = null, string newPassword = null)
{
var request = new Dictionary<string, string>
{
["restore_sid"] = restoreSid,
["change_password_hash"] = changePasswordHash,
["old_password"] = oldPassword,
["new_password"] = newPassword,
};
return RequestManager.CreateRequestAsync<AccountChangePasswordResponse>("account.changePassword", null, request);
}
/// <summary>
/// Returns a list of active ads (offers) which executed by the user will bring him/her respective number of votes to his balance in the application.
/// </summary>
public Task<ApiRequest<AccountGetActiveOffersResponse>> GetActiveOffersApi(int? offset = null, int? count = null)
{
var request = new Dictionary<string, string>
{
["offset"] = offset?.ToString(),
["count"] = count?.ToString(),
};
return RequestManager.CreateRequestAsync<AccountGetActiveOffersResponse>("account.getActiveOffers", null, request);
}
/// <summary>
/// Gets settings of the user in this application.
/// </summary>
public Task<ApiRequest<int?>> GetAppPermissionsApi(int? userId = null)
{
var request = new Dictionary<string, string>
{
["user_id"] = userId?.ToString(),
};
return RequestManager.CreateRequestAsync<int?>("account.getAppPermissions", null, request);
}
/// <summary>
/// Returns a user's blacklist.
/// </summary>
public Task<ApiRequest<AccountGetBannedResponse>> GetBannedApi(int? offset = null, int? count = null)
{
var request = new Dictionary<string, string>
{
["offset"] = offset?.ToString(),
["count"] = count?.ToString(),
};
return RequestManager.CreateRequestAsync<AccountGetBannedResponse>("account.getBanned", null, request);
}
/// <summary>
/// Returns non-null values of user counters.
/// </summary>
public Task<ApiRequest<AccountAccountCounters>> GetCountersApi(IEnumerable<string> filter = null)
{
var request = new Dictionary<string, string>
{
["filter"] = RequestHelpers.ParseEnumerable(filter),
};
return RequestManager.CreateRequestAsync<AccountAccountCounters>("account.getCounters", null, request);
}
/// <summary>
/// Returns current account info.
/// </summary>
public Task<ApiRequest<AccountInfo>> GetInfoApi(IEnumerable<string> fields = null)
{
var request = new Dictionary<string, string>
{
["fields"] = RequestHelpers.ParseEnumerable(fields),
};
return RequestManager.CreateRequestAsync<AccountInfo>("account.getInfo", null, request);
}
/// <summary>
/// Returns the current account info.
/// </summary>
public Task<ApiRequest<AccountUserSettings>> GetProfileInfoApi()
{
var request = new Dictionary<string, string>
{
};
return RequestManager.CreateRequestAsync<AccountUserSettings>("account.getProfileInfo", null, request);
}
/// <summary>
/// Gets settings of push notifications.
/// </summary>
public Task<ApiRequest<AccountPushSettings>> GetPushSettingsApi(string deviceId = null)
{
var request = new Dictionary<string, string>
{
["device_id"] = deviceId,
};
return RequestManager.CreateRequestAsync<AccountPushSettings>("account.getPushSettings", null, request);
}
/// <summary>
/// Subscribes an iOS/Android/Windows Phone-based device to receive push notifications.
/// </summary>
public Task<ApiRequest<bool?>> RegisterDeviceApi(string token = null, string deviceModel = null, int? deviceYear = null, string deviceId = null, string systemVersion = null, string settings = null, bool? sandbox = null)
{
var request = new Dictionary<string, string>
{
["token"] = token,
["device_model"] = deviceModel,
["device_year"] = deviceYear?.ToString(),
["device_id"] = deviceId,
["system_version"] = systemVersion,
["settings"] = settings,
["sandbox"] = RequestHelpers.ParseBoolean(sandbox),
};
return RequestManager.CreateRequestAsync<bool?>("account.registerDevice", null, request);
}
/// <summary>
/// Edits current profile info.
/// </summary>
public Task<ApiRequest<AccountSaveProfileInfoResponse>> SaveProfileInfoApi(string firstName = null, string lastName = null, string maidenName = null, string screenName = null, int? cancelRequestId = null, int? sex = null, int? relation = null, int? relationPartnerId = null, string bdate = null, int? bdateVisibility = null, string homeTown = null, int? countryId = null, int? cityId = null, string status = null)
{
var request = new Dictionary<string, string>
{
["first_name"] = firstName,
["last_name"] = lastName,
["maiden_name"] = maidenName,
["screen_name"] = screenName,
["cancel_request_id"] = cancelRequestId?.ToString(),
["sex"] = sex?.ToString(),
["relation"] = relation?.ToString(),
["relation_partner_id"] = relationPartnerId?.ToString(),
["bdate"] = bdate,
["bdate_visibility"] = bdateVisibility?.ToString(),
["home_town"] = homeTown,
["country_id"] = countryId?.ToString(),
["city_id"] = cityId?.ToString(),
["status"] = status,
};
return RequestManager.CreateRequestAsync<AccountSaveProfileInfoResponse>("account.saveProfileInfo", null, request);
}
/// <summary>
/// Allows to edit the current account info.
/// </summary>
public Task<ApiRequest<bool?>> SetInfoApi(string name = null, string value = null)
{
var request = new Dictionary<string, string>
{
["name"] = name,
["value"] = value,
};
return RequestManager.CreateRequestAsync<bool?>("account.setInfo", null, request);
}
/// <summary>
/// Sets an application screen name (up to 17 characters), that is shown to the user in the left menu.
/// </summary>
public Task<ApiRequest<bool?>> SetNameInMenuApi(int? userId = null, string name = null)
{
var request = new Dictionary<string, string>
{
["user_id"] = userId?.ToString(),
["name"] = name,
};
return RequestManager.CreateRequestAsync<bool?>("account.setNameInMenu", null, request);
}
/// <summary>
/// Marks a current user as offline.
/// </summary>
public Task<ApiRequest<bool?>> SetOfflineApi()
{
var request = new Dictionary<string, string>
{
};
return RequestManager.CreateRequestAsync<bool?>("account.setOffline", null, request);
}
/// <summary>
/// Marks the current user as online for 15 minutes.
/// </summary>
public Task<ApiRequest<bool?>> SetOnlineApi(bool? voip = null)
{
var request = new Dictionary<string, string>
{
["voip"] = RequestHelpers.ParseBoolean(voip),
};
return RequestManager.CreateRequestAsync<bool?>("account.setOnline", null, request);
}
/// <summary>
/// Change push settings.
/// </summary>
public Task<ApiRequest<bool?>> SetPushSettingsApi(string deviceId = null, string settings = null, string key = null, IEnumerable<string> value = null)
{
var request = new Dictionary<string, string>
{
["device_id"] = deviceId,
["settings"] = settings,
["key"] = key,
["value"] = RequestHelpers.ParseEnumerable(value),
};
return RequestManager.CreateRequestAsync<bool?>("account.setPushSettings", null, request);
}
/// <summary>
/// Mutes push notifications for the set period of time.
/// </summary>
public Task<ApiRequest<bool?>> SetSilenceModeApi(string deviceId = null, int? time = null, int? peerId = null, int? sound = null)
{
var request = new Dictionary<string, string>
{
["device_id"] = deviceId,
["time"] = time?.ToString(),
["peer_id"] = peerId?.ToString(),
["sound"] = sound?.ToString(),
};
return RequestManager.CreateRequestAsync<bool?>("account.setSilenceMode", null, request);
}
public Task<ApiRequest<bool?>> UnbanApi(int? ownerId = null)
{
var request = new Dictionary<string, string>
{
["owner_id"] = ownerId?.ToString(),
};
return RequestManager.CreateRequestAsync<bool?>("account.unban", null, request);
}
/// <summary>
/// Unsubscribes a device from push notifications.
/// </summary>
public Task<ApiRequest<bool?>> UnregisterDeviceApi(string deviceId = null, bool? sandbox = null)
{
var request = new Dictionary<string, string>
{
["device_id"] = deviceId,
["sandbox"] = RequestHelpers.ParseBoolean(sandbox),
};
return RequestManager.CreateRequestAsync<bool?>("account.unregisterDevice", null, request);
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
namespace NLog.UnitTests.Targets
{
using System;
using System.IO;
using NLog.Targets;
using System.Collections.Generic;
using Xunit;
using System.Threading.Tasks;
public class ConsoleTargetTests : NLogTestBase
{
[Fact]
public void ConsoleOutWriteLineTest()
{
ConsoleOutTest(false);
}
[Fact]
public void ConsoleOutWriteBufferTest()
{
ConsoleOutTest(true);
}
private void ConsoleOutTest(bool writeBuffer)
{
var target = new ConsoleTarget()
{
Header = "-- header --",
Layout = "${logger} ${message}",
Footer = "-- footer --",
WriteBuffer = writeBuffer,
};
var consoleOutWriter = new StringWriter();
TextWriter oldConsoleOutWriter = Console.Out;
Console.SetOut(consoleOutWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add));
Assert.Equal(6, exceptions.Count);
target.Flush((ex) => { });
target.Close();
}
finally
{
Console.SetOut(oldConsoleOutWriter);
}
var actual = consoleOutWriter.ToString();
Assert.True(actual.IndexOf("-- header --") != -1);
Assert.True(actual.IndexOf("Logger1 message1") != -1);
Assert.True(actual.IndexOf("Logger1 message2") != -1);
Assert.True(actual.IndexOf("Logger1 message3") != -1);
Assert.True(actual.IndexOf("Logger2 message4") != -1);
Assert.True(actual.IndexOf("Logger2 message5") != -1);
Assert.True(actual.IndexOf("Logger1 message6") != -1);
Assert.True(actual.IndexOf("-- footer --") != -1);
}
[Fact]
public void ConsoleErrorTest()
{
var target = new ConsoleTarget()
{
Header = "-- header --",
Layout = "${logger} ${message}",
Footer = "-- footer --",
Error = true,
};
var consoleErrorWriter = new StringWriter();
TextWriter oldConsoleErrorWriter = Console.Error;
Console.SetError(consoleErrorWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvents(
new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add),
new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add));
Assert.Equal(6, exceptions.Count);
target.Flush((ex) => { });
target.Close();
}
finally
{
Console.SetError(oldConsoleErrorWriter);
}
string expectedResult = string.Format("-- header --{0}Logger1 message1{0}Logger1 message2{0}Logger1 message3{0}Logger2 message4{0}Logger2 message5{0}Logger1 message6{0}-- footer --{0}", Environment.NewLine);
Assert.Equal(expectedResult, consoleErrorWriter.ToString());
}
#if !MONO
[Fact]
public void ConsoleEncodingTest()
{
var consoleOutputEncoding = Console.OutputEncoding;
var target = new ConsoleTarget()
{
Header = "-- header --",
Layout = "${logger} ${message}",
Footer = "-- footer --",
Encoding = System.Text.Encoding.UTF8
};
Assert.Equal(System.Text.Encoding.UTF8, target.Encoding);
var consoleOutWriter = new StringWriter();
TextWriter oldConsoleOutWriter = Console.Out;
Console.SetOut(consoleOutWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
// Not really testing whether Console.OutputEncoding works, but just that it is configured without breaking ConsoleTarget
Assert.Equal(System.Text.Encoding.UTF8, Console.OutputEncoding);
Assert.Equal(System.Text.Encoding.UTF8, target.Encoding);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add));
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add));
Assert.Equal(2, exceptions.Count);
target.Encoding = consoleOutputEncoding;
Assert.Equal(consoleOutputEncoding, Console.OutputEncoding);
target.Close();
}
finally
{
Console.OutputEncoding = consoleOutputEncoding;
Console.SetOut(oldConsoleOutWriter);
}
string expectedResult = string.Format("-- header --{0}Logger1 message1{0}Logger1 message2{0}-- footer --{0}", Environment.NewLine);
Assert.Equal(expectedResult, consoleOutWriter.ToString());
}
#endif
#if !NET3_5 && !MONO
[Fact]
public void ConsoleRaceCondtionIgnoreTest()
{
var configXml = @"
<nlog throwExceptions='true'>
<targets>
<target name='console' type='console' layout='${message}' />
<target name='consoleError' type='console' layout='${message}' error='true' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='console,consoleError' />
</rules>
</nlog>";
ConsoleRaceCondtionIgnoreInnerTest(configXml);
}
internal static void ConsoleRaceCondtionIgnoreInnerTest(string configXml)
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml);
// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug.
// See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written
// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service
//
// Full error:
// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory.
// The I/ O package is not thread safe by default.In multithreaded applications,
// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or
// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader.
var oldOut = Console.Out;
var oldError = Console.Error;
try
{
Console.SetOut(StreamWriter.Null);
Console.SetError(StreamWriter.Null);
LogManager.ThrowExceptions = true;
var logger = LogManager.GetCurrentClassLogger();
Parallel.For(0, 10, new ParallelOptions() { MaxDegreeOfParallelism = 10 }, (_) =>
{
for (int i = 0; i < 100; i++)
{
logger.Trace("test message to the out and error stream");
}
});
}
finally
{
Console.SetOut(oldOut);
Console.SetError(oldError);
}
}
#endif
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.PhysicsModules.SharedBase;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
{
/// <summary>
/// The possible states that an agent can be in when its being transferred between regions.
/// </summary>
/// <remarks>
/// This is a state machine.
///
/// [Entry] => Preparing
/// Preparing => { Transferring || Cancelling || CleaningUp || Aborting || [Exit] }
/// Transferring => { ReceivedAtDestination || Cancelling || CleaningUp || Aborting }
/// Cancelling => CleaningUp || Aborting
/// ReceivedAtDestination => CleaningUp || Aborting
/// CleaningUp => [Exit]
/// Aborting => [Exit]
///
/// In other words, agents normally travel throwing Preparing => Transferring => ReceivedAtDestination => CleaningUp
/// However, any state can transition to CleaningUp if the teleport has failed.
/// </remarks>
enum AgentTransferState
{
Preparing, // The agent is being prepared for transfer
Transferring, // The agent is in the process of being transferred to a destination
ReceivedAtDestination, // The destination has notified us that the agent has been successfully received
CleaningUp, // The agent is being changed to child/removed after a transfer
Cancelling, // The user has cancelled the teleport but we have yet to act upon this.
Aborting // The transfer is aborting. Unlike Cancelling, no compensating actions should be performed
}
/// <summary>
/// Records the state of entities when they are in transfer within or between regions (cross or teleport).
/// </summary>
public class EntityTransferStateMachine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[ENTITY TRANSFER STATE MACHINE]";
/// <summary>
/// If true then on a teleport, the source region waits for a callback from the destination region. If
/// a callback fails to arrive within a set time then the user is pulled back into the source region.
/// </summary>
public bool EnableWaitForAgentArrivedAtDestination { get; set; }
private EntityTransferModule m_mod;
private Dictionary<UUID, AgentTransferState> m_agentsInTransit = new Dictionary<UUID, AgentTransferState>();
public EntityTransferStateMachine(EntityTransferModule module)
{
m_mod = module;
}
/// <summary>
/// Set that an agent is in transit.
/// </summary>
/// <param name='id'>The ID of the agent being teleported</param>
/// <returns>true if the agent was not already in transit, false if it was</returns>
internal bool SetInTransit(UUID id)
{
// m_log.DebugFormat("{0} SetInTransit. agent={1}, newState=Preparing", LogHeader, id);
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.ContainsKey(id))
{
m_agentsInTransit[id] = AgentTransferState.Preparing;
return true;
}
}
return false;
}
/// <summary>
/// Updates the state of an agent that is already in transit.
/// </summary>
/// <param name='id'></param>
/// <param name='newState'></param>
/// <returns></returns>
/// <exception cref='Exception'>Illegal transitions will throw an Exception</exception>
internal bool UpdateInTransit(UUID id, AgentTransferState newState)
{
// m_log.DebugFormat("{0} UpdateInTransit. agent={1}, newState={2}", LogHeader, id, newState);
bool transitionOkay = false;
// We don't want to throw an exception on cancel since this can come it at any time.
bool failIfNotOkay = true;
// Should be a failure message if failure is not okay.
string failureMessage = null;
AgentTransferState? oldState = null;
lock (m_agentsInTransit)
{
// Illegal to try and update an agent that's not actually in transit.
if (!m_agentsInTransit.ContainsKey(id))
{
if (newState != AgentTransferState.Cancelling && newState != AgentTransferState.Aborting)
failureMessage = string.Format(
"Agent with ID {0} is not registered as in transit in {1}",
id, m_mod.Scene.RegionInfo.RegionName);
else
failIfNotOkay = false;
}
else
{
oldState = m_agentsInTransit[id];
if (newState == AgentTransferState.Aborting)
{
transitionOkay = true;
}
else if (newState == AgentTransferState.CleaningUp && oldState != AgentTransferState.CleaningUp)
{
transitionOkay = true;
}
else if (newState == AgentTransferState.Transferring && oldState == AgentTransferState.Preparing)
{
transitionOkay = true;
}
else if (newState == AgentTransferState.ReceivedAtDestination && oldState == AgentTransferState.Transferring)
{
transitionOkay = true;
}
else
{
if (newState == AgentTransferState.Cancelling
&& (oldState == AgentTransferState.Preparing || oldState == AgentTransferState.Transferring))
{
transitionOkay = true;
}
else
{
failIfNotOkay = false;
}
}
if (!transitionOkay)
failureMessage
= string.Format(
"Agent with ID {0} is not allowed to move from old transit state {1} to new state {2} in {3}",
id, oldState, newState, m_mod.Scene.RegionInfo.RegionName);
}
if (transitionOkay)
{
m_agentsInTransit[id] = newState;
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Changed agent with id {0} from state {1} to {2} in {3}",
// id, oldState, newState, m_mod.Scene.Name);
}
else if (failIfNotOkay)
{
m_log.DebugFormat("{0} UpdateInTransit. Throwing transition failure = {1}", LogHeader, failureMessage);
throw new Exception(failureMessage);
}
// else
// {
// if (oldState != null)
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Ignored change of agent with id {0} from state {1} to {2} in {3}",
// id, oldState, newState, m_mod.Scene.Name);
// else
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Ignored change of agent with id {0} to state {1} in {2} since agent not in transit",
// id, newState, m_mod.Scene.Name);
// }
}
return transitionOkay;
}
/// <summary>
/// Gets the current agent transfer state.
/// </summary>
/// <returns>Null if the agent is not in transit</returns>
/// <param name='id'>
/// Identifier.
/// </param>
internal AgentTransferState? GetAgentTransferState(UUID id)
{
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.ContainsKey(id))
return null;
else
return m_agentsInTransit[id];
}
}
/// <summary>
/// Removes an agent from the transit state machine.
/// </summary>
/// <param name='id'></param>
/// <returns>true if the agent was flagged as being teleported when this method was called, false otherwise</returns>
internal bool ResetFromTransit(UUID id)
{
lock (m_agentsInTransit)
{
if (m_agentsInTransit.ContainsKey(id))
{
AgentTransferState state = m_agentsInTransit[id];
// if (state == AgentTransferState.Transferring || state == AgentTransferState.ReceivedAtDestination)
// {
// FIXME: For now, we allow exit from any state since a thrown exception in teleport is now guranteed
// to be handled properly - ResetFromTransit() could be invoked at any step along the process
// m_log.WarnFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Agent with ID {0} should not exit directly from state {1}, should go to {2} state first in {3}",
// id, state, AgentTransferState.CleaningUp, m_mod.Scene.RegionInfo.RegionName);
// throw new Exception(
// "Agent with ID {0} cannot exit directly from state {1}, it must go to {2} state first",
// state, AgentTransferState.CleaningUp);
// }
m_agentsInTransit.Remove(id);
// m_log.DebugFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Agent {0} cleared from transit in {1}",
// id, m_mod.Scene.RegionInfo.RegionName);
return true;
}
}
// m_log.WarnFormat(
// "[ENTITY TRANSFER STATE MACHINE]: Agent {0} requested to clear from transit in {1} but was already cleared",
// id, m_mod.Scene.RegionInfo.RegionName);
return false;
}
internal bool WaitForAgentArrivedAtDestination(UUID id)
{
if (!m_mod.WaitForAgentArrivedAtDestination)
return true;
lock (m_agentsInTransit)
{
AgentTransferState? currentState = GetAgentTransferState(id);
if (currentState == null)
throw new Exception(
string.Format(
"Asked to wait for destination callback for agent with ID {0} in {1} but agent is not in transit",
id, m_mod.Scene.RegionInfo.RegionName));
if (currentState != AgentTransferState.Transferring && currentState != AgentTransferState.ReceivedAtDestination)
throw new Exception(
string.Format(
"Asked to wait for destination callback for agent with ID {0} in {1} but agent is in state {2}",
id, m_mod.Scene.RegionInfo.RegionName, currentState));
}
int count = 400;
// There should be no race condition here since no other code should be removing the agent transfer or
// changing the state to another other than Transferring => ReceivedAtDestination.
while (count-- > 0)
{
lock (m_agentsInTransit)
{
if (m_agentsInTransit[id] == AgentTransferState.ReceivedAtDestination)
break;
}
// m_log.Debug(" >>> Waiting... " + count);
Thread.Sleep(100);
}
return count > 0;
}
internal void SetAgentArrivedAtDestination(UUID id)
{
lock (m_agentsInTransit)
{
if (!m_agentsInTransit.ContainsKey(id))
{
m_log.WarnFormat(
"[ENTITY TRANSFER STATE MACHINE]: Region {0} received notification of arrival in destination of agent {1} but no teleport request is active",
m_mod.Scene.RegionInfo.RegionName, id);
return;
}
AgentTransferState currentState = m_agentsInTransit[id];
if (currentState == AgentTransferState.ReceivedAtDestination)
{
// An anomoly but don't make this an outright failure - destination region could be overzealous in sending notification.
m_log.WarnFormat(
"[ENTITY TRANSFER STATE MACHINE]: Region {0} received notification of arrival in destination of agent {1} but notification has already previously been received",
m_mod.Scene.RegionInfo.RegionName, id);
}
else if (currentState != AgentTransferState.Transferring)
{
m_log.ErrorFormat(
"[ENTITY TRANSFER STATE MACHINE]: Region {0} received notification of arrival in destination of agent {1} but agent is in state {2}",
m_mod.Scene.RegionInfo.RegionName, id, currentState);
return;
}
m_agentsInTransit[id] = AgentTransferState.ReceivedAtDestination;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// StrongNameIdentityPermission.cs
//
// <OWNER>[....]</OWNER>
//
namespace System.Security.Permissions
{
using System;
#if FEATURE_CAS_POLICY
using SecurityElement = System.Security.SecurityElement;
#endif // FEATURE_CAS_POLICY
using System.Security.Util;
using System.IO;
using String = System.String;
using Version = System.Version;
using System.Security.Policy;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
// The only difference between this class and System.Security.Policy.StrongName is that this one
// allows m_name to be null. We should merge this class with System.Security.Policy.StrongName
[Serializable]
sealed internal class StrongName2
{
public StrongNamePublicKeyBlob m_publicKeyBlob;
public String m_name;
public Version m_version;
public StrongName2(StrongNamePublicKeyBlob publicKeyBlob, String name, Version version)
{
m_publicKeyBlob = publicKeyBlob;
m_name = name;
m_version = version;
}
public StrongName2 Copy()
{
return new StrongName2(m_publicKeyBlob, m_name, m_version);
}
public bool IsSubsetOf(StrongName2 target)
{
// This StrongName2 is a subset of the target if it's public key blob is null no matter what
if (this.m_publicKeyBlob == null)
return true;
// Subsets are always false if the public key blobs do not match
if (!this.m_publicKeyBlob.Equals( target.m_publicKeyBlob ))
return false;
// We use null in strings to represent the "Anything" state.
// Therefore, the logic to detect an individual subset is:
//
// 1. If the this string is null ("Anything" is a subset of any other).
// 2. If the this string and target string are the same (equality is sufficient for a subset).
//
// The logic is reversed here to discover things that are not subsets.
if (this.m_name != null)
{
if (target.m_name == null || !System.Security.Policy.StrongName.CompareNames( target.m_name, this.m_name ))
return false;
}
if ((Object) this.m_version != null)
{
if ((Object) target.m_version == null ||
target.m_version.CompareTo( this.m_version ) != 0)
{
return false;
}
}
return true;
}
public StrongName2 Intersect(StrongName2 target)
{
if (target.IsSubsetOf( this ))
return target.Copy();
else if (this.IsSubsetOf( target ))
return this.Copy();
else
return null;
}
public bool Equals(StrongName2 target)
{
if (!target.IsSubsetOf(this))
return false;
if (!this.IsSubsetOf(target))
return false;
return true;
}
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class StrongNameIdentityPermission : CodeAccessPermission, IBuiltInPermission
{
//------------------------------------------------------
//
// PRIVATE STATE DATA
//
//------------------------------------------------------
private bool m_unrestricted;
private StrongName2[] m_strongNames;
//------------------------------------------------------
//
// PUBLIC CONSTRUCTORS
//
//------------------------------------------------------
public StrongNameIdentityPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
m_unrestricted = true;
}
else if (state == PermissionState.None)
{
m_unrestricted = false;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
public StrongNameIdentityPermission( StrongNamePublicKeyBlob blob, String name, Version version )
{
if (blob == null)
throw new ArgumentNullException( "blob" );
if (name != null && name.Equals( "" ))
throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) );
Contract.EndContractBlock();
m_unrestricted = false;
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(blob, name, version);
}
//------------------------------------------------------
//
// PUBLIC ACCESSOR METHODS
//
//------------------------------------------------------
public StrongNamePublicKeyBlob PublicKey
{
set
{
if (value == null)
throw new ArgumentNullException( "PublicKey" );
Contract.EndContractBlock();
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
m_strongNames[0].m_publicKeyBlob = value;
else
{
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(value, "", new Version());
}
}
get
{
if(m_strongNames == null || m_strongNames.Length == 0)
return null;
if(m_strongNames.Length > 1)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
return m_strongNames[0].m_publicKeyBlob;
}
}
public String Name
{
set
{
if (value != null && value.Length == 0)
throw new ArgumentException( Environment.GetResourceString("Argument_EmptyName" ));
Contract.EndContractBlock();
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
m_strongNames[0].m_name = value;
else
{
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(null, value, new Version());
}
}
get
{
if(m_strongNames == null || m_strongNames.Length == 0)
return "";
if(m_strongNames.Length > 1)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
return m_strongNames[0].m_name;
}
}
public Version Version
{
set
{
m_unrestricted = false;
if(m_strongNames != null && m_strongNames.Length == 1)
m_strongNames[0].m_version = value;
else
{
m_strongNames = new StrongName2[1];
m_strongNames[0] = new StrongName2(null, "", value);
}
}
get
{
if(m_strongNames == null || m_strongNames.Length == 0)
return new Version();
if(m_strongNames.Length > 1)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity"));
return m_strongNames[0].m_version;
}
}
//------------------------------------------------------
//
// PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS
//
//------------------------------------------------------
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override IPermission Copy()
{
StrongNameIdentityPermission perm = new StrongNameIdentityPermission(PermissionState.None);
perm.m_unrestricted = this.m_unrestricted;
if(this.m_strongNames != null)
{
perm.m_strongNames = new StrongName2[this.m_strongNames.Length];
int n;
for(n = 0; n < this.m_strongNames.Length; n++)
perm.m_strongNames[n] = this.m_strongNames[n].Copy();
}
return perm;
}
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
if(m_unrestricted)
return false;
if(m_strongNames == null)
return true;
if(m_strongNames.Length == 0)
return true;
return false;
}
StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
if(that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if(that.m_unrestricted)
return true;
if(m_unrestricted)
return false;
if(this.m_strongNames != null)
{
foreach(StrongName2 snThis in m_strongNames)
{
bool bOK = false;
if(that.m_strongNames != null)
{
foreach(StrongName2 snThat in that.m_strongNames)
{
if(snThis.IsSubsetOf(snThat))
{
bOK = true;
break;
}
}
}
if(!bOK)
return false;
}
}
return true;
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
return null;
StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
if(that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if(this.m_unrestricted && that.m_unrestricted)
{
StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None);
res.m_unrestricted = true;
return res;
}
if(this.m_unrestricted)
return that.Copy();
if(that.m_unrestricted)
return this.Copy();
if(this.m_strongNames == null || that.m_strongNames == null || this.m_strongNames.Length == 0 || that.m_strongNames.Length == 0)
return null;
List<StrongName2> alStrongNames = new List<StrongName2>();
foreach(StrongName2 snThis in this.m_strongNames)
{
foreach(StrongName2 snThat in that.m_strongNames)
{
StrongName2 snInt = (StrongName2)snThis.Intersect(snThat);
if(snInt != null)
alStrongNames.Add(snInt);
}
}
if(alStrongNames.Count == 0)
return null;
StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None);
result.m_strongNames = alStrongNames.ToArray();
return result;
}
public override IPermission Union(IPermission target)
{
if (target == null)
{
if((this.m_strongNames == null || this.m_strongNames.Length == 0) && !this.m_unrestricted)
return null;
return this.Copy();
}
StrongNameIdentityPermission that = target as StrongNameIdentityPermission;
if(that == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if(this.m_unrestricted || that.m_unrestricted)
{
StrongNameIdentityPermission res = new StrongNameIdentityPermission(PermissionState.None);
res.m_unrestricted = true;
return res;
}
if (this.m_strongNames == null || this.m_strongNames.Length == 0)
{
if(that.m_strongNames == null || that.m_strongNames.Length == 0)
return null;
return that.Copy();
}
if(that.m_strongNames == null || that.m_strongNames.Length == 0)
return this.Copy();
List<StrongName2> alStrongNames = new List<StrongName2>();
foreach(StrongName2 snThis in this.m_strongNames)
alStrongNames.Add(snThis);
foreach(StrongName2 snThat in that.m_strongNames)
{
bool bDupe = false;
foreach(StrongName2 sn in alStrongNames)
{
if(snThat.Equals(sn))
{
bDupe = true;
break;
}
}
if(!bDupe)
alStrongNames.Add(snThat);
}
StrongNameIdentityPermission result = new StrongNameIdentityPermission(PermissionState.None);
result.m_strongNames = alStrongNames.ToArray();
return result;
}
#if FEATURE_CAS_POLICY
public override void FromXml(SecurityElement e)
{
m_unrestricted = false;
m_strongNames = null;
CodeAccessPermission.ValidateElement( e, this );
String unr = e.Attribute( "Unrestricted" );
if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0)
{
m_unrestricted = true;
return;
}
String elBlob = e.Attribute("PublicKeyBlob");
String elName = e.Attribute("Name");
String elVersion = e.Attribute("AssemblyVersion");
StrongName2 sn;
List<StrongName2> al = new List<StrongName2>();
if(elBlob != null || elName != null || elVersion != null)
{
sn = new StrongName2(
(elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)),
elName,
(elVersion == null ? null : new Version(elVersion)));
al.Add(sn);
}
ArrayList alChildren = e.Children;
if(alChildren != null)
{
foreach(SecurityElement child in alChildren)
{
elBlob = child.Attribute("PublicKeyBlob");
elName = child.Attribute("Name");
elVersion = child.Attribute("AssemblyVersion");
if(elBlob != null || elName != null || elVersion != null)
{
sn = new StrongName2(
(elBlob == null ? null : new StrongNamePublicKeyBlob(elBlob)),
elName,
(elVersion == null ? null : new Version(elVersion)));
al.Add(sn);
}
}
}
if(al.Count != 0)
m_strongNames = al.ToArray();
}
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.StrongNameIdentityPermission" );
if (m_unrestricted)
esd.AddAttribute( "Unrestricted", "true" );
else if (m_strongNames != null)
{
if (m_strongNames.Length == 1)
{
if (m_strongNames[0].m_publicKeyBlob != null)
esd.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[0].m_publicKeyBlob.PublicKey));
if (m_strongNames[0].m_name != null)
esd.AddAttribute("Name", m_strongNames[0].m_name);
if ((Object)m_strongNames[0].m_version != null)
esd.AddAttribute("AssemblyVersion", m_strongNames[0].m_version.ToString());
}
else
{
int n;
for(n = 0; n < m_strongNames.Length; n++)
{
SecurityElement child = new SecurityElement("StrongName");
if (m_strongNames[n].m_publicKeyBlob != null)
child.AddAttribute("PublicKeyBlob", Hex.EncodeHexString(m_strongNames[n].m_publicKeyBlob.PublicKey));
if (m_strongNames[n].m_name != null)
child.AddAttribute("Name", m_strongNames[n].m_name);
if ((Object)m_strongNames[n].m_version != null)
child.AddAttribute("AssemblyVersion", m_strongNames[n].m_version.ToString());
esd.AddChild(child);
}
}
}
return esd;
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return StrongNameIdentityPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.StrongNameIdentityPermissionIndex;
}
}
}
| |
// 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 Infrastructure.Common;
using System;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using Xunit;
public class NegotiateStream_Http_Tests : ConditionalWcfTest
{
// The tests are as follows:
//
// NegotiateStream_*_AmbientCredentials
// Windows: This should pass by default without any code changes
// Linux: This should not pass by default
// Run 'kinit user@DC.DOMAIN.COM' before running this test to use ambient credentials
// ('DC.DOMAIN.COM' must be in capital letters)
// If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all
// prior Kerberos tickets
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword
// Windows: Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// Linux: Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// If previous tests were run, it may be necessary to run 'kdestroy -A' to remove all
// prior Kerberos tickets
//
// NegotiateStream_*_With_ExplicitSpn
// Windows: Set the NegotiateTestSPN TestProperties to match a valid SPN for the server
// Linux: Set the NegotiateTestSPN TestProperties to match a valid SPN for the server
//
// By default, the SPN is the same as the host's fully qualified domain name, for example,
// 'host.domain.com'
// On a Windows host, one has to register the SPN using 'setspn', or run the process as LOCAL SYSTEM.
// This can be done by setting the PSEXEC_PATH environment variable to point to the folder containing
// psexec.exe prior to starting the WCF self-host service.
//
// NegotiateStream_*_With_Upn
// Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server in the form of
// 'user@DOMAIN.COM'
// Linux: This scenario is not yet supported - dotnet/corefx#6606
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Spn
// Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server
// Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// Linux: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server
// Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
//
// NegotiateStream_*_With_ExplicitUserNameAndPassword_With_Upn
// Windows: Set the NegotiateTestUPN TestProperties to match a valid UPN for the server
// Set the ExplicitUserName, ExplicitPassword, and NegotiateTestDomain TestProperties to a user valid on your Kerberos realm
// Linux: This scenario is not yet supported - dotnet/corefx#6606
// These tests are used for testing NegotiateStream (SecurityMode.Transport)
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Root_Certificate_Installed),
nameof(Ambient_Credentials_Available))]
[OuterLoop]
public static void NegotiateStream_Http_AmbientCredentials()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(Endpoints.Https_WindowsAuth_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Root_Certificate_Installed),
nameof(Explicit_Credentials_Available),
nameof(Domain_Available))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "NegotiateTestRealm"
// "NegotiateTestDomain"
// "ExplicitUserName"
// "ExplicitPassword"
// "ServiceUri" (server running as machine context)
public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(Endpoints.Https_WindowsAuth_Address));
factory.Credentials.Windows.ClientCredential.Domain = GetDomain();
factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName();
factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword();
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Root_Certificate_Installed),
nameof(SPN_Available))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "NegotiateTestRealm"
// "NegotiateTestDomain"
// "NegotiateTestSpn" (host/<servername>)
// "ServiceUri" (server running as machine context)
public static void NegotiateStream_Http_With_ExplicitSpn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Https_WindowsAuth_Address),
new SpnEndpointIdentity(GetSPN())
));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Root_Certificate_Installed),
nameof(UPN_Available))]
[OuterLoop]
public static void NegotiateStream_Http_With_Upn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Https_WindowsAuth_Address),
new UpnEndpointIdentity(GetUPN())
));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Root_Certificate_Installed),
nameof(Explicit_Credentials_Available),
nameof(Domain_Available),
nameof(SPN_Available))]
[OuterLoop]
// Test Requirements \\
// The following environment variables must be set...
// "NegotiateTestRealm"
// "NegotiateTestDomain"
// "ExplicitUserName"
// "ExplicitPassword"
// "NegotiateTestSpn" (host/<servername>)
// "ServiceUri" (server running as machine context)
public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword_With_Spn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Https_WindowsAuth_Address),
new SpnEndpointIdentity(GetSPN())
));
factory.Credentials.Windows.ClientCredential.Domain = GetDomain();
factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName();
factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword();
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[WcfFact]
[Condition(nameof(Windows_Authentication_Available),
nameof(Root_Certificate_Installed),
nameof(Explicit_Credentials_Available),
nameof(Domain_Available),
nameof(UPN_Available))]
[OuterLoop]
public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword_With_Upn()
{
string testString = "Hello";
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
factory = new ChannelFactory<IWcfService>(
binding,
new EndpointAddress(
new Uri(Endpoints.Https_WindowsAuth_Address),
new UpnEndpointIdentity(GetUPN())
));
factory.Credentials.Windows.ClientCredential.Domain = GetDomain();
factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName();
factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword();
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
string result = serviceProxy.Echo(testString);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
//
// FieldDefinition.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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 Mono.Collections.Generic;
namespace Mono.Cecil {
public sealed class FieldDefinition : FieldReference, IMemberDefinition, IConstantProvider, IMarshalInfoProvider {
ushort attributes;
Collection<CustomAttribute> custom_attributes;
int offset = Mixin.NotResolvedMarker;
internal int rva = Mixin.NotResolvedMarker;
byte [] initial_value;
object constant = Mixin.NotResolved;
MarshalInfo marshal_info;
void ResolveLayout ()
{
if (offset != Mixin.NotResolvedMarker)
return;
if (!HasImage) {
offset = Mixin.NoDataMarker;
return;
}
offset = Module.Read (this, (field, reader) => reader.ReadFieldLayout (field));
}
public bool HasLayoutInfo {
get {
if (offset >= 0)
return true;
ResolveLayout ();
return offset >= 0;
}
}
public int Offset {
get {
if (offset >= 0)
return offset;
ResolveLayout ();
return offset >= 0 ? offset : -1;
}
set { offset = value; }
}
void ResolveRVA ()
{
if (rva != Mixin.NotResolvedMarker)
return;
if (!HasImage)
return;
rva = Module.Read (this, (field, reader) => reader.ReadFieldRVA (field));
}
public int RVA {
get {
if (rva > 0)
return rva;
ResolveRVA ();
return rva > 0 ? rva : 0;
}
}
public byte [] InitialValue {
get {
if (initial_value != null)
return initial_value;
ResolveRVA ();
if (initial_value == null)
initial_value = Empty<byte>.Array;
return initial_value;
}
set { initial_value = value; }
}
public FieldAttributes Attributes {
get { return (FieldAttributes) attributes; }
set { attributes = (ushort) value; }
}
public bool HasConstant {
get {
ResolveConstant ();
return constant != Mixin.NoValue;
}
set { if (!value) constant = Mixin.NoValue; }
}
public object Constant {
get { return HasConstant ? constant : null; }
set { constant = value; }
}
void ResolveConstant ()
{
if (constant != Mixin.NotResolved)
return;
this.ResolveConstant (ref constant, Module);
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); }
}
public bool HasMarshalInfo {
get {
if (marshal_info != null)
return true;
return this.GetHasMarshalInfo (Module);
}
}
public MarshalInfo MarshalInfo {
get { return marshal_info ?? (marshal_info = this.GetMarshalInfo (Module)); }
set { marshal_info = value; }
}
#region FieldAttributes
public bool IsCompilerControlled {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.CompilerControlled, value); }
}
public bool IsPrivate {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Private, value); }
}
public bool IsFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamANDAssem, value); }
}
public bool IsAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Assembly, value); }
}
public bool IsFamily {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Family, value); }
}
public bool IsFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.FamORAssem, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((ushort) FieldAttributes.FieldAccessMask, (ushort) FieldAttributes.Public, value); }
}
public bool IsStatic {
get { return attributes.GetAttributes ((ushort) FieldAttributes.Static); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Static, value); }
}
public bool IsInitOnly {
get { return attributes.GetAttributes ((ushort) FieldAttributes.InitOnly); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.InitOnly, value); }
}
public bool IsLiteral {
get { return attributes.GetAttributes ((ushort) FieldAttributes.Literal); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.Literal, value); }
}
public bool IsNotSerialized {
get { return attributes.GetAttributes ((ushort) FieldAttributes.NotSerialized); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.NotSerialized, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((ushort) FieldAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.SpecialName, value); }
}
public bool IsPInvokeImpl {
get { return attributes.GetAttributes ((ushort) FieldAttributes.PInvokeImpl); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.PInvokeImpl, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((ushort) FieldAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.RTSpecialName, value); }
}
public bool HasDefault {
get { return attributes.GetAttributes ((ushort) FieldAttributes.HasDefault); }
set { attributes = attributes.SetAttributes ((ushort) FieldAttributes.HasDefault, value); }
}
#endregion
public override bool IsDefinition {
get { return true; }
}
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public FieldDefinition (string name, FieldAttributes attributes, TypeReference fieldType)
: base (name, fieldType)
{
this.attributes = (ushort) attributes;
}
public override FieldDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public const int NotResolvedMarker = -2;
public const int NoDataMarker = -1;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace FileDialogs.Design
{
internal class FileDialogPlacesEditor : CollectionEditor
{
#region Construction
public FileDialogPlacesEditor(Type type)
: base(type)
{
}
#endregion
#region Overriden Methods
protected override CollectionEditor.CollectionForm CreateCollectionForm()
{
return new FileDialogPlacesEditorForm(this);
}
#endregion
private class FileDialogPlacesEditorForm : CollectionForm
{
#region Member Fields
private List<FileDialogPlaceBase> m_places = new List<FileDialogPlaceBase>();
#endregion
#region Construction
public FileDialogPlacesEditorForm(CollectionEditor editor)
: base(editor)
{
InitializeComponent();
placesBar.Renderer = new FileDialogs.PlacesBarRenderer();
List<KeyValuePair<string, SpecialFolder>> specialFolders = new List<KeyValuePair<string, SpecialFolder>>();
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("Desktop", SpecialFolder.Desktop));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Computer", SpecialFolder.MyComputer));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Network Places", SpecialFolder.Network));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Documents", SpecialFolder.MyDocuments));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Pictures", SpecialFolder.MyPictures));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Music", SpecialFolder.MyMusic));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Video", SpecialFolder.MyVideo));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("Favorites", SpecialFolder.Favorites));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("My Recent Documents", SpecialFolder.Recent));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("Recycle Bin", SpecialFolder.RecycleBin));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("Windows", SpecialFolder.Windows));
specialFolders.Add(new KeyValuePair<string, SpecialFolder>("System", SpecialFolder.System));
specialFoldersComboBox.DataSource = specialFolders;
specialFoldersComboBox.SelectedIndex = 0;
placesListBox.DataSource = m_places;
placesListBox.DisplayMember = "Text";
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FileDialogPlacesEditor.FileDialogPlacesEditorForm));
this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.addCustomPathTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.browseButton = new System.Windows.Forms.Button();
this.customPathTextBox = new System.Windows.Forms.TextBox();
this.customPlacesLabel = new System.Windows.Forms.Label();
this.propsLabel = new System.Windows.Forms.Label();
this.previewLabel = new System.Windows.Forms.Label();
this.placesBar = new System.Windows.Forms.ToolStrip();
this.addSpecialFolderTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.specialFoldersComboBox = new System.Windows.Forms.ComboBox();
this.addSpecialFolderButton = new System.Windows.Forms.Button();
this.specialFolderLabel = new System.Windows.Forms.Label();
this.placesLabel = new System.Windows.Forms.Label();
this.placesListBox = new System.Windows.Forms.ListBox();
this.moveUpButton = new System.Windows.Forms.Button();
this.moveDownButton = new System.Windows.Forms.Button();
this.removeButton = new System.Windows.Forms.Button();
this.selectedPlaceProps = new FileDialogs.Design.VsPropertyGrid(base.Context);
this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.addCustomPathButton = new System.Windows.Forms.Button();
this.tableLayoutPanel.SuspendLayout();
this.addCustomPathTableLayoutPanel.SuspendLayout();
this.addSpecialFolderTableLayoutPanel.SuspendLayout();
this.okCancelTableLayoutPanel.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel
//
resources.ApplyResources(this.tableLayoutPanel, "tableLayoutPanel");
this.tableLayoutPanel.Controls.Add(this.addCustomPathTableLayoutPanel, 0, 3);
this.tableLayoutPanel.Controls.Add(this.customPlacesLabel, 0, 2);
this.tableLayoutPanel.Controls.Add(this.propsLabel, 2, 0);
this.tableLayoutPanel.Controls.Add(this.previewLabel, 3, 0);
this.tableLayoutPanel.Controls.Add(this.placesBar, 3, 1);
this.tableLayoutPanel.Controls.Add(this.addSpecialFolderTableLayoutPanel, 0, 1);
this.tableLayoutPanel.Controls.Add(this.specialFolderLabel, 0, 0);
this.tableLayoutPanel.Controls.Add(this.placesLabel, 0, 5);
this.tableLayoutPanel.Controls.Add(this.placesListBox, 0, 6);
this.tableLayoutPanel.Controls.Add(this.moveUpButton, 1, 6);
this.tableLayoutPanel.Controls.Add(this.moveDownButton, 1, 7);
this.tableLayoutPanel.Controls.Add(this.removeButton, 1, 8);
this.tableLayoutPanel.Controls.Add(this.selectedPlaceProps, 2, 1);
this.tableLayoutPanel.Controls.Add(this.okCancelTableLayoutPanel, 0, 9);
this.tableLayoutPanel.Controls.Add(this.addCustomPathButton, 0, 4);
this.tableLayoutPanel.Name = "tableLayoutPanel";
//
// addCustomPathTableLayoutPanel
//
resources.ApplyResources(this.addCustomPathTableLayoutPanel, "addCustomPathTableLayoutPanel");
this.addCustomPathTableLayoutPanel.Controls.Add(this.browseButton, 1, 0);
this.addCustomPathTableLayoutPanel.Controls.Add(this.customPathTextBox, 0, 0);
this.addCustomPathTableLayoutPanel.Name = "addCustomPathTableLayoutPanel";
//
// browseButton
//
resources.ApplyResources(this.browseButton, "browseButton");
this.browseButton.Name = "browseButton";
this.browseButton.UseVisualStyleBackColor = true;
this.browseButton.Click += new System.EventHandler(this.browseButton_Click);
//
// customPathTextBox
//
resources.ApplyResources(this.customPathTextBox, "customPathTextBox");
this.customPathTextBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.customPathTextBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
this.customPathTextBox.Name = "customPathTextBox";
this.customPathTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(customPathTextBox_KeyDown);
this.customPathTextBox.TextChanged += new System.EventHandler(this.customPathTextBox_TextChanged);
//
// customPlacesLabel
//
resources.ApplyResources(this.customPlacesLabel, "customPlacesLabel");
this.customPlacesLabel.Name = "customPlacesLabel";
//
// propsLabel
//
resources.ApplyResources(this.propsLabel, "propsLabel");
this.propsLabel.Name = "propsLabel";
//
// previewLabel
//
resources.ApplyResources(this.previewLabel, "previewLabel");
this.previewLabel.Name = "previewLabel";
//
// placesBar
//
resources.ApplyResources(this.placesBar, "placesBar");
this.placesBar.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.placesBar.ImageScalingSize = new System.Drawing.Size(32, 32);
this.placesBar.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow;
this.placesBar.Name = "placesBar";
this.placesBar.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.tableLayoutPanel.SetRowSpan(this.placesBar, 8);
this.placesBar.Stretch = true;
this.placesBar.TabStop = true;
//
// addSpecialFolderTableLayoutPanel
//
resources.ApplyResources(this.addSpecialFolderTableLayoutPanel, "addSpecialFolderTableLayoutPanel");
this.addSpecialFolderTableLayoutPanel.Controls.Add(this.specialFoldersComboBox, 0, 0);
this.addSpecialFolderTableLayoutPanel.Controls.Add(this.addSpecialFolderButton, 1, 0);
this.addSpecialFolderTableLayoutPanel.Name = "addSpecialFolderTableLayoutPanel";
//
// specialFoldersComboBox
//
resources.ApplyResources(this.specialFoldersComboBox, "specialFoldersComboBox");
this.specialFoldersComboBox.DisplayMember = "Key";
this.specialFoldersComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.specialFoldersComboBox.FormattingEnabled = true;
this.specialFoldersComboBox.Name = "specialFoldersComboBox";
this.specialFoldersComboBox.ValueMember = "Value";
//
// addSpecialFolderButton
//
resources.ApplyResources(this.addSpecialFolderButton, "addSpecialFolderButton");
this.addSpecialFolderButton.Name = "addSpecialFolderButton";
this.addSpecialFolderButton.UseVisualStyleBackColor = true;
this.addSpecialFolderButton.Click += new System.EventHandler(this.addSpecialFolderButton_Click);
//
// specialFolderLabel
//
resources.ApplyResources(this.specialFolderLabel, "specialFolderLabel");
this.specialFolderLabel.Name = "specialFolderLabel";
//
// placesLabel
//
resources.ApplyResources(this.placesLabel, "placesLabel");
this.placesLabel.Name = "placesLabel";
//
// placesListBox
//
resources.ApplyResources(this.placesListBox, "placesListBox");
this.placesListBox.Name = "placesListBox";
this.tableLayoutPanel.SetRowSpan(this.placesListBox, 3);
this.placesListBox.SelectedIndexChanged += new System.EventHandler(this.placesListBox_SelectedIndexChanged);
//
// moveUpButton
//
resources.ApplyResources(this.moveUpButton, "moveUpButton");
this.moveUpButton.Name = "moveUpButton";
this.moveUpButton.UseVisualStyleBackColor = true;
this.moveUpButton.Click += new System.EventHandler(this.moveUpButton_Click);
//
// moveDownButton
//
resources.ApplyResources(this.moveDownButton, "moveDownButton");
this.moveDownButton.Name = "moveDownButton";
this.moveDownButton.UseVisualStyleBackColor = true;
this.moveDownButton.Click += new System.EventHandler(this.moveDownButton_Click);
//
// removeButton
//
resources.ApplyResources(this.removeButton, "removeButton");
this.removeButton.Name = "removeButton";
this.removeButton.UseVisualStyleBackColor = true;
this.removeButton.Click += new System.EventHandler(this.removeButton_Click);
//
// selectedPlaceProps
//
this.selectedPlaceProps.CommandsVisibleIfAvailable = false;
resources.ApplyResources(this.selectedPlaceProps, "selectedPlaceProps");
this.selectedPlaceProps.Name = "selectedPlaceProps";
this.tableLayoutPanel.SetRowSpan(this.selectedPlaceProps, 8);
this.selectedPlaceProps.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.selectedPlaceProps_PropertyValueChanged);
//
// okCancelTableLayoutPanel
//
resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel");
this.tableLayoutPanel.SetColumnSpan(this.okCancelTableLayoutPanel, 4);
this.okCancelTableLayoutPanel.Controls.Add(this.okButton, 0, 0);
this.okCancelTableLayoutPanel.Controls.Add(this.cancelButton, 1, 0);
this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel";
this.okCancelTableLayoutPanel.TabStop = true;
//
// okButton
//
resources.ApplyResources(this.okButton, "okButton");
this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okButton.Name = "okButton";
this.okButton.UseVisualStyleBackColor = true;
this.okButton.Click += new System.EventHandler(okButton_Click);
//
// cancelButton
//
resources.ApplyResources(this.cancelButton, "cancelButton");
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Name = "cancelButton";
this.cancelButton.UseVisualStyleBackColor = true;
//
// addCustomPathButton
//
resources.ApplyResources(this.addCustomPathButton, "addCustomPathButton");
this.addCustomPathButton.Name = "addCustomPathButton";
this.addCustomPathButton.UseVisualStyleBackColor = true;
this.addCustomPathButton.Click += new System.EventHandler(this.addCustomPathButton_Click);
//
// Form1
//
this.AcceptButton = this.okButton;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cancelButton;
this.Controls.Add(this.tableLayoutPanel);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.tableLayoutPanel.ResumeLayout(false);
this.tableLayoutPanel.PerformLayout();
this.addCustomPathTableLayoutPanel.ResumeLayout(false);
this.addCustomPathTableLayoutPanel.PerformLayout();
this.addSpecialFolderTableLayoutPanel.ResumeLayout(false);
this.addSpecialFolderTableLayoutPanel.PerformLayout();
this.okCancelTableLayoutPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
private System.Windows.Forms.TableLayoutPanel addSpecialFolderTableLayoutPanel;
private System.Windows.Forms.ComboBox specialFoldersComboBox;
private System.Windows.Forms.Button addSpecialFolderButton;
private System.Windows.Forms.Label specialFolderLabel;
private System.Windows.Forms.Label placesLabel;
private System.Windows.Forms.ListBox placesListBox;
private System.Windows.Forms.Button moveUpButton;
private System.Windows.Forms.Button moveDownButton;
private System.Windows.Forms.Button removeButton;
private FileDialogs.Design.VsPropertyGrid selectedPlaceProps;
private System.Windows.Forms.ToolStrip placesBar;
private System.Windows.Forms.TableLayoutPanel okCancelTableLayoutPanel;
private System.Windows.Forms.Button okButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Label previewLabel;
private System.Windows.Forms.Label propsLabel;
private System.Windows.Forms.Label customPlacesLabel;
private System.Windows.Forms.TableLayoutPanel addCustomPathTableLayoutPanel;
private System.Windows.Forms.Button browseButton;
private System.Windows.Forms.TextBox customPathTextBox;
private System.Windows.Forms.Button addCustomPathButton;
#endregion
#region Common Methods
private void AddPlace(FileDialogPlaceBase place)
{
m_places.Add(place);
((CurrencyManager)placesListBox.BindingContext[m_places]).Refresh();
bool multipleLines;
ToolStripButton placeButton = new ToolStripButton(FileDialog.InsertLineBreaks(place.Text, out multipleLines));
placeButton.Image = ShellImageList.GetImage(place.PIDL);
placeButton.ImageAlign = ContentAlignment.BottomCenter;
placeButton.Margin = new Padding(1, 0, 0, 0);
placeButton.Padding = new Padding(0, multipleLines ? 3 : 8, 0, multipleLines ? 0 : 8);
placeButton.Tag = place;
placeButton.TextImageRelation = TextImageRelation.ImageAboveText;
placesBar.Items.Add(placeButton);
placesListBox.ClearSelected();
placesListBox.SelectedIndex = placesListBox.Items.Count - 1;
}
private void MovePlace(int fromIndex, int toIndex)
{
FileDialogPlaceBase place = (FileDialogPlaceBase)placesListBox.Items[fromIndex];
ToolStripItem placeButton = placesBar.Items[fromIndex];
m_places.RemoveAt(fromIndex);
placesBar.Items.RemoveAt(fromIndex);
m_places.Insert(toIndex, place);
placesBar.Items.Insert(toIndex, placeButton);
((CurrencyManager)placesListBox.BindingContext[m_places]).Refresh();
}
private void RemovePlace(int index)
{
m_places.RemoveAt(index);
placesBar.Items.RemoveAt(index);
((CurrencyManager)placesListBox.BindingContext[m_places]).Refresh();
if (placesListBox.Items.Count > 0)
{
placesListBox.ClearSelected();
index = Math.Max(0, Math.Min(index, placesListBox.Items.Count - 1));
placesListBox.SelectedIndex = index;
}
}
#endregion
#region Overriden Methods
protected override void OnEditValueChanged()
{
if (Items.Length > 0)
{
for (int i = 0; i < Items.Length; i++)
{
AddPlace((FileDialogPlaceBase)Items[i]);
}
}
else
{
AddPlace(new FileDialogPlace(SpecialFolder.Desktop));
AddPlace(new FileDialogPlace(SpecialFolder.MyDocuments));
AddPlace(new FileDialogPlace(SpecialFolder.MyComputer));
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (placesListBox.Items.Count > 0)
placesListBox.SelectedIndex = 0;
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter && customPathTextBox.Focused)
{
return false;
}
return base.ProcessDialogKey(keyData);
}
#endregion
#region Control Specific Methods
private void addSpecialFolderButton_Click(object sender, EventArgs e)
{
AddPlace(new FileDialogPlace((SpecialFolder)specialFoldersComboBox.SelectedValue));
}
private void customPathTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
addCustomPathButton.PerformClick();
}
}
private void customPathTextBox_TextChanged(object sender, EventArgs e)
{
addCustomPathButton.Enabled = customPathTextBox.Text.Trim().Length > 0;
}
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog(this) == DialogResult.OK)
customPathTextBox.Text = dlg.SelectedPath;
}
private void addCustomPathButton_Click(object sender, EventArgs e)
{
string path = customPathTextBox.Text;
if (!Directory.Exists(path))
{
MessageBox.Show(this, "The directory at the specified path doesn't exist.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
AddPlace(new CustomFileDialogPlace(path));
customPathTextBox.Clear();
}
private void placesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
selectedPlaceProps.SelectedObject = placesListBox.SelectedItem;
int selectedIndex = placesListBox.SelectedIndex;
moveUpButton.Enabled = (selectedIndex > 0);
moveDownButton.Enabled = (selectedIndex >= 0 && selectedIndex < placesListBox.Items.Count - 1);
removeButton.Enabled = (selectedIndex >= 0);
}
private void moveUpButton_Click(object sender, EventArgs e)
{
int index = placesListBox.SelectedIndex;
MovePlace(index, --index);
placesListBox.SelectedIndex = index;
}
private void moveDownButton_Click(object sender, EventArgs e)
{
int index = placesListBox.SelectedIndex;
MovePlace(index, ++index);
placesListBox.SelectedIndex = index;
}
private void removeButton_Click(object sender, EventArgs e)
{
RemovePlace(placesListBox.SelectedIndex);
}
private void selectedPlaceProps_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
FileDialogPlaceBase place = (FileDialogPlaceBase)placesListBox.SelectedItem;
((CurrencyManager)placesListBox.BindingContext[m_places]).Refresh();
bool multipleLines;
ToolStripButton placeButton = (ToolStripButton)placesBar.Items[placesListBox.SelectedIndex];
placeButton.Text = FileDialog.InsertLineBreaks(place.Text, out multipleLines);
placeButton.Padding = new Padding(0, multipleLines ? 3 : 8, 0, multipleLines ? 0 : 8);
if (e.ChangedItem.Label == "Path")
placeButton.Image = ShellImageList.GetImage(place.PIDL);
}
private void okButton_Click(object sender, EventArgs e)
{
if (placesListBox.Items.Count == 0)
{
MessageBox.Show(this, "The places bar must at least contain one place.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.None;
return;
}
object[] places = new object[placesListBox.Items.Count];
for (int i = 0; i < placesListBox.Items.Count; i++)
{
places[i] = placesListBox.Items[i];
}
Items = places;
}
#endregion
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IServiceTypeApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ServiceType</returns>
ServiceType GetServiceTypeById (string serviceTypeId);
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ApiResponse of ServiceType</returns>
ApiResponse<ServiceType> GetServiceTypeByIdWithHttpInfo (string serviceTypeId);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ServiceType></returns>
List<ServiceType> GetServiceTypeBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ServiceType></returns>
ApiResponse<List<ServiceType>> GetServiceTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ServiceType</returns>
System.Threading.Tasks.Task<ServiceType> GetServiceTypeByIdAsync (string serviceTypeId);
/// <summary>
/// Get a serviceType by id
/// </summary>
/// <remarks>
/// Returns the serviceType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ApiResponse (ServiceType)</returns>
System.Threading.Tasks.Task<ApiResponse<ServiceType>> GetServiceTypeByIdAsyncWithHttpInfo (string serviceTypeId);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ServiceType></returns>
System.Threading.Tasks.Task<List<ServiceType>> GetServiceTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search serviceTypes
/// </summary>
/// <remarks>
/// Returns the list of serviceTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ServiceType>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ServiceType>>> GetServiceTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ServiceTypeApi : IServiceTypeApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ServiceTypeApi"/> class.
/// </summary>
/// <returns></returns>
public ServiceTypeApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ServiceTypeApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ServiceTypeApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Infoplus.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ServiceType</returns>
public ServiceType GetServiceTypeById (string serviceTypeId)
{
ApiResponse<ServiceType> localVarResponse = GetServiceTypeByIdWithHttpInfo(serviceTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>ApiResponse of ServiceType</returns>
public ApiResponse< ServiceType > GetServiceTypeByIdWithHttpInfo (string serviceTypeId)
{
// verify the required parameter 'serviceTypeId' is set
if (serviceTypeId == null)
throw new ApiException(400, "Missing required parameter 'serviceTypeId' when calling ServiceTypeApi->GetServiceTypeById");
var localVarPath = "/v1.0/serviceType/{serviceTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (serviceTypeId != null) localVarPathParams.Add("serviceTypeId", Configuration.ApiClient.ParameterToString(serviceTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetServiceTypeById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ServiceType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ServiceType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ServiceType)));
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ServiceType</returns>
public async System.Threading.Tasks.Task<ServiceType> GetServiceTypeByIdAsync (string serviceTypeId)
{
ApiResponse<ServiceType> localVarResponse = await GetServiceTypeByIdAsyncWithHttpInfo(serviceTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a serviceType by id Returns the serviceType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="serviceTypeId">Id of serviceType to be returned.</param>
/// <returns>Task of ApiResponse (ServiceType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ServiceType>> GetServiceTypeByIdAsyncWithHttpInfo (string serviceTypeId)
{
// verify the required parameter 'serviceTypeId' is set
if (serviceTypeId == null)
throw new ApiException(400, "Missing required parameter 'serviceTypeId' when calling ServiceTypeApi->GetServiceTypeById");
var localVarPath = "/v1.0/serviceType/{serviceTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (serviceTypeId != null) localVarPathParams.Add("serviceTypeId", Configuration.ApiClient.ParameterToString(serviceTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetServiceTypeById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ServiceType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ServiceType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ServiceType)));
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ServiceType></returns>
public List<ServiceType> GetServiceTypeBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ServiceType>> localVarResponse = GetServiceTypeBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ServiceType></returns>
public ApiResponse< List<ServiceType> > GetServiceTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/v1.0/serviceType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetServiceTypeBySearchText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ServiceType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ServiceType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ServiceType>)));
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ServiceType></returns>
public async System.Threading.Tasks.Task<List<ServiceType>> GetServiceTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ServiceType>> localVarResponse = await GetServiceTypeBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search serviceTypes Returns the list of serviceTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ServiceType>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ServiceType>>> GetServiceTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/v1.0/serviceType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetServiceTypeBySearchText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ServiceType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ServiceType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ServiceType>)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using ruibarbo.core.Common;
using ruibarbo.core.ElementFactory;
using ruibarbo.core.Hardware;
using ruibarbo.core.Search;
using ruibarbo.core.Utils;
using ruibarbo.core.Wpf.Invoker;
namespace ruibarbo.core.Wpf.Base
{
public abstract class WpfFrameworkElementBase<TNativeElement> : ISearchSourceElement, IAmFoundByUpdatable, IHasStrongReference<TNativeElement>, IClickable
where TNativeElement : System.Windows.FrameworkElement
{
private readonly ISearchSourceElement _searchParent;
private readonly WeakReference _frameworkElement;
private string _foundByAsString;
protected WpfFrameworkElementBase(ISearchSourceElement searchParent, TNativeElement frameworkElement)
{
_searchParent = searchParent;
_frameworkElement = new WeakReference(frameworkElement);
_foundByAsString = string.Empty;
}
public virtual string Name
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.Name); }
}
public virtual string Class
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.GetType().FullName); }
}
public virtual IEnumerable<object> NativeChildren
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.GetFrameworkElementChildren()); }
}
public virtual object NativeParent
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.GetFrameworkElementParent()); }
}
public virtual string FoundBy
{
get { return _foundByAsString; }
}
public virtual ISearchSourceElement SearchParent
{
get { return _searchParent; }
}
public virtual int InstanceId
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.GetHashCode()); }
}
public bool IsVisible
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.IsVisible); }
}
public bool IsEnabled
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.IsEnabled); }
}
public virtual void Click()
{
Click(x => { });
}
public virtual void Click(Action<Configurator> cfgAction)
{
VerifyIsLoadedAndVisibleAndEnabled();
this.BringIntoView();
VerifyIsClickable();
Mouse.Click(this, cfgAction);
}
public void DoubleClick()
{
VerifyIsLoadedAndVisibleAndEnabled();
this.BringIntoView();
VerifyIsClickable();
Mouse.DoubleClick(this);
}
private void VerifyIsLoadedAndVisibleAndEnabled()
{
bool isLoaded = Wait.Until(() => IsLoaded);
if (!isLoaded)
{
throw RuibarboException.StateFailed(this, x => x.IsLoaded);
}
bool isVisible = Wait.Until(() => IsVisible);
if (!isVisible)
{
throw RuibarboException.StateFailed(this, x => x.IsVisible);
}
bool isEnabled = Wait.Until(() => IsEnabled);
if (!isEnabled)
{
throw RuibarboException.StateFailed(this, x => x.IsEnabled);
}
}
private bool IsLoaded
{
get { return OnUiThread.Get(this, frameworkElement => frameworkElement.IsLoaded); }
}
private void VerifyIsClickable()
{
bool isClickable = Wait.Until(() => IsClickable);
if (!isClickable)
{
var clickablePoint = ClickablePoint;
var screenPoint = new System.Windows.Point(clickablePoint.X, clickablePoint.Y);
var localPoint = OnUiThread.Get(this, frameworkElement => frameworkElement.PointFromScreen(screenPoint));
throw RuibarboException.StateFailed(this, x => x.IsClickable, string.Format("Clickable Point: {0}", localPoint));
}
}
public bool IsClickable
{
get
{
var clickablePoint = ClickablePoint;
var screenPoint = new System.Windows.Point(clickablePoint.X, clickablePoint.Y);
return OnUiThread.Get(this, frameworkElement =>
{
System.Windows.FrameworkElement rootElement = GetRootElement(frameworkElement);
var localPoint = rootElement.PointFromScreen(screenPoint);
System.Windows.Media.HitTestResult result = null;
System.Windows.Media.VisualTreeHelper.HitTest(
rootElement,
filterElement =>
{
var uiElement = filterElement as System.Windows.UIElement;
if (uiElement != null)
{
if (uiElement.IsVisible)
{
return uiElement.IsHitTestVisible
? System.Windows.Media.HitTestFilterBehavior.Continue
: System.Windows.Media.HitTestFilterBehavior.ContinueSkipSelf;
}
}
return System.Windows.Media.HitTestFilterBehavior.ContinueSkipSelfAndChildren;
},
resultElement =>
{
result = resultElement;
return System.Windows.Media.HitTestResultBehavior.Stop;
},
new System.Windows.Media.PointHitTestParameters(localPoint));
if (result != null)
{
var hitDependencyObject = result.VisualHit;
return IsChildOf(frameworkElement, hitDependencyObject);
}
return false;
});
}
}
private static System.Windows.FrameworkElement GetRootElement(System.Windows.FrameworkElement child)
{
System.Windows.FrameworkElement currentFrameworkElement = child;
System.Windows.DependencyObject current = child;
while (true)
{
var parent = System.Windows.Media.VisualTreeHelper.GetParent(current);
if (parent == null)
{
return currentFrameworkElement;
}
current = parent;
var asFrameworkElement = current as System.Windows.FrameworkElement;
if (asFrameworkElement != null)
{
currentFrameworkElement = asFrameworkElement;
}
}
}
private static bool IsChildOf(System.Windows.DependencyObject parent, System.Windows.DependencyObject child)
{
System.Windows.DependencyObject current = child;
while (true)
{
if (Equals(parent, current))
{
return true;
}
current = System.Windows.Media.VisualTreeHelper.GetParent(current);
if (current == null)
{
return false;
}
}
}
public virtual MousePoint ClickablePoint
{
get
{
var bounds = this.BoundsOnScreen();
var centerX = (int)(bounds.X + bounds.Width / 2);
var centerY = (int)(bounds.Y + bounds.Height / 2);
return new MousePoint(centerX, centerY);
}
}
public void UpdateFoundBy(string foundByAsString)
{
_foundByAsString = foundByAsString;
}
public TTooltipElement Tooltip<TTooltipElement>()
where TTooltipElement : class, ISearchSourceElement
{
return AllTooltips<TTooltipElement>().FirstOrDefault();
}
private IEnumerable<TTooltipElement> AllTooltips<TTooltipElement>()
where TTooltipElement : class, ISearchSourceElement
{
System.Windows.Controls.ToolTip tooltip = OnUiThread.Get(this, frameworkElement =>
{
object toolTip = frameworkElement.ToolTip;
var asToolTip = toolTip as System.Windows.Controls.ToolTip;
if (asToolTip != null)
{
return asToolTip;
}
// TODO: This can happen. When? What to do?
return null;
});
if (tooltip == null)
{
return new TTooltipElement[] { };
}
return ElementFactory.ElementFactory.CreateElements(this, tooltip)
.OfType<TTooltipElement>()
.Where(e => e.GetType() == typeof(TTooltipElement));
}
// I would have liked a method that always returns the visual tree of the ToolTip. However, there seems to be no way of
// getting hold on it when the ToolTip is specified as a string. The visual is created on the fly (after the ToolTipOpening
// event has fired) and is opened in a Popup window that has no relation to the FrameworkElement. This seems to be the only
// way, to have two separate methods for the two scenarios...
//
// One possibility, based on http://stackoverflow.com/a/24596864/617658:
// Create a ShowTooltip_T() method that places the mouse over the FrameworkElement. Then set an attach property on the ToolTip
// style (a uniqe value such as timestamp) and extract the visuals from the attached property callback.
public string TooltipAsString()
{
return OnUiThread.Get(this, frameworkElement =>
{
var toolTip = frameworkElement.ToolTip;
var asString = toolTip as string;
if (asString != null)
{
return asString;
}
return null;
});
}
public TNativeElement GetStrongReference()
{
var strongReference = (TNativeElement)_frameworkElement.Target;
if (strongReference != null)
{
return strongReference;
}
throw RuibarboException.NoLongerAvailable(this);
}
}
public static class WpfElementExtensions
{
public static System.Windows.Rect BoundsOnScreen<TFrameworkElement>(this WpfFrameworkElementBase<TFrameworkElement> me)
where TFrameworkElement : System.Windows.FrameworkElement
{
return OnUiThread.Get(me, frameworkElement =>
{
var locationFromScreen = frameworkElement.PointToScreen(new System.Windows.Point(0.0, 0.0));
var width = frameworkElement.ActualWidth;
var height = frameworkElement.ActualHeight;
return new System.Windows.Rect(locationFromScreen.X, locationFromScreen.Y, width, height);
});
}
public static bool IsHitTestVisible<TFrameworkElement>(this WpfFrameworkElementBase<TFrameworkElement> me)
where TFrameworkElement : System.Windows.FrameworkElement
{
return OnUiThread.Get(me, frameworkElement => frameworkElement.IsHitTestVisible);
}
public static bool IsKeyboardFocused<TFrameworkElement>(this WpfFrameworkElementBase<TFrameworkElement> me)
where TFrameworkElement : System.Windows.FrameworkElement
{
return OnUiThread.Get(me, frameworkElement => frameworkElement.IsKeyboardFocused);
}
public static void BringIntoView<TNativeElement>(this WpfFrameworkElementBase<TNativeElement> me)
where TNativeElement : System.Windows.FrameworkElement
{
OnUiThread.Invoke(me, frameworkElement => frameworkElement.BringIntoView());
bool isInView = Wait.Until(() => me.IsInView());
if (!isInView)
{
throw RuibarboException.StateFailed(me, x => x.IsInView());
}
}
public static bool IsInView<TFrameworkElement>(this WpfFrameworkElementBase<TFrameworkElement> me)
where TFrameworkElement : System.Windows.FrameworkElement
{
return OnUiThread.Get(me, element =>
{
var container = System.Windows.Media.VisualTreeHelper.GetParent(element) as System.Windows.FrameworkElement;
if (container == null)
{
// Not really sure about this...
return true;
}
var elementBounds = element
.TransformToAncestor(container)
.TransformBounds(new System.Windows.Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
var containerBounds = new System.Windows.Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
var isInView = containerBounds.IntersectsWith(elementBounds);
//Console.WriteLine("IsInView '{0}' of {1}:{2} in '{3}' of {4}:{5}: {6} ({7} in {8})",
// element.Name,
// element.GetType().Name,
// element.GetHashCode(),
// container.Name,
// container.GetType().Name,
// container.GetHashCode(),
// isInView,
// elementBounds.ToString(),
// containerBounds.ToString());
return isInView;
});
}
}
}
| |
namespace dotless.Core.Importers
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Input;
using Parser;
using Parser.Tree;
using Utils;
using System.Text.RegularExpressions;
using System.Reflection;
public class Importer : IImporter
{
private static readonly Regex _embeddedResourceRegex = new Regex(@"^dll://(?<Assembly>.+?)#(?<Resource>.+)$");
public static Regex EmbeddedResourceRegex { get { return _embeddedResourceRegex; } }
public IFileReader FileReader { get; set; }
/// <summary>
/// List of successful imports
/// </summary>
public List<string> Imports { get; set; }
public Func<Parser> Parser { get; set; }
private readonly List<string> _paths = new List<string>();
/// <summary>
/// The raw imports of every @import node, for use with @import
/// </summary>
protected readonly List<string> _rawImports = new List<string>();
/// <summary>
/// Duplicates of reference imports should be ignored just like normal imports
/// but a reference import must not interfere with a regular import, hence a different list
/// </summary>
private readonly List<string> _referenceImports = new List<string>();
public virtual string CurrentDirectory { get; set; }
/// <summary>
/// Whether or not the importer should alter urls
/// </summary>
public bool IsUrlRewritingDisabled { get; set; }
public string RootPath { get; set; }
/// <summary>
/// Import all files as if they are less regardless of file extension
/// </summary>
public bool ImportAllFilesAsLess { get; set; }
/// <summary>
/// Import the css and include inline
/// </summary>
public bool InlineCssFiles { get; set; }
public Importer() : this(new FileReader())
{
}
public Importer(IFileReader fileReader) : this(fileReader, false, "", false, false)
{
}
public Importer(IFileReader fileReader, bool disableUrlReWriting, string rootPath, bool inlineCssFiles, bool importAllFilesAsLess)
{
FileReader = fileReader;
IsUrlRewritingDisabled = disableUrlReWriting;
RootPath = rootPath;
InlineCssFiles = inlineCssFiles;
ImportAllFilesAsLess = importAllFilesAsLess;
Imports = new List<string>();
CurrentDirectory = "";
}
/// <summary>
/// Whether a url has a protocol on it
/// </summary>
private static bool IsProtocolUrl(string url)
{
return Regex.IsMatch(url, @"^([a-zA-Z]{2,}:)");
}
/// <summary>
/// Whether a url has a protocol on it
/// </summary>
private static bool IsNonRelativeUrl(string url)
{
return url.StartsWith(@"/") || url.StartsWith(@"~/") || Regex.IsMatch(url, @"^[a-zA-Z]:");
}
/// <summary>
/// Whether a url represents an embedded resource
/// </summary>
private static bool IsEmbeddedResource(string path)
{
return _embeddedResourceRegex.IsMatch(path);
}
/// <summary>
/// Get a list of the current paths, used to pass back in to alter url's after evaluation
/// </summary>
/// <returns></returns>
public List<string> GetCurrentPathsClone()
{
return new List<string>(_paths);
}
/// <summary>
/// returns true if the import should be ignored because it is a duplicate and import-once was used
/// </summary>
/// <param name="import"></param>
/// <returns></returns>
protected bool CheckIgnoreImport(Import import)
{
return CheckIgnoreImport(import, import.Path);
}
/// <summary>
/// returns true if the import should be ignored because it is a duplicate and import-once was used
/// </summary>
/// <param name="import"></param>
/// <returns></returns>
protected bool CheckIgnoreImport(Import import, string path)
{
if (IsOptionSet(import.ImportOptions, ImportOptions.Multiple))
{
return false;
}
// The import option Reference is set at parse time,
// but the IsReference bit is set at evaluation time (inherited from parent)
// so we check both.
if (import.IsReference || IsOptionSet(import.ImportOptions, ImportOptions.Reference))
{
if (_rawImports.Contains(path, StringComparer.InvariantCultureIgnoreCase))
{
// Already imported as a regular import, so the reference import is redundant
return true;
}
return CheckIgnoreImport(_referenceImports, path);
}
return CheckIgnoreImport(_rawImports, path);
}
private bool CheckIgnoreImport(List<string> importList, string path) {
if (importList.Contains(path, StringComparer.InvariantCultureIgnoreCase))
{
return true;
}
importList.Add(path);
return false;
}
/// <summary>
/// Imports the file inside the import as a dot-less file.
/// </summary>
/// <param name="import"></param>
/// <returns> The action for the import node to process</returns>
public virtual ImportAction Import(Import import)
{
// if the import is protocol'd (e.g. http://www.opencss.com/css?blah) then leave the import alone
if (IsProtocolUrl(import.Path) && !IsEmbeddedResource(import.Path))
{
if (import.Path.EndsWith(".less"))
{
throw new FileNotFoundException(string.Format(".less cannot import non local less files [{0}].", import.Path), import.Path);
}
if (CheckIgnoreImport(import))
{
return ImportAction.ImportNothing;
}
return ImportAction.LeaveImport;
}
var file = import.Path;
if (!IsNonRelativeUrl(file))
{
file = GetAdjustedFilePath(import.Path, _paths);
}
if (CheckIgnoreImport(import, file))
{
return ImportAction.ImportNothing;
}
bool importAsless = ImportAllFilesAsLess || IsOptionSet(import.ImportOptions, ImportOptions.Less);
if (!importAsless && import.Path.EndsWith(".css") && !import.Path.EndsWith(".less.css"))
{
if (InlineCssFiles || IsOptionSet(import.ImportOptions, ImportOptions.Inline))
{
if (IsEmbeddedResource(import.Path) && ImportEmbeddedCssContents(file, import))
return ImportAction.ImportCss;
if (ImportCssFileContents(file, import))
return ImportAction.ImportCss;
}
return ImportAction.LeaveImport;
}
if (Parser == null)
throw new InvalidOperationException("Parser cannot be null.");
if (!ImportLessFile(file, import))
{
if (IsOptionSet(import.ImportOptions, ImportOptions.Optional))
{
return ImportAction.ImportNothing;
}
if (IsOptionSet(import.ImportOptions, ImportOptions.Css))
{
return ImportAction.LeaveImport;
}
if (import.Path.EndsWith(".less", StringComparison.InvariantCultureIgnoreCase))
{
throw new FileNotFoundException(string.Format("You are importing a file ending in .less that cannot be found [{0}].", file), file);
}
return ImportAction.LeaveImport;
}
return ImportAction.ImportLess;
}
public IDisposable BeginScope(Import parentScope) {
return new ImportScope(this, Path.GetDirectoryName(parentScope.Path));
}
/// <summary>
/// Uses the paths to adjust the file path
/// </summary>
protected string GetAdjustedFilePath(string path, IEnumerable<string> pathList)
{
return pathList.Concat(new[] { path }).AggregatePaths(CurrentDirectory);
}
/// <summary>
/// Imports a less file and puts the root into the import node
/// </summary>
protected bool ImportLessFile(string lessPath, Import import)
{
string contents, file = null;
if (IsEmbeddedResource(lessPath))
{
contents = ResourceLoader.GetResource(lessPath, FileReader, out file);
if (contents == null) return false;
}
else
{
string fullName = lessPath;
if (Path.IsPathRooted(lessPath))
{
fullName = lessPath;
}
else if (!string.IsNullOrEmpty(CurrentDirectory)) {
fullName = CurrentDirectory.Replace(@"\", "/").TrimEnd('/') + '/' + lessPath;
}
bool fileExists = FileReader.DoesFileExist(fullName);
if (!fileExists && !fullName.EndsWith(".less"))
{
fullName += ".less";
fileExists = FileReader.DoesFileExist(fullName);
}
if (!fileExists) return false;
contents = FileReader.GetFileContents(fullName);
file = fullName;
}
_paths.Add(Path.GetDirectoryName(import.Path));
try
{
if (!string.IsNullOrEmpty(file))
{
Imports.Add(file);
}
import.InnerRoot = Parser().Parse(contents, lessPath);
}
catch
{
Imports.Remove(file);
throw;
}
finally
{
_paths.RemoveAt(_paths.Count - 1);
}
return true;
}
/// <summary>
/// Imports a css file from an embedded resource and puts the contents into the import node
/// </summary>
/// <param name="file"></param>
/// <param name="import"></param>
/// <returns></returns>
private bool ImportEmbeddedCssContents(string file, Import import)
{
string content = ResourceLoader.GetResource(file, FileReader, out file);
if (content == null) return false;
import.InnerContent = content;
return true;
}
/// <summary>
/// Imports a css file and puts the contents into the import node
/// </summary>
protected bool ImportCssFileContents(string file, Import import)
{
if (!FileReader.DoesFileExist(file))
{
return false;
}
import.InnerContent = FileReader.GetFileContents(file);
Imports.Add(file);
return true;
}
/// <summary>
/// Called for every Url and allows the importer to adjust relative url's to be relative to the
/// primary url
/// </summary>
public string AlterUrl(string url, List<string> pathList)
{
if (!IsProtocolUrl (url) && !IsNonRelativeUrl (url))
{
if (pathList.Any() && !IsUrlRewritingDisabled)
{
url = GetAdjustedFilePath(url, pathList);
}
return RootPath + url;
}
return url;
}
private class ImportScope : IDisposable {
private readonly Importer importer;
public ImportScope(Importer importer, string path) {
this.importer = importer;
this.importer._paths.Add(path);
}
public void Dispose() {
this.importer._paths.RemoveAt(this.importer._paths.Count - 1);
}
}
private bool IsOptionSet(ImportOptions options, ImportOptions test)
{
return (options & test) == test;
}
}
/// <summary>
/// Utility class used to retrieve the content of an embedded resource using a separate app domain in order to unload the assembly when done.
/// </summary>
class ResourceLoader : MarshalByRefObject
{
private byte[] _fileContents;
private string _resourceName;
private string _resourceContent;
/// <summary>
/// Gets the text content of an embedded resource.
/// </summary>
/// <param name="file">The path in the form: dll://AssemblyName#ResourceName</param>
/// <returns>The content of the resource</returns>
public static string GetResource(string file, IFileReader fileReader, out string fileDependency)
{
fileDependency = null;
var match = Importer.EmbeddedResourceRegex.Match(file);
if (!match.Success) return null;
var loader = new ResourceLoader();
loader._resourceName = match.Groups["Resource"].Value;
try
{
fileDependency = match.Groups["Assembly"].Value;
LoadFromCurrentAppDomain(loader, fileDependency);
if (String.IsNullOrEmpty(loader._resourceContent))
LoadFromNewAppDomain(loader, fileReader, fileDependency);
}
catch (Exception)
{
throw new FileNotFoundException("Unable to load resource [" + loader._resourceName + "] in assembly [" + fileDependency + "]");
}
finally
{
loader._fileContents = null;
}
return loader._resourceContent;
}
private static void LoadFromCurrentAppDomain(ResourceLoader loader, String assemblyName)
{
foreach (var assembly in AppDomain.CurrentDomain
.GetAssemblies()
.Where(x => !IsDynamicAssembly(x) && x.Location.EndsWith(assemblyName, StringComparison.InvariantCultureIgnoreCase)))
{
if (assembly.GetManifestResourceNames().Contains(loader._resourceName))
{
using (var stream = assembly.GetManifestResourceStream(loader._resourceName))
using (var reader = new StreamReader(stream))
{
loader._resourceContent = reader.ReadToEnd();
if (!String.IsNullOrEmpty(loader._resourceContent))
return;
}
}
}
}
private static bool IsDynamicAssembly(Assembly assembly) {
try {
string loc = assembly.Location;
return false;
} catch (NotSupportedException) {
// Location is not supported for dynamic assemblies, so it will throw a NotSupportedException
return true;
}
}
private static void LoadFromNewAppDomain(ResourceLoader loader, IFileReader fileReader, String assemblyName)
{
if (!fileReader.DoesFileExist(assemblyName))
{
throw new FileNotFoundException("Unable to locate assembly file [" + assemblyName + "]");
}
loader._fileContents = fileReader.GetBinaryFileContents(assemblyName);
var domainSetup = new AppDomainSetup();
domainSetup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var domain = AppDomain.CreateDomain("LoaderDomain", null, domainSetup);
domain.DoCallBack(loader.LoadResource);
AppDomain.Unload(domain);
}
// Runs in the separate app domain
private void LoadResource()
{
var assembly = Assembly.Load(_fileContents);
using (var stream = assembly.GetManifestResourceStream(_resourceName))
using (var reader = new StreamReader(stream))
{
_resourceContent = reader.ReadToEnd();
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>CustomerUserAccessInvitation</c> resource.</summary>
public sealed partial class CustomerUserAccessInvitationName : gax::IResourceName, sys::IEquatable<CustomerUserAccessInvitationName>
{
/// <summary>The possible contents of <see cref="CustomerUserAccessInvitationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>
/// .
/// </summary>
CustomerInvitation = 1,
}
private static gax::PathTemplate s_customerInvitation = new gax::PathTemplate("customers/{customer_id}/customerUserAccessInvitations/{invitation_id}");
/// <summary>
/// Creates a <see cref="CustomerUserAccessInvitationName"/> 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="CustomerUserAccessInvitationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerUserAccessInvitationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerUserAccessInvitationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerUserAccessInvitationName"/> with the pattern
/// <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="invitationId">The <c>Invitation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="CustomerUserAccessInvitationName"/> constructed from the provided ids.
/// </returns>
public static CustomerUserAccessInvitationName FromCustomerInvitation(string customerId, string invitationId) =>
new CustomerUserAccessInvitationName(ResourceNameType.CustomerInvitation, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), invitationId: gax::GaxPreconditions.CheckNotNullOrEmpty(invitationId, nameof(invitationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerUserAccessInvitationName"/> with
/// pattern <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="invitationId">The <c>Invitation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerUserAccessInvitationName"/> with pattern
/// <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>.
/// </returns>
public static string Format(string customerId, string invitationId) =>
FormatCustomerInvitation(customerId, invitationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerUserAccessInvitationName"/> with
/// pattern <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="invitationId">The <c>Invitation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerUserAccessInvitationName"/> with pattern
/// <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>.
/// </returns>
public static string FormatCustomerInvitation(string customerId, string invitationId) =>
s_customerInvitation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(invitationId, nameof(invitationId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerUserAccessInvitationName"/> 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}/customerUserAccessInvitations/{invitation_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerUserAccessInvitationName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <returns>The parsed <see cref="CustomerUserAccessInvitationName"/> if successful.</returns>
public static CustomerUserAccessInvitationName Parse(string customerUserAccessInvitationName) =>
Parse(customerUserAccessInvitationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerUserAccessInvitationName"/> 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}/customerUserAccessInvitations/{invitation_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerUserAccessInvitationName">
/// 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="CustomerUserAccessInvitationName"/> if successful.</returns>
public static CustomerUserAccessInvitationName Parse(string customerUserAccessInvitationName, bool allowUnparsed) =>
TryParse(customerUserAccessInvitationName, allowUnparsed, out CustomerUserAccessInvitationName 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="CustomerUserAccessInvitationName"/>
/// 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}/customerUserAccessInvitations/{invitation_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customerUserAccessInvitationName">
/// The resource name in string form. Must not be <c>null</c>.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerUserAccessInvitationName"/>, 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 customerUserAccessInvitationName, out CustomerUserAccessInvitationName result) =>
TryParse(customerUserAccessInvitationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerUserAccessInvitationName"/>
/// 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}/customerUserAccessInvitations/{invitation_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerUserAccessInvitationName">
/// 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="CustomerUserAccessInvitationName"/>, 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 customerUserAccessInvitationName, bool allowUnparsed, out CustomerUserAccessInvitationName result)
{
gax::GaxPreconditions.CheckNotNull(customerUserAccessInvitationName, nameof(customerUserAccessInvitationName));
gax::TemplatedResourceName resourceName;
if (s_customerInvitation.TryParseName(customerUserAccessInvitationName, out resourceName))
{
result = FromCustomerInvitation(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerUserAccessInvitationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomerUserAccessInvitationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string invitationId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
InvitationId = invitationId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerUserAccessInvitationName"/> class from the component parts
/// of pattern <c>customers/{customer_id}/customerUserAccessInvitations/{invitation_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="invitationId">The <c>Invitation</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerUserAccessInvitationName(string customerId, string invitationId) : this(ResourceNameType.CustomerInvitation, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), invitationId: gax::GaxPreconditions.CheckNotNullOrEmpty(invitationId, nameof(invitationId)))
{
}
/// <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>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>Invitation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string InvitationId { 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.CustomerInvitation: return s_customerInvitation.Expand(CustomerId, InvitationId);
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 CustomerUserAccessInvitationName);
/// <inheritdoc/>
public bool Equals(CustomerUserAccessInvitationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerUserAccessInvitationName a, CustomerUserAccessInvitationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerUserAccessInvitationName a, CustomerUserAccessInvitationName b) => !(a == b);
}
public partial class CustomerUserAccessInvitation
{
/// <summary>
/// <see cref="CustomerUserAccessInvitationName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CustomerUserAccessInvitationName ResourceNameAsCustomerUserAccessInvitationName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerUserAccessInvitationName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.
// -----------------------------------------------------------------------------
// Original code from SlimDX project, ported from C++/CLI.
// Greetings to SlimDX Group. Original code published with the following license:
// -----------------------------------------------------------------------------
/*
* Copyright (c) 2007-2011 SlimDX Group
*
* 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.Runtime.InteropServices;
using System.Text;
using SharpDX.Direct3D;
namespace SharpDX.Direct3D9
{
/// <summary>
/// Represents the compiled bytecode of a shader or effect.
/// </summary>
/// <unmanaged>Blob</unmanaged>
public class ShaderBytecode : DisposeBase
{
private bool isOwner;
private Blob blob;
private ConstantTable constantTable;
/// <summary>
/// Initializes a new instance of the <see cref = "SharpDX.Direct3D9.ShaderBytecode" /> class.
/// </summary>
/// <param name = "data">A <see cref = "SharpDX.DataStream" /> containing the compiled bytecode.</param>
public ShaderBytecode(DataStream data)
{
CreateFromPointer(data.PositionPointer, (int)(data.Length - data.Position));
}
/// <summary>
/// Initializes a new instance of the <see cref = "SharpDX.Direct3D9.ShaderBytecode" /> class.
/// </summary>
/// <param name = "data">A <see cref = "T:System.IO.Stream" /> containing the compiled bytecode.</param>
public ShaderBytecode(Stream data)
{
int size = (int)(data.Length - data.Position);
byte[] localBuffer = new byte[size];
data.Read(localBuffer, 0, size);
CreateFromBuffer(localBuffer);
}
/// <summary>
/// Initializes a new instance of the <see cref="ShaderBytecode"/> class.
/// </summary>
/// <param name="buffer">The buffer.</param>
public ShaderBytecode(byte[] buffer)
{
CreateFromBuffer(buffer);
}
/// <summary>
/// Initializes a new instance of the <see cref = "SharpDX.Direct3D9.ShaderBytecode" /> class.
/// </summary>
/// <param name = "buffer">a pointer to a compiler bytecode</param>
/// <param name = "sizeInBytes">size of the bytecode</param>
public ShaderBytecode(IntPtr buffer, int sizeInBytes)
{
BufferPointer = buffer;
BufferSize = sizeInBytes;
}
/// <summary>
/// Initializes a new instance of the <see cref="ShaderBytecode"/> class.
/// </summary>
/// <param name="blob">The BLOB.</param>
protected internal ShaderBytecode(Blob blob)
{
this.blob = blob;
BufferPointer = blob.BufferPointer;
BufferSize = blob.BufferSize;
}
/// <summary>
/// Gets the buffer pointer.
/// </summary>
public System.IntPtr BufferPointer { get; private set; }
/// <summary>
/// Gets or sets the size of the buffer.
/// </summary>
/// <value>
/// The size of the buffer.
/// </value>
public SharpDX.PointerSize BufferSize { get; set; }
/// <summary>
/// Gets the shader constant table.
/// </summary>
/// <unmanaged>HRESULT D3DXGetShaderConstantTable([In] const void* pFunction,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public ConstantTable ConstantTable
{
get
{
if (constantTable != null)
return constantTable;
return constantTable = D3DX9.GetShaderConstantTable(BufferPointer);
}
}
/// <summary>
/// Gets the version of the shader.
/// </summary>
/// <unmanaged>unsigned int D3DXGetShaderVersion([In] const void* pFunction)</unmanaged>
public int Version
{
get
{
return D3DX9.GetShaderVersion(BufferPointer);
}
}
/// <summary>
/// Gets the size of the shader from a function pointer.
/// </summary>
/// <param name="shaderFunctionPtr">The shader function pointer.</param>
/// <returns>Size of the shader</returns>
public static int GetShaderSize(IntPtr shaderFunctionPtr)
{
return D3DX9.GetShaderSize(shaderFunctionPtr);
}
/// <summary>
/// Assembles a shader from the given source data.
/// </summary>
/// <param name="sourceData">The source shader data.</param>
/// <param name="flags">Compilation options.</param>
/// <returns>A <see cref="SharpDX.Direct3D9.ShaderBytecode" /> object representing the raw shader stream.</returns>
/// <unmanaged>HRESULT D3DXAssembleShader([In] const void* pSrcData,[In] unsigned int SrcDataLen,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static CompilationResult Assemble(byte[] sourceData, ShaderFlags flags)
{
return Assemble(sourceData, null, null, flags);
}
/// <summary>
/// Assembles a shader from the given source data.
/// </summary>
/// <param name="sourceData">The source shader data.</param>
/// <param name="flags">Compilation options.</param>
/// <returns>A <see cref="SharpDX.Direct3D9.CompilationResult" /> object representing the raw shader stream.</returns>
/// <unmanaged>HRESULT D3DXAssembleShader([In] const void* pSrcData,[In] unsigned int SrcDataLen,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static CompilationResult Assemble(string sourceData, ShaderFlags flags)
{
return Assemble(sourceData, null, null, flags);
}
/// <summary>
/// Assembles a shader from the given source data.
/// </summary>
/// <param name="sourceData">The source shader data.</param>
/// <param name="defines">Macro definitions.</param>
/// <param name="includeFile">An <see cref="SharpDX.Direct3D9.Include" /> interface to use for handling #include directives.</param>
/// <param name="flags">Compilation options.</param>
/// <returns>A <see cref="SharpDX.Direct3D9.CompilationResult" /> object representing the raw shader stream.</returns>
/// <unmanaged>HRESULT D3DXAssembleShader([In] const void* pSrcData,[In] unsigned int SrcDataLen,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static CompilationResult Assemble(string sourceData, Macro[] defines, Include includeFile, ShaderFlags flags)
{
return Assemble(Encoding.ASCII.GetBytes(sourceData), defines, includeFile, flags);
}
/// <summary>
/// Assembles a shader from the given source data.
/// </summary>
/// <param name="sourceData">The source shader data.</param>
/// <param name="defines">Macro definitions.</param>
/// <param name="includeFile">An <see cref="SharpDX.Direct3D9.Include" /> interface to use for handling #include directives.</param>
/// <param name="flags">Compilation options.</param>
/// <returns>A <see cref="SharpDX.Direct3D9.CompilationResult" /> object representing the raw shader stream.</returns>
/// <unmanaged>HRESULT D3DXAssembleShader([In] const void* pSrcData,[In] unsigned int SrcDataLen,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static CompilationResult Assemble(byte[] sourceData, Macro[] defines, Include includeFile, ShaderFlags flags)
{
unsafe
{
var resultCode = Result.Ok;
Blob blobForCode = null;
Blob blobForErrors = null;
try
{
fixed (void* pData = sourceData)
D3DX9.AssembleShader(
(IntPtr)pData,
sourceData.Length,
PrepareMacros(defines),
IncludeShadow.ToIntPtr(includeFile),
(int)flags,
out blobForCode,
out blobForErrors);
}
catch (SharpDXException ex)
{
if (blobForErrors != null)
{
resultCode = ex.ResultCode;
if (Configuration.ThrowOnShaderCompileError)
throw new CompilationException(ex.ResultCode, Utilities.BlobToString(blobForErrors));
}
else
{
throw;
}
}
return new CompilationResult(blobForCode != null ? new ShaderBytecode(blobForCode) : null, resultCode, Utilities.BlobToString(blobForErrors));
}
}
/// <summary>
/// Assembles a shader from file.
/// </summary>
/// <param name="fileName">Name of the shader file.</param>
/// <param name="flags">Compilation options.</param>
/// <returns>A <see cref="SharpDX.Direct3D9.CompilationResult" /> object representing the raw shader stream.</returns>
public static CompilationResult AssembleFromFile(string fileName, ShaderFlags flags)
{
return AssembleFromFile(fileName, null, null, flags);
}
/// <summary>
/// Assembles a shader from file.
/// </summary>
/// <param name="fileName">Name of the shader file.</param>
/// <param name="defines">Macro definitions.</param>
/// <param name="includeFile">An <see cref="SharpDX.Direct3D9.Include"/> interface to use for handling #include directives.</param>
/// <param name="flags">Compilation options.</param>
/// <returns>
/// A <see cref="SharpDX.Direct3D9.CompilationResult"/> object representing the raw shader stream.
/// </returns>
public static CompilationResult AssembleFromFile(string fileName, Macro[] defines, Include includeFile, ShaderFlags flags)
{
return Assemble(File.ReadAllText(fileName), defines, includeFile, flags);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">A string containing the source of the shader or effect to compile.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(string shaderSource, string profile, ShaderFlags shaderFlags)
{
if (string.IsNullOrEmpty(shaderSource))
{
throw new ArgumentNullException("shaderSource");
}
return Compile(Encoding.ASCII.GetBytes(shaderSource), null, profile, shaderFlags, null, null);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(byte[] shaderSource, string profile, ShaderFlags shaderFlags)
{
return Compile(shaderSource, null, profile, shaderFlags, null, null);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">A string containing the source of the shader or effect to compile.</param>
/// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(string shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags)
{
if (string.IsNullOrEmpty(shaderSource))
{
throw new ArgumentNullException("shaderSource");
}
return Compile(Encoding.ASCII.GetBytes(shaderSource), entryPoint, profile, shaderFlags, null, null);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param>
/// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(byte[] shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags)
{
return Compile(shaderSource, entryPoint, profile, shaderFlags, null, null);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">A string containing the source of the shader or effect to compile.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <param name="defines">A set of macros to define during compilation.</param>
/// <param name="include">An interface for handling include files.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(string shaderSource, string profile, ShaderFlags shaderFlags, Macro[] defines, Include include)
{
if (string.IsNullOrEmpty(shaderSource))
{
throw new ArgumentNullException("shaderSource");
}
return Compile(Encoding.ASCII.GetBytes(shaderSource), null, profile, shaderFlags, defines, include);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <param name="defines">A set of macros to define during compilation.</param>
/// <param name="include">An interface for handling include files.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(byte[] shaderSource, string profile, ShaderFlags shaderFlags, Macro[] defines, Include include)
{
return Compile(shaderSource, null, profile, shaderFlags, defines, include);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">A string containing the source of the shader or effect to compile.</param>
/// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <param name="defines">A set of macros to define during compilation.</param>
/// <param name="include">An interface for handling include files.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(string shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags, Macro[] defines, Include include)
{
if (string.IsNullOrEmpty(shaderSource))
{
throw new ArgumentNullException("shaderSource");
}
return Compile(Encoding.ASCII.GetBytes(shaderSource), entryPoint, profile, shaderFlags, defines, include);
}
/// <summary>
/// Compiles a shader or effect from a file on disk.
/// </summary>
/// <param name="fileName">The name of the source file to compile.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <param name="defines">A set of macros to define during compilation.</param>
/// <param name="include">An interface for handling include files.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult CompileFromFile(string fileName, string profile, ShaderFlags shaderFlags = ShaderFlags.None, Macro[] defines = null, Include include = null)
{
return CompileFromFile(fileName, null, profile, shaderFlags, defines, include);
}
/// <summary>
/// Compiles a shader or effect from a file on disk.
/// </summary>
/// <param name="fileName">The name of the source file to compile.</param>
/// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <param name="defines">A set of macros to define during compilation.</param>
/// <param name="include">An interface for handling include files.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult CompileFromFile(string fileName, string entryPoint, string profile, ShaderFlags shaderFlags = ShaderFlags.None, Macro[] defines = null, Include include = null)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
if (profile == null)
{
throw new ArgumentNullException("profile");
}
if (!File.Exists(fileName))
{
throw new FileNotFoundException("Could not open the shader or effect file.", fileName);
}
return Compile(File.ReadAllText(fileName), entryPoint, profile, shaderFlags, PrepareMacros(defines), include);
}
/// <summary>
/// Compiles the provided shader or effect source.
/// </summary>
/// <param name="shaderSource">An array of bytes containing the raw source of the shader or effect to compile.</param>
/// <param name="entryPoint">The name of the shader entry-point function, or <c>null</c> for an effect file.</param>
/// <param name="profile">The shader target or set of shader features to compile against.</param>
/// <param name="shaderFlags">Shader compilation options.</param>
/// <param name="defines">A set of macros to define during compilation.</param>
/// <param name="include">An interface for handling include files.</param>
/// <returns>
/// The compiled shader bytecode, or <c>null</c> if the method fails.
/// </returns>
/// <unmanaged>HRESULT D3DXCompileShader([In] const char* pSrcData,[In] unsigned int SrcDataLen,[In] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] const char* pFunctionName,[In] const char* pProfile,[In] unsigned int Flags,[In] ID3DXBuffer** ppShader,[In] ID3DXBuffer** ppErrorMsgs,[In] ID3DXConstantTable** ppConstantTable)</unmanaged>
public static CompilationResult Compile(byte[] shaderSource, string entryPoint, string profile, ShaderFlags shaderFlags, Macro[] defines, Include include)
{
unsafe
{
var resultCode = Result.Ok;
Blob blobForCode = null;
Blob blobForErrors = null;
ConstantTable constantTable = null;
try
{
fixed (void* pData = &shaderSource[0])
D3DX9.CompileShader(
(IntPtr)pData,
shaderSource.Length,
PrepareMacros(defines),
IncludeShadow.ToIntPtr(include),
entryPoint,
profile,
(int)shaderFlags,
out blobForCode,
out blobForErrors,
out constantTable);
}
catch (SharpDXException ex)
{
if (blobForErrors != null)
{
resultCode = ex.ResultCode;
if (Configuration.ThrowOnShaderCompileError)
throw new CompilationException(ex.ResultCode, Utilities.BlobToString(blobForErrors));
}
else
{
throw;
}
}
finally
{
if (constantTable != null)
constantTable.Dispose();
}
return new CompilationResult(blobForCode != null ? new ShaderBytecode(blobForCode) : null, resultCode, Utilities.BlobToString(blobForErrors));
}
}
/// <summary>
/// Disassembles compiled HLSL code back into textual source.
/// </summary>
/// <returns>The textual source of the shader or effect.</returns>
/// <unmanaged>HRESULT D3DXDisassembleShader([In] const void* pShader,[In] BOOL EnableColorCode,[In] const char* pComments,[In] ID3DXBuffer** ppDisassembly)</unmanaged>
public string Disassemble()
{
return this.Disassemble(false, null);
}
/// <summary>
/// Disassembles compiled HLSL code back into textual source.
/// </summary>
/// <param name="enableColorCode">if set to <c>true</c> [enable color code].</param>
/// <returns>
/// The textual source of the shader or effect.
/// </returns>
/// <unmanaged>HRESULT D3DXDisassembleShader([In] const void* pShader,[In] BOOL EnableColorCode,[In] const char* pComments,[In] ID3DXBuffer** ppDisassembly)</unmanaged>
public string Disassemble(bool enableColorCode)
{
return this.Disassemble(enableColorCode, null);
}
/// <summary>
/// Disassembles compiled HLSL code back into textual source.
/// </summary>
/// <param name="enableColorCode">if set to <c>true</c> [enable color code].</param>
/// <param name="comments">Commenting information to embed in the disassembly.</param>
/// <returns>
/// The textual source of the shader or effect.
/// </returns>
/// <unmanaged>HRESULT D3DXDisassembleShader([In] const void* pShader,[In] BOOL EnableColorCode,[In] const char* pComments,[In] ID3DXBuffer** ppDisassembly)</unmanaged>
public string Disassemble(bool enableColorCode, string comments)
{
Blob output;
D3DX9.DisassembleShader(BufferPointer, enableColorCode, comments, out output);
return Utilities.BlobToString(output);
}
/// <summary>
/// Searches through the shader for the specified comment.
/// </summary>
/// <param name="fourCC">A FOURCC code used to identify the comment.</param>
/// <returns>The comment data.</returns>
/// <unmanaged>HRESULT D3DXFindShaderComment([In] const void* pFunction,[In] unsigned int FourCC,[Out] const void** ppData,[Out] unsigned int* pSizeInBytes)</unmanaged>
public DataStream FindComment(Format fourCC)
{
IntPtr buffer;
int size;
D3DX9.FindShaderComment(BufferPointer, (int)fourCC, out buffer, out size);
return new DataStream(buffer, size, true, true);
}
/// <summary>
/// Gets the set of semantics for shader inputs.
/// </summary>
/// <returns>The set of semantics for shader inputs.</returns>
/// <unmanaged>HRESULT D3DXGetShaderInputSemantics([In] const void* pFunction,[In, Out, Buffer] D3DXSEMANTIC* pSemantics,[InOut] unsigned int* pCount)</unmanaged>
public ShaderSemantic[] GetInputSemantics()
{
int count = 0;
D3DX9.GetShaderInputSemantics(BufferPointer, null, ref count);
if (count == 0)
return null;
var buffer = new ShaderSemantic[count];
D3DX9.GetShaderInputSemantics(BufferPointer, buffer, ref count);
return buffer;
}
/// <summary>
/// Gets the set of semantics for shader outputs.
/// </summary>
/// <returns>The set of semantics for shader outputs.</returns>
/// <unmanaged>HRESULT D3DXGetShaderOutputSemantics([In] const void* pFunction,[In, Out, Buffer] D3DXSEMANTIC* pSemantics,[InOut] unsigned int* pCount)</unmanaged>
public ShaderSemantic[] GetOutputSemantics()
{
int count = 0;
D3DX9.GetShaderOutputSemantics(BufferPointer, null, ref count);
if (count == 0)
return null;
var buffer = new ShaderSemantic[count];
D3DX9.GetShaderOutputSemantics(BufferPointer, buffer, ref count);
return buffer;
}
/// <summary>
/// Gets the sampler names references in the shader.
/// </summary>
/// <returns>The set of referenced sampler names.</returns>
/// <unmanaged>HRESULT D3DXGetShaderSamplers([In] const void* pFunction,[In] const char** pSamplers,[In] unsigned int* pCount)</unmanaged>
public string[] GetSamplers()
{
unsafe
{
int count = 0;
D3DX9.GetShaderSamplers(BufferPointer, IntPtr.Zero, ref count);
if (count == 0)
return null;
var result = new string[count];
if (count < 1024)
{
var pointers = stackalloc IntPtr[count];
D3DX9.GetShaderSamplers(BufferPointer, (IntPtr)pointers, ref count);
for (int i = 0; i < count; i++)
result[i] = Marshal.PtrToStringAnsi(pointers[i]);
}
else
{
var pointers = new IntPtr[count];
fixed (void* pPointers = pointers)
D3DX9.GetShaderSamplers(BufferPointer, (IntPtr)pPointers, ref count);
for (int i = 0; i < count; i++)
result[i] = Marshal.PtrToStringAnsi(pointers[i]);
}
return result;
}
}
/// <summary>
/// Extracts the major version component of a shader version number.
/// </summary>
/// <param name="version">The shader version number.</param>
/// <returns>The major version component.</returns>
public static int MajorVersion(int version)
{
return ((version >> 8) & 0xff);
}
/// <summary>
/// Extracts the minor version component of a shader version number.
/// </summary>
/// <param name="version">The shader version number.</param>
/// <returns>The minor version component.</returns>
public static int MinorVersion(int version)
{
return (version & 0xff);
}
/// <summary>
/// Converts a shader version number into a managed <see cref="T:System.Version" /> object.
/// </summary>
/// <param name="version">The shader version number.</param>
/// <returns>The parsed shader version information.</returns>
public static Version ParseVersion(int version)
{
return new Version((version >> 8) & 0xff, version & 0xff);
}
/// <summary>
/// Loads from the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>A shader bytecode</returns>
public static ShaderBytecode Load(Stream stream)
{
var buffer = Utilities.ReadStream(stream);
return new ShaderBytecode(buffer);
}
/// <summary>
/// Saves to the specified file name.
/// </summary>
/// <param name="fileName">Name of the file.</param>
public void Save(string fileName)
{
using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
Save(stream);
}
/// <summary>
/// Saves this bytecode to the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
public void Save(Stream stream)
{
if (BufferSize == 0) return;
var buffer = new byte[BufferSize];
Utilities.Read(BufferPointer, buffer, 0, buffer.Length);
stream.Write(buffer, 0, buffer.Length);
}
/// <summary>
/// Create a ShaderBytecode from a pointer.
/// </summary>
/// <param name="pointer">The pointer.</param>
/// <returns></returns>
public static ShaderBytecode FromPointer(IntPtr pointer)
{
// TODO: check that pointer is a blob?
return new ShaderBytecode(new Blob(pointer));
}
/// <summary>
/// Preprocesses the provided shader or effect source.
/// </summary>
/// <param name = "shaderSource">A string containing the source of the shader or effect to preprocess.</param>
/// <param name = "defines">A set of macros to define during preprocessing.</param>
/// <param name = "include">An interface for handling include files.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string Preprocess(string shaderSource, Macro[] defines = null, Include include = null)
{
string errors = null;
if (string.IsNullOrEmpty(shaderSource))
{
throw new ArgumentNullException("shaderSource");
}
var shaderSourcePtr = Marshal.StringToHGlobalAnsi(shaderSource);
try
{
return Preprocess(shaderSourcePtr, shaderSource.Length, defines, include, out errors);
}
finally
{
if (shaderSourcePtr != IntPtr.Zero)
Marshal.FreeHGlobal(shaderSourcePtr);
}
}
/// <summary>
/// Preprocesses the provided shader or effect source.
/// </summary>
/// <param name = "shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param>
/// <param name = "defines">A set of macros to define during preprocessing.</param>
/// <param name = "include">An interface for handling include files.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string Preprocess(byte[] shaderSource, Macro[] defines = null, Include include = null)
{
string errors = null;
return Preprocess(shaderSource, defines, include, out errors);
}
/// <summary>
/// Preprocesses the provided shader or effect source.
/// </summary>
/// <param name = "shaderSource">An array of bytes containing the raw source of the shader or effect to preprocess.</param>
/// <param name = "defines">A set of macros to define during preprocessing.</param>
/// <param name = "include">An interface for handling include files.</param>
/// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string Preprocess(byte[] shaderSource, Macro[] defines, Include include, out string compilationErrors)
{
unsafe
{
fixed (void* pData = &shaderSource[0])
return Preprocess((IntPtr)pData, shaderSource.Length, defines, include, out compilationErrors);
}
}
/// <summary>
/// Preprocesses the provided shader or effect source.
/// </summary>
/// <param name="shaderSourcePtr">The shader source PTR.</param>
/// <param name="shaderSourceLength">Length of the shader source.</param>
/// <param name="defines">A set of macros to define during preprocessing.</param>
/// <param name="include">An interface for handling include files.</param>
/// <param name="compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param>
/// <returns>
/// The preprocessed shader source.
/// </returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string Preprocess(IntPtr shaderSourcePtr, int shaderSourceLength, Macro[] defines, Include include, out string compilationErrors)
{
unsafe
{
Blob blobForText = null;
Blob blobForErrors = null;
compilationErrors = null;
try
{
D3DX9.PreprocessShader(shaderSourcePtr, shaderSourceLength, PrepareMacros(defines), IncludeShadow.ToIntPtr(include), out blobForText, out blobForErrors);
}
catch (SharpDXException ex)
{
if (blobForErrors != null)
{
compilationErrors = Utilities.BlobToString(blobForErrors);
throw new CompilationException(ex.ResultCode, compilationErrors);
}
throw;
}
return Utilities.BlobToString(blobForText);
}
}
/// <summary>
/// Preprocesses the provided shader or effect source.
/// </summary>
/// <param name = "shaderSource">A string containing the source of the shader or effect to preprocess.</param>
/// <param name = "defines">A set of macros to define during preprocessing.</param>
/// <param name = "include">An interface for handling include files.</param>
/// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string Preprocess(string shaderSource, Macro[] defines, Include include, out string compilationErrors)
{
if (string.IsNullOrEmpty(shaderSource))
{
throw new ArgumentNullException("shaderSource");
}
var shaderSourcePtr = Marshal.StringToHGlobalAnsi(shaderSource);
try
{
return Preprocess(shaderSourcePtr, shaderSource.Length, defines, include, out compilationErrors);
}
finally
{
if (shaderSourcePtr != IntPtr.Zero)
Marshal.FreeHGlobal(shaderSourcePtr);
}
}
/// <summary>
/// Preprocesses a shader or effect from a file on disk.
/// </summary>
/// <param name = "fileName">The name of the source file to compile.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string PreprocessFromFile(string fileName)
{
string errors = null;
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
if (!File.Exists(fileName))
{
throw new FileNotFoundException("Could not open the shader or effect file.", fileName);
}
string str = File.ReadAllText(fileName);
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException("fileName");
}
return Preprocess(Encoding.ASCII.GetBytes(str), null, null, out errors);
}
/// <summary>
/// Preprocesses a shader or effect from a file on disk.
/// </summary>
/// <param name = "fileName">The name of the source file to compile.</param>
/// <param name = "defines">A set of macros to define during preprocessing.</param>
/// <param name = "include">An interface for handling include files.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string PreprocessFromFile(string fileName, Macro[] defines, Include include)
{
string errors = null;
return PreprocessFromFile(fileName, defines, include, out errors);
}
/// <summary>
/// Preprocesses a shader or effect from a file on disk.
/// </summary>
/// <param name = "fileName">The name of the source file to compile.</param>
/// <param name = "defines">A set of macros to define during preprocessing.</param>
/// <param name = "include">An interface for handling include files.</param>
/// <param name = "compilationErrors">When the method completes, contains a string of compilation errors, or an empty string if preprocessing succeeded.</param>
/// <returns>The preprocessed shader source.</returns>
/// <unmanaged>HRESULT D3DXPreprocessShader([In] const void* pSrcData,[In] unsigned int SrcDataSize,[In, Buffer] const D3DXMACRO* pDefines,[In] ID3DXInclude* pInclude,[In] ID3DXBuffer** ppShaderText,[In] ID3DXBuffer** ppErrorMsgs)</unmanaged>
public static string PreprocessFromFile(string fileName, Macro[] defines, Include include, out string compilationErrors)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
if (!File.Exists(fileName))
{
throw new FileNotFoundException("Could not open the shader or effect file.", fileName);
}
return Preprocess(File.ReadAllText(fileName), defines, include, out compilationErrors);
}
/// <summary>
/// Gets the raw data of the compiled bytecode.
/// </summary>
public DataStream Data
{
get { return new DataStream(BufferPointer, BufferSize, true, true); }
}
/// <summary>
/// Read a compiled shader bytecode from a Stream and return a ShaderBytecode
/// </summary>
/// <param name = "stream"></param>
/// <returns></returns>
public static ShaderBytecode FromStream(Stream stream)
{
return new ShaderBytecode(stream);
}
/// <summary>
/// Read a compiled shader bytecode from a Stream and return a ShaderBytecode
/// </summary>
/// <param name = "fileName"></param>
/// <returns></returns>
public static ShaderBytecode FromFile(string fileName)
{
return new ShaderBytecode(File.ReadAllBytes(fileName));
}
internal static Macro[] PrepareMacros(Macro[] macros)
{
if (macros == null)
return null;
if (macros.Length == 0)
return null;
if (macros[macros.Length - 1].Name == null && macros[macros.Length - 1].Definition == null)
return macros;
var macroArray = new Macro[macros.Length + 1];
Array.Copy(macros, macroArray, macros.Length);
macroArray[macros.Length] = new Macro(null, null);
return macroArray;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (blob != null)
{
blob.Dispose();
blob = null;
}
if (constantTable != null)
{
constantTable.Dispose();
constantTable = null;
}
}
if (isOwner && BufferPointer != IntPtr.Zero)
{
Marshal.FreeHGlobal(BufferPointer);
BufferPointer = IntPtr.Zero;
BufferSize = 0;
}
}
private void CreateFromBuffer(byte[] buffer)
{
unsafe
{
fixed (void* pBuffer = &buffer[0])
CreateFromPointer((IntPtr)pBuffer, buffer.Length);
}
}
private void CreateFromPointer(IntPtr buffer, int sizeInBytes)
{
// D3DCommon.CreateBlob(sizeInBytes, this);
BufferPointer = Marshal.AllocHGlobal(sizeInBytes);
BufferSize = sizeInBytes;
isOwner = true;
Utilities.CopyMemory(BufferPointer, buffer, sizeInBytes);
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Net.Security;
using System.Security.Authentication.ExtendedProtection;
using System.Threading;
namespace System.Net
{
internal class NTAuthentication
{
static private ContextCallback s_InitializeCallback = new ContextCallback(InitializeCallback);
private bool _isServer;
private SafeFreeCredentials _credentialsHandle;
private SafeDeleteContext _securityContext;
private string _spn;
private string _clientSpecifiedSpn;
private int _tokenSize;
private Interop.SspiCli.ContextFlags _requestedContextFlags;
private Interop.SspiCli.ContextFlags _contextFlags;
private bool _isCompleted;
private string _protocolName;
private SecSizes _sizes;
private string _lastProtocolName;
private string _package;
private ChannelBinding _channelBinding;
// If set, no more calls should be made.
internal bool IsCompleted
{
get
{
return _isCompleted;
}
}
internal bool IsValidContext
{
get
{
return !(_securityContext == null || _securityContext.IsInvalid);
}
}
internal string AssociatedName
{
get
{
if (!(IsValidContext && IsCompleted))
{
throw new Win32Exception((int)Interop.SecurityStatus.InvalidHandle);
}
string name = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, _securityContext, Interop.SspiCli.ContextAttribute.Names) as string;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication: The context is associated with [" + name + "]");
}
return name;
}
}
internal bool IsConfidentialityFlag
{
get
{
return (_contextFlags & Interop.SspiCli.ContextFlags.Confidentiality) != 0;
}
}
internal bool IsIntegrityFlag
{
get
{
return (_contextFlags & (_isServer ? Interop.SspiCli.ContextFlags.AcceptIntegrity : Interop.SspiCli.ContextFlags.InitIntegrity)) != 0;
}
}
internal bool IsMutualAuthFlag
{
get
{
return (_contextFlags & Interop.SspiCli.ContextFlags.MutualAuth) != 0;
}
}
internal bool IsDelegationFlag
{
get
{
return (_contextFlags & Interop.SspiCli.ContextFlags.Delegate) != 0;
}
}
internal bool IsIdentifyFlag
{
get
{
return (_contextFlags & (_isServer ? Interop.SspiCli.ContextFlags.AcceptIdentify : Interop.SspiCli.ContextFlags.InitIdentify)) != 0;
}
}
internal string Spn
{
get
{
return _spn;
}
}
internal string ClientSpecifiedSpn
{
get
{
if (_clientSpecifiedSpn == null)
{
_clientSpecifiedSpn = GetClientSpecifiedSpn();
}
return _clientSpecifiedSpn;
}
}
//
// True indicates this instance is for Server and will use AcceptSecurityContext SSPI API.
//
internal bool IsServer
{
get
{
return _isServer;
}
}
internal bool IsKerberos
{
get
{
if (_lastProtocolName == null)
{
_lastProtocolName = ProtocolName;
}
return (object)_lastProtocolName == (object)NegotiationInfoClass.Kerberos;
}
}
internal bool IsNTLM
{
get
{
if (_lastProtocolName == null)
{
_lastProtocolName = ProtocolName;
}
return (object)_lastProtocolName == (object)NegotiationInfoClass.NTLM;
}
}
internal string ProtocolName
{
get
{
// Note: May return string.Empty if the auth is not done yet or failed.
if (_protocolName == null)
{
NegotiationInfoClass negotiationInfo = null;
if (IsValidContext)
{
negotiationInfo = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, _securityContext, Interop.SspiCli.ContextAttribute.NegotiationInfo) as NegotiationInfoClass;
if (IsCompleted)
{
if (negotiationInfo != null)
{
// Cache it only when it's completed.
_protocolName = negotiationInfo.AuthenticationPackage;
}
}
}
return negotiationInfo == null ? string.Empty : negotiationInfo.AuthenticationPackage;
}
return _protocolName;
}
}
internal SecSizes Sizes
{
get
{
if (!(IsCompleted && IsValidContext))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("NTAuthentication#{0}::MaxDataSize|The context is not completed or invalid.", LoggingHash.HashString(this));
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::MaxDataSize |The context is not completed or invalid.");
}
if (_sizes == null)
{
_sizes = SSPIWrapper.QueryContextAttributes(
GlobalSSPI.SSPIAuth,
_securityContext,
Interop.SspiCli.ContextAttribute.Sizes
) as SecSizes;
}
return _sizes;
}
}
//
// This overload does not attempt to impersonate because the caller either did it already or the original thread context is still preserved.
//
internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, Interop.SspiCli.ContextFlags requestedContextFlags, ChannelBinding channelBinding)
{
Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
}
private class InitializeCallbackContext
{
internal InitializeCallbackContext(NTAuthentication thisPtr, bool isServer, string package, NetworkCredential credential, string spn, Interop.SspiCli.ContextFlags requestedContextFlags, ChannelBinding channelBinding)
{
ThisPtr = thisPtr;
IsServer = isServer;
Package = package;
Credential = credential;
Spn = spn;
RequestedContextFlags = requestedContextFlags;
ChannelBinding = channelBinding;
}
internal readonly NTAuthentication ThisPtr;
internal readonly bool IsServer;
internal readonly string Package;
internal readonly NetworkCredential Credential;
internal readonly string Spn;
internal readonly Interop.SspiCli.ContextFlags RequestedContextFlags;
internal readonly ChannelBinding ChannelBinding;
}
private static void InitializeCallback(object state)
{
InitializeCallbackContext context = (InitializeCallbackContext)state;
context.ThisPtr.Initialize(context.IsServer, context.Package, context.Credential, context.Spn, context.RequestedContextFlags, context.ChannelBinding);
}
private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, Interop.SspiCli.ContextFlags requestedContextFlags, ChannelBinding channelBinding)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::.ctor() package:" + LoggingHash.ObjectToString(package) + " spn:" + LoggingHash.ObjectToString(spn) + " flags :" + requestedContextFlags.ToString());
}
_tokenSize = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken;
_isServer = isServer;
_spn = spn;
_securityContext = null;
_requestedContextFlags = requestedContextFlags;
_package = package;
_channelBinding = channelBinding;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("Peer SPN-> '" + _spn + "'");
}
//
// Check if we're using DefaultCredentials.
//
Debug.Assert(CredentialCache.DefaultCredentials == CredentialCache.DefaultNetworkCredentials);
if (credential == CredentialCache.DefaultCredentials)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::.ctor(): using DefaultCredentials");
}
_credentialsHandle = SSPIWrapper.AcquireDefaultCredential(
GlobalSSPI.SSPIAuth,
package,
(_isServer ? Interop.SspiCli.CredentialUse.Inbound : Interop.SspiCli.CredentialUse.Outbound));
}
else
{
unsafe
{
SafeSspiAuthDataHandle authData = null;
try
{
Interop.SecurityStatus result = Interop.SspiCli.SspiEncodeStringsAsAuthIdentity(
credential.UserName, credential.Domain,
credential.Password, out authData);
if (result != Interop.SecurityStatus.OK)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.PrintError(
NetEventSource.ComponentType.Security,
SR.Format(
SR.net_log_operation_failed_with_error,
"SspiEncodeStringsAsAuthIdentity()",
String.Format(CultureInfo.CurrentCulture, "0x{0:X}", (int)result)));
}
throw new Win32Exception((int)result);
}
_credentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth,
package, (_isServer ? Interop.SspiCli.CredentialUse.Inbound : Interop.SspiCli.CredentialUse.Outbound), ref authData);
}
finally
{
if (authData != null)
{
authData.Dispose();
}
}
}
}
}
// This will return a client token when conducted authentication on server side.
// This token can be used for impersonation. We use it to create a WindowsIdentity and hand it out to the server app.
internal SecurityContextTokenHandle GetContextToken(out Interop.SecurityStatus status)
{
if (!(IsCompleted && IsValidContext))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("NTAuthentication#{0}::GetContextToken|Should be called only when completed with success, currently is not!", LoggingHash.HashString(this));
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::GetContextToken |Should be called only when completed with success, currently is not!");
}
if (!IsServer)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("NTAuthentication#{0}::GetContextToken|The method must not be called by the client side!", LoggingHash.HashString(this));
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::GetContextToken |The method must not be called by the client side!");
}
if (!IsValidContext)
{
throw new Win32Exception((int)Interop.SecurityStatus.InvalidHandle);
}
SecurityContextTokenHandle token = null;
status = (Interop.SecurityStatus)SSPIWrapper.QuerySecurityContextToken(
GlobalSSPI.SSPIAuth,
_securityContext,
out token);
return token;
}
internal SecurityContextTokenHandle GetContextToken()
{
Interop.SecurityStatus status;
SecurityContextTokenHandle token = GetContextToken(out status);
if (status != Interop.SecurityStatus.OK)
{
throw new Win32Exception((int)status);
}
return token;
}
internal void CloseContext()
{
if (_securityContext != null && !_securityContext.IsClosed)
{
_securityContext.Dispose();
}
}
// Accepts an incoming binary security blob and returns an outgoing binary security blob.
internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out Interop.SecurityStatus statusCode)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", ((incomingBlob == null) ? "0" : incomingBlob.Length.ToString(NumberFormatInfo.InvariantInfo)) + " bytes");
}
var list = new List<SecurityBuffer>(2);
if (incomingBlob != null)
{
list.Add(new SecurityBuffer(incomingBlob, SecurityBufferType.Token));
}
if (_channelBinding != null)
{
list.Add(new SecurityBuffer(_channelBinding));
}
SecurityBuffer[] inSecurityBufferArray = null;
if (list.Count > 0)
{
inSecurityBufferArray = list.ToArray();
}
var outSecurityBuffer = new SecurityBuffer(_tokenSize, SecurityBufferType.Token);
bool firstTime = _securityContext == null;
try
{
if (!_isServer)
{
// client session
statusCode = (Interop.SecurityStatus)SSPIWrapper.InitializeSecurityContext(
GlobalSSPI.SSPIAuth,
_credentialsHandle,
ref _securityContext,
_spn,
_requestedContextFlags,
Interop.SspiCli.Endianness.Network,
inSecurityBufferArray,
outSecurityBuffer,
ref _contextFlags);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.InitializeSecurityContext() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
}
if (statusCode == Interop.SecurityStatus.CompleteNeeded)
{
var inSecurityBuffers = new SecurityBuffer[1];
inSecurityBuffers[0] = outSecurityBuffer;
statusCode = (Interop.SecurityStatus)SSPIWrapper.CompleteAuthToken(
GlobalSSPI.SSPIAuth,
ref _securityContext,
inSecurityBuffers);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.CompleteAuthToken() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
}
outSecurityBuffer.token = null;
}
}
else
{
// Server session.
statusCode = (Interop.SecurityStatus)SSPIWrapper.AcceptSecurityContext(
GlobalSSPI.SSPIAuth,
_credentialsHandle,
ref _securityContext,
_requestedContextFlags,
Interop.SspiCli.Endianness.Network,
inSecurityBufferArray,
outSecurityBuffer,
ref _contextFlags);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.AcceptSecurityContext() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
}
}
}
finally
{
//
// Assuming the ISC or ASC has referenced the credential on the first successful call,
// we want to decrement the effective ref count by "disposing" it.
// The real dispose will happen when the security context is closed.
// Note if the first call was not successful the handle is physically destroyed here.
//
if (firstTime && _credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
}
if (((int)statusCode & unchecked((int)0x80000000)) != 0)
{
CloseContext();
_isCompleted = true;
if (throwOnError)
{
var exception = new Win32Exception((int)statusCode);
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", "Win32Exception:" + exception);
}
throw exception;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", "null statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")");
}
return null;
}
else if (firstTime && _credentialsHandle != null)
{
// Cache until it is pushed out by newly incoming handles.
SSPIHandleCache.CacheCredential(_credentialsHandle);
}
// The return value from SSPI will tell us correctly if the
// handshake is over or not: http://msdn.microsoft.com/library/psdk/secspi/sspiref_67p0.htm
// we also have to consider the case in which SSPI formed a new context, in this case we're done as well.
if (statusCode == Interop.SecurityStatus.OK)
{
// Success.
if (statusCode != Interop.SecurityStatus.OK)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("NTAuthentication#{0}::GetOutgoingBlob()|statusCode:[0x{1:x8}] ({2}) m_SecurityContext#{3}::Handle:[{4}] [STATUS != OK]", LoggingHash.HashString(this), (int)statusCode, statusCode, LoggingHash.HashString(_securityContext), LoggingHash.ObjectToString(_securityContext));
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob()|statusCode:[0x" + ((int)statusCode).ToString("x8") + "] (" + statusCode + ") m_SecurityContext#" + LoggingHash.HashString(_securityContext) + "::Handle:[" + LoggingHash.ObjectToString(_securityContext) + "] [STATUS != OK]");
}
_isCompleted = true;
}
else if (GlobalLog.IsEnabled)
{
// We need to continue.
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob() need continue statusCode:[0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + "] (" + statusCode.ToString() + ") m_SecurityContext#" + LoggingHash.HashString(_securityContext) + "::Handle:" + LoggingHash.ObjectToString(_securityContext) + "]");
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("NTAuthentication#" + LoggingHash.HashString(this) + "::GetOutgoingBlob", "IsCompleted:" + IsCompleted.ToString());
}
return outSecurityBuffer.token;
}
internal int Encrypt(byte[] buffer, int offset, int count, ref byte[] output, uint sequenceNumber)
{
SecSizes sizes = Sizes;
try
{
int maxCount = checked(Int32.MaxValue - 4 - sizes.BlockSize - sizes.SecurityTrailer);
if (count > maxCount || count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.net_io_out_range, maxCount));
}
}
catch (Exception e)
{
if (!ExceptionCheck.IsFatal(e))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range.");
}
throw;
}
int resultSize = count + sizes.SecurityTrailer + sizes.BlockSize;
if (output == null || output.Length < resultSize + 4)
{
output = new byte[resultSize + 4];
}
// Make a copy of user data for in-place encryption.
Buffer.BlockCopy(buffer, offset, output, 4 + sizes.SecurityTrailer, count);
// Prepare buffers TOKEN(signature), DATA and Padding.
var securityBuffer = new SecurityBuffer[3];
securityBuffer[0] = new SecurityBuffer(output, 4, sizes.SecurityTrailer, SecurityBufferType.Token);
securityBuffer[1] = new SecurityBuffer(output, 4 + sizes.SecurityTrailer, count, SecurityBufferType.Data);
securityBuffer[2] = new SecurityBuffer(output, 4 + sizes.SecurityTrailer + count, sizes.BlockSize, SecurityBufferType.Padding);
int errorCode;
if (IsConfidentialityFlag)
{
errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPIAuth, _securityContext, securityBuffer, sequenceNumber);
}
else
{
if (IsNTLM)
{
securityBuffer[1].type |= SecurityBufferType.ReadOnlyFlag;
}
errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, _securityContext, securityBuffer, 0);
}
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::Encrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
}
throw new Win32Exception(errorCode);
}
// Compacting the result.
resultSize = securityBuffer[0].size;
bool forceCopy = false;
if (resultSize != sizes.SecurityTrailer)
{
forceCopy = true;
Buffer.BlockCopy(output, securityBuffer[1].offset, output, 4 + resultSize, securityBuffer[1].size);
}
resultSize += securityBuffer[1].size;
if (securityBuffer[2].size != 0 && (forceCopy || resultSize != (count + sizes.SecurityTrailer)))
{
Buffer.BlockCopy(output, securityBuffer[2].offset, output, 4 + resultSize, securityBuffer[2].size);
}
resultSize += securityBuffer[2].size;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal int Decrypt(byte[] payload, int offset, int count, out int newOffset, uint expectedSeqNumber)
{
if (offset < 0 || offset > (payload == null ? 0 : payload.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(this) + "::Decrypt", "Argument 'offset' out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::Decrypt", "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (payload == null ? 0 : payload.Length - offset))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(this) + "::Decrypt", "Argument 'count' out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::Decrypt", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
if (IsNTLM)
{
return DecryptNtlm(payload, offset, count, out newOffset, expectedSeqNumber);
}
//
// Kerberos and up
//
var securityBuffer = new SecurityBuffer[2];
securityBuffer[0] = new SecurityBuffer(payload, offset, count, SecurityBufferType.Stream);
securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.Data);
int errorCode;
if (IsConfidentialityFlag)
{
errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, _securityContext, securityBuffer, expectedSeqNumber);
}
else
{
errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, _securityContext, securityBuffer, expectedSeqNumber);
}
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
}
throw new Win32Exception(errorCode);
}
if (securityBuffer[1].type != SecurityBufferType.Data)
{
throw new InternalException();
}
newOffset = securityBuffer[1].offset;
return securityBuffer[1].size;
}
private string GetClientSpecifiedSpn()
{
if (!(IsValidContext && IsCompleted))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication: Trying to get the client SPN before handshaking is done!");
}
Debug.Fail("NTAuthentication: Trying to get the client SPN before handshaking is done!");
}
string spn = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, _securityContext,
Interop.SspiCli.ContextAttribute.ClientSpecifiedSpn) as string;
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication: The client specified SPN is [" + spn + "]");
}
return spn;
}
private int DecryptNtlm(byte[] payload, int offset, int count, out int newOffset, uint expectedSeqNumber)
{
// For the most part the arguments are verified in Encrypt().
if (count < 16)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("NTAuthentication#" + LoggingHash.HashString(this) + "::DecryptNtlm", "Argument 'count' out of range.");
}
Debug.Fail("NTAuthentication#" + LoggingHash.HashString(this) + "::DecryptNtlm", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
var securityBuffer = new SecurityBuffer[2];
securityBuffer[0] = new SecurityBuffer(payload, offset, 16, SecurityBufferType.Token);
securityBuffer[1] = new SecurityBuffer(payload, offset + 16, count - 16, SecurityBufferType.Data);
int errorCode;
SecurityBufferType realDataType = SecurityBufferType.Data;
if (IsConfidentialityFlag)
{
errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, _securityContext, securityBuffer, expectedSeqNumber);
}
else
{
realDataType |= SecurityBufferType.ReadOnlyFlag;
securityBuffer[1].type = realDataType;
errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, _securityContext, securityBuffer, expectedSeqNumber);
}
if (errorCode != 0)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("NTAuthentication#" + LoggingHash.HashString(this) + "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo));
}
throw new Win32Exception(errorCode);
}
if (securityBuffer[1].type != realDataType)
{
throw new InternalException();
}
newOffset = securityBuffer[1].offset;
return securityBuffer[1].size;
}
}
}
| |
//
// DatabaseImportManager.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Unix;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration.Schema;
using Banshee.ServiceStack;
using Banshee.Streaming;
namespace Banshee.Collection.Database
{
public class DatabaseImportManager : ImportManager
{
// This is a list of known media files that we may encounter. The extensions
// in this list do not mean they are actually supported - this list is just
// used to see if we should allow the file to be processed by TagLib. The
// point is to rule out, at the path level, files that we won't support.
public static readonly Banshee.IO.ExtensionSet WhiteListFileExtensions = new Banshee.IO.ExtensionSet (
"3g2", "3gp", "3gp2", "3gpp", "aac", "ac3", "aif", "aifc",
"aiff", "al", "alaw", "ape", "asf", "asx", "au", "avi",
"cda", "cdr", "divx", "dv", "flac", "flv", "gvi", "gvp",
"m1v", "m21", "m2p", "m2v", "m4a", "m4b", "m4e", "m4p",
"m4u", "m4v", "mp+", "mid", "midi", "mjp", "mkv", "moov",
"mov", "movie","mp1", "mp2", "mp21", "mp3", "mp4", "mpa",
"mpc", "mpe", "mpeg", "mpg", "mpga", "mpp", "mpu", "mpv",
"mpv2", "oga", "ogg", "ogv", "ogm", "omf", "qt", "ra",
"ram", "raw", "rm", "rmvb", "rts", "smil", "swf", "tivo",
"u", "vfw", "vob", "wav", "wave", "wax", "wm", "wma",
"wmd", "wmv", "wmx", "wv", "wvc", "wvx", "yuv", "f4v",
"f4a", "f4b", "669", "it", "med", "mod", "mol", "mtm",
"nst", "s3m", "stm", "ult", "wow", "xm", "xnm", "spx",
"ts"
);
public static bool IsWhiteListedFile (string path)
{
return WhiteListFileExtensions.IsMatchingFile (path);
}
public delegate PrimarySource TrackPrimarySourceChooser (DatabaseTrackInfo track);
private TrackPrimarySourceChooser trackPrimarySourceChooser;
private Dictionary<int, int> counts;
private ErrorSource error_source;
private int [] primary_source_ids;
private string base_directory;
private bool force_copy;
public event DatabaseImportResultHandler ImportResult;
public DatabaseImportManager (PrimarySource psource) :
this (psource.ErrorSource, delegate { return psource; }, new int [] {psource.DbId}, psource.BaseDirectory)
{
}
public DatabaseImportManager (ErrorSource error_source, TrackPrimarySourceChooser chooser,
int [] primarySourceIds, string baseDirectory) : this (chooser)
{
this.error_source = error_source;
primary_source_ids = primarySourceIds;
base_directory = baseDirectory;
}
public DatabaseImportManager (TrackPrimarySourceChooser chooser)
{
trackPrimarySourceChooser = chooser;
counts = new Dictionary<int, int> ();
}
protected virtual ErrorSource ErrorSource {
get { return error_source; }
}
protected virtual int [] PrimarySourceIds {
get { return primary_source_ids; }
set { primary_source_ids = value; }
}
protected virtual string BaseDirectory {
get { return base_directory; }
set { base_directory = value; }
}
protected virtual bool ForceCopy {
get { return force_copy; }
set { force_copy = value; }
}
protected override void OnImportRequested (string path)
{
try {
DatabaseTrackInfo track = ImportTrack (path);
if (track != null && track.TrackId > 0) {
UpdateProgress (String.Format ("{0} - {1}",
track.DisplayArtistName, track.DisplayTrackTitle));
} else {
UpdateProgress (null);
}
OnImportResult (track, path, null);
} catch (Exception e) {
LogError (path, e);
UpdateProgress (null);
OnImportResult (null, path, e);
}
}
protected virtual void OnImportResult (DatabaseTrackInfo track, string path, Exception error)
{
DatabaseImportResultHandler handler = ImportResult;
if (handler != null) {
handler (this, new DatabaseImportResultArgs (track, path, error));
}
}
public DatabaseTrackInfo ImportTrack (string path)
{
return ImportTrack (new SafeUri (path));
}
public DatabaseTrackInfo ImportTrack (SafeUri uri)
{
if (!IsWhiteListedFile (uri.AbsoluteUri)) {
return null;
}
if (DatabaseTrackInfo.ContainsUri (uri, PrimarySourceIds)) {
// TODO add DatabaseTrackInfo.SyncedStamp property, and if the file has been
// updated since the last sync, fetch its metadata into the db.
return null;
}
DatabaseTrackInfo track = null;
// TODO note, there is deadlock potential here b/c of locking of shared commands and blocking
// because of transactions. Needs to be fixed in HyenaDatabaseConnection.
ServiceManager.DbConnection.BeginTransaction ();
try {
track = new DatabaseTrackInfo ();
track.Uri = uri;
using (var file = StreamTagger.ProcessUri (uri)) {
StreamTagger.TrackInfoMerge (track, file, false, true);
}
track.PrimarySource = trackPrimarySourceChooser (track);
bool save_track = true;
if (track.PrimarySource is Banshee.Library.LibrarySource) {
save_track = track.CopyToLibraryIfAppropriate (force_copy);
}
if (save_track) {
track.Save (false);
}
ServiceManager.DbConnection.CommitTransaction ();
} catch (Exception) {
ServiceManager.DbConnection.RollbackTransaction ();
throw;
}
counts[track.PrimarySourceId] = counts.ContainsKey (track.PrimarySourceId) ? counts[track.PrimarySourceId] + 1 : 1;
// Reload every 20% or every 250 tracks, whatever is more (eg at most reload 5 times during an import)
if (counts[track.PrimarySourceId] >= Math.Max (TotalCount/5, 250)) {
counts[track.PrimarySourceId] = 0;
track.PrimarySource.NotifyTracksAdded ();
}
return track;
}
private void LogError (string path, Exception e)
{
LogError (path, e.Message);
if (!(e is TagLib.CorruptFileException) && !(e is TagLib.UnsupportedFormatException)) {
Log.DebugFormat ("Full import exception: {0}", e.ToString ());
}
}
private void LogError (string path, string msg)
{
ErrorSource.AddMessage (path, msg);
Log.Error (path, msg, false);
}
public void NotifyAllSources ()
{
foreach (int primary_source_id in counts.Keys) {
PrimarySource.GetById (primary_source_id).NotifyTracksAdded ();
}
counts.Clear ();
}
protected override void OnFinished ()
{
NotifyAllSources ();
base.OnFinished ();
}
}
}
| |
using Avalonia.Input.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Data;
using Avalonia.Layout;
using Avalonia.Utilities;
using Avalonia.Controls.Metadata;
namespace Avalonia.Controls
{
/// <summary>
/// Represents a control that can be used to display or edit unformatted text.
/// </summary>
[PseudoClasses(":empty")]
public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
{
public static KeyGesture CutGesture { get; } = AvaloniaLocator.Current
.GetService<PlatformHotkeyConfiguration>()?.Cut.FirstOrDefault();
public static KeyGesture CopyGesture { get; } = AvaloniaLocator.Current
.GetService<PlatformHotkeyConfiguration>()?.Copy.FirstOrDefault();
public static KeyGesture PasteGesture { get; } = AvaloniaLocator.Current
.GetService<PlatformHotkeyConfiguration>()?.Paste.FirstOrDefault();
public static readonly StyledProperty<bool> AcceptsReturnProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsReturn));
public static readonly StyledProperty<bool> AcceptsTabProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(AcceptsTab));
public static readonly DirectProperty<TextBox, int> CaretIndexProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(CaretIndex),
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
public static readonly StyledProperty<char> PasswordCharProperty =
AvaloniaProperty.Register<TextBox, char>(nameof(PasswordChar));
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextBox, IBrush>(nameof(SelectionBrushProperty));
public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty =
AvaloniaProperty.Register<TextBox, IBrush>(nameof(SelectionForegroundBrushProperty));
public static readonly StyledProperty<IBrush> CaretBrushProperty =
AvaloniaProperty.Register<TextBox, IBrush>(nameof(CaretBrushProperty));
public static readonly DirectProperty<TextBox, int> SelectionStartProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionStart),
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextBox, int> SelectionEndProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionEnd),
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
public static readonly StyledProperty<int> MaxLengthProperty =
AvaloniaProperty.Register<TextBox, int>(nameof(MaxLength), defaultValue: 0);
public static readonly DirectProperty<TextBox, string> TextProperty =
TextBlock.TextProperty.AddOwnerWithDataValidation<TextBox>(
o => o.Text,
(o, v) => o.Text = v,
defaultBindingMode: BindingMode.TwoWay,
enableDataValidation: true);
public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
/// <summary>
/// Defines the <see cref="HorizontalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
ContentControl.HorizontalContentAlignmentProperty.AddOwner<TextBox>();
/// <summary>
/// Defines the <see cref="VerticalAlignment"/> property.
/// </summary>
public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
ContentControl.VerticalContentAlignmentProperty.AddOwner<TextBox>();
public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
TextBlock.TextWrappingProperty.AddOwner<TextBox>();
public static readonly StyledProperty<string> WatermarkProperty =
AvaloniaProperty.Register<TextBox, string>(nameof(Watermark));
public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(UseFloatingWatermark));
public static readonly DirectProperty<TextBox, string> NewLineProperty =
AvaloniaProperty.RegisterDirect<TextBox, string>(nameof(NewLine),
textbox => textbox.NewLine, (textbox, newline) => textbox.NewLine = newline);
public static readonly StyledProperty<object> InnerLeftContentProperty =
AvaloniaProperty.Register<TextBox, object>(nameof(InnerLeftContent));
public static readonly StyledProperty<object> InnerRightContentProperty =
AvaloniaProperty.Register<TextBox, object>(nameof(InnerRightContent));
public static readonly StyledProperty<bool> RevealPasswordProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(RevealPassword));
public static readonly DirectProperty<TextBox, bool> CanCutProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>(
nameof(CanCut),
o => o.CanCut);
public static readonly DirectProperty<TextBox, bool> CanCopyProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>(
nameof(CanCopy),
o => o.CanCopy);
public static readonly DirectProperty<TextBox, bool> CanPasteProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>(
nameof(CanPaste),
o => o.CanPaste);
public static readonly StyledProperty<bool> IsUndoEnabledProperty =
AvaloniaProperty.Register<TextBox, bool>(
nameof(IsUndoEnabled),
defaultValue: true);
public static readonly DirectProperty<TextBox, int> UndoLimitProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(UndoLimit),
o => o.UndoLimit,
(o, v) => o.UndoLimit = v,
unsetValue: -1);
public static readonly RoutedEvent<RoutedEventArgs> CopyingToClipboardEvent =
RoutedEvent.Register<TextBox, RoutedEventArgs>(
"CopyingToClipboard", RoutingStrategies.Bubble);
public static readonly RoutedEvent<RoutedEventArgs> CuttingToClipboardEvent =
RoutedEvent.Register<TextBox, RoutedEventArgs>(
"CuttingToClipboard", RoutingStrategies.Bubble);
public static readonly RoutedEvent<RoutedEventArgs> PastingFromClipboardEvent =
RoutedEvent.Register<TextBox, RoutedEventArgs>(
"PastingFromClipboard", RoutingStrategies.Bubble);
readonly struct UndoRedoState : IEquatable<UndoRedoState>
{
public string Text { get; }
public int CaretPosition { get; }
public UndoRedoState(string text, int caretPosition)
{
Text = text;
CaretPosition = caretPosition;
}
public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
public override bool Equals(object obj) => obj is UndoRedoState other && Equals(other);
public override int GetHashCode() => Text.GetHashCode();
}
private string _text;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private TextPresenter _presenter;
private TextBoxTextInputMethodClient _imClient = new TextBoxTextInputMethodClient();
private UndoRedoHelper<UndoRedoState> _undoRedoHelper;
private bool _isUndoingRedoing;
private bool _ignoreTextChanges;
private bool _canCut;
private bool _canCopy;
private bool _canPaste;
private string _newLine = Environment.NewLine;
private static readonly string[] invalidCharacters = new String[1] { "\u007f" };
private int _selectedTextChangesMadeSinceLastUndoSnapshot;
private bool _hasDoneSnapshotOnce;
private const int _maxCharsBeforeUndoSnapshot = 7;
static TextBox()
{
FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
TextInputMethodClientRequestedEvent.AddClassHandler<TextBox>((tb, e) =>
{
e.Client = tb._imClient;
});
}
public TextBox()
{
var horizontalScrollBarVisibility = Observable.CombineLatest(
this.GetObservable(AcceptsReturnProperty),
this.GetObservable(TextWrappingProperty),
(acceptsReturn, wrapping) =>
{
if (wrapping != TextWrapping.NoWrap)
{
return ScrollBarVisibility.Disabled;
}
return acceptsReturn ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden;
});
this.Bind(
ScrollViewer.HorizontalScrollBarVisibilityProperty,
horizontalScrollBarVisibility,
BindingPriority.Style);
_undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = false;
UpdatePseudoclasses();
}
public bool AcceptsReturn
{
get { return GetValue(AcceptsReturnProperty); }
set { SetValue(AcceptsReturnProperty, value); }
}
public bool AcceptsTab
{
get { return GetValue(AcceptsTabProperty); }
set { SetValue(AcceptsTabProperty, value); }
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
UndoRedoState state;
if (IsUndoEnabled && _undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
_undoRedoHelper.UpdateLastState();
}
}
public bool IsReadOnly
{
get { return GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
public char PasswordChar
{
get => GetValue(PasswordCharProperty);
set => SetValue(PasswordCharProperty, value);
}
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
public IBrush SelectionForegroundBrush
{
get => GetValue(SelectionForegroundBrushProperty);
set => SetValue(SelectionForegroundBrushProperty, value);
}
public IBrush CaretBrush
{
get => GetValue(CaretBrushProperty);
set => SetValue(CaretBrushProperty, value);
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
var changed = SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
if (changed)
{
UpdateCommandStates();
}
if (SelectionStart == SelectionEnd)
{
CaretIndex = SelectionStart;
}
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
var changed = SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
if (changed)
{
UpdateCommandStates();
}
if (SelectionStart == SelectionEnd)
{
CaretIndex = SelectionEnd;
}
}
}
public int MaxLength
{
get { return GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}
[Content]
public string Text
{
get { return _text; }
set
{
if (!_ignoreTextChanges)
{
var caretIndex = CaretIndex;
SelectionStart = CoerceCaretIndex(SelectionStart, value);
SelectionEnd = CoerceCaretIndex(SelectionEnd, value);
CaretIndex = CoerceCaretIndex(caretIndex, value);
if (SetAndRaise(TextProperty, ref _text, value) && IsUndoEnabled && !_isUndoingRedoing)
{
_undoRedoHelper.Clear();
SnapshotUndoRedo(); // so we always have an initial state
}
}
}
}
public string SelectedText
{
get { return GetSelection(); }
set
{
if (string.IsNullOrEmpty(value))
{
_selectedTextChangesMadeSinceLastUndoSnapshot++;
SnapshotUndoRedo(ignoreChangeCount: false);
DeleteSelection();
}
else
{
HandleTextInput(value);
}
}
}
/// <summary>
/// Gets or sets the horizontal alignment of the content within the control.
/// </summary>
public HorizontalAlignment HorizontalContentAlignment
{
get { return GetValue(HorizontalContentAlignmentProperty); }
set { SetValue(HorizontalContentAlignmentProperty, value); }
}
/// <summary>
/// Gets or sets the vertical alignment of the content within the control.
/// </summary>
public VerticalAlignment VerticalContentAlignment
{
get { return GetValue(VerticalContentAlignmentProperty); }
set { SetValue(VerticalContentAlignmentProperty, value); }
}
public TextAlignment TextAlignment
{
get { return GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public string Watermark
{
get { return GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
public bool UseFloatingWatermark
{
get { return GetValue(UseFloatingWatermarkProperty); }
set { SetValue(UseFloatingWatermarkProperty, value); }
}
public object InnerLeftContent
{
get { return GetValue(InnerLeftContentProperty); }
set { SetValue(InnerLeftContentProperty, value); }
}
public object InnerRightContent
{
get { return GetValue(InnerRightContentProperty); }
set { SetValue(InnerRightContentProperty, value); }
}
public bool RevealPassword
{
get { return GetValue(RevealPasswordProperty); }
set { SetValue(RevealPasswordProperty, value); }
}
public TextWrapping TextWrapping
{
get { return GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
/// <summary>
/// Gets or sets which characters are inserted when Enter is pressed. Default: <see cref="Environment.NewLine"/>
/// </summary>
public string NewLine
{
get { return _newLine; }
set { SetAndRaise(NewLineProperty, ref _newLine, value); }
}
/// <summary>
/// Clears the current selection, maintaining the <see cref="CaretIndex"/>
/// </summary>
public void ClearSelection()
{
SelectionStart = SelectionEnd = CaretIndex;
}
/// <summary>
/// Property for determining if the Cut command can be executed.
/// </summary>
public bool CanCut
{
get { return _canCut; }
private set { SetAndRaise(CanCutProperty, ref _canCut, value); }
}
/// <summary>
/// Property for determining if the Copy command can be executed.
/// </summary>
public bool CanCopy
{
get { return _canCopy; }
private set { SetAndRaise(CanCopyProperty, ref _canCopy, value); }
}
/// <summary>
/// Property for determining if the Paste command can be executed.
/// </summary>
public bool CanPaste
{
get { return _canPaste; }
private set { SetAndRaise(CanPasteProperty, ref _canPaste, value); }
}
/// <summary>
/// Property for determining whether undo/redo is enabled
/// </summary>
public bool IsUndoEnabled
{
get { return GetValue(IsUndoEnabledProperty); }
set { SetValue(IsUndoEnabledProperty, value); }
}
public int UndoLimit
{
get { return _undoRedoHelper.Limit; }
set
{
if (_undoRedoHelper.Limit != value)
{
// can't use SetAndRaise due to using _undoRedoHelper.Limit
// (can't send a ref of a property to SetAndRaise),
// so use RaisePropertyChanged instead.
var oldValue = _undoRedoHelper.Limit;
_undoRedoHelper.Limit = value;
RaisePropertyChanged(UndoLimitProperty, oldValue, value);
}
// from docs at
// https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
// "Setting UndoLimit clears the undo queue."
_undoRedoHelper.Clear();
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = false;
}
}
public event EventHandler<RoutedEventArgs> CopyingToClipboard
{
add => AddHandler(CopyingToClipboardEvent, value);
remove => RemoveHandler(CopyingToClipboardEvent, value);
}
public event EventHandler<RoutedEventArgs> CuttingToClipboard
{
add => AddHandler(CuttingToClipboardEvent, value);
remove => RemoveHandler(CuttingToClipboardEvent, value);
}
public event EventHandler<RoutedEventArgs> PastingFromClipboard
{
add => AddHandler(PastingFromClipboardEvent, value);
remove => RemoveHandler(PastingFromClipboardEvent, value);
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
_presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
_imClient.SetPresenter(_presenter);
if (IsFocused)
{
_presenter?.ShowCaret();
}
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == TextProperty)
{
UpdatePseudoclasses();
UpdateCommandStates();
}
else if (change.Property == IsUndoEnabledProperty && change.NewValue.GetValueOrDefault<bool>() == false)
{
// from docs at
// https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.primitives.textboxbase.isundoenabled:
// "Setting this property to false clears the undo stack.
// Therefore, if you disable undo and then re-enable it, undo commands still do not work
// because the undo stack was emptied when you disabled undo."
_undoRedoHelper.Clear();
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = false;
}
}
private void UpdateCommandStates()
{
var text = GetSelection();
var isSelectionNullOrEmpty = string.IsNullOrEmpty(text);
CanCopy = !IsPasswordBox && !isSelectionNullOrEmpty;
CanCut = !IsPasswordBox && !isSelectionNullOrEmpty && !IsReadOnly;
CanPaste = !IsReadOnly;
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
// when navigating to a textbox via the tab key, select all text if
// 1) this textbox is *not* a multiline textbox
// 2) this textbox has any text to select
if (e.NavigationMethod == NavigationMethod.Tab &&
!AcceptsReturn &&
Text?.Length > 0)
{
SelectAll();
}
UpdateCommandStates();
_presenter?.ShowCaret();
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if ((ContextFlyout == null || !ContextFlyout.IsOpen) &&
(ContextMenu == null || !ContextMenu.IsOpen))
{
ClearSelection();
RevealPassword = false;
}
UpdateCommandStates();
_presenter?.HideCaret();
}
protected override void OnTextInput(TextInputEventArgs e)
{
if (!e.Handled)
{
HandleTextInput(e.Text);
e.Handled = true;
}
}
private void HandleTextInput(string input)
{
if (IsReadOnly)
{
return;
}
input = RemoveInvalidCharacters(input);
if (string.IsNullOrEmpty(input))
{
return;
}
_selectedTextChangesMadeSinceLastUndoSnapshot++;
SnapshotUndoRedo(ignoreChangeCount: false);
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
int newLength = input.Length + text.Length - Math.Abs(SelectionStart - SelectionEnd);
if (MaxLength > 0 && newLength > MaxLength)
{
input = input.Remove(Math.Max(0, input.Length - (newLength - MaxLength)));
}
if (!string.IsNullOrEmpty(input))
{
DeleteSelection();
caretIndex = CaretIndex;
text = Text ?? string.Empty;
SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex));
CaretIndex += input.Length;
ClearSelection();
if (IsUndoEnabled)
{
_undoRedoHelper.DiscardRedo();
}
}
}
public string RemoveInvalidCharacters(string text)
{
for (var i = 0; i < invalidCharacters.Length; i++)
{
text = text.Replace(invalidCharacters[i], string.Empty);
}
return text;
}
public async void Cut()
{
var text = GetSelection();
if (string.IsNullOrEmpty(text))
{
return;
}
var eventArgs = new RoutedEventArgs(CuttingToClipboardEvent);
RaiseEvent(eventArgs);
if (!eventArgs.Handled)
{
SnapshotUndoRedo();
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(text);
DeleteSelection();
}
}
public async void Copy()
{
var text = GetSelection();
if (string.IsNullOrEmpty(text))
{
return;
}
var eventArgs = new RoutedEventArgs(CopyingToClipboardEvent);
RaiseEvent(eventArgs);
if (!eventArgs.Handled)
{
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(text);
}
}
public async void Paste()
{
var eventArgs = new RoutedEventArgs(PastingFromClipboardEvent);
RaiseEvent(eventArgs);
if (eventArgs.Handled)
{
return;
}
var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
if (string.IsNullOrEmpty(text))
{
return;
}
SnapshotUndoRedo();
HandleTextInput(text);
}
protected override void OnKeyDown(KeyEventArgs e)
{
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
bool movement = false;
bool selection = false;
bool handled = false;
var modifiers = e.KeyModifiers;
var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
bool DetectSelection() => e.KeyModifiers.HasAllFlags(keymap.SelectionModifiers);
if (Match(keymap.SelectAll))
{
SelectAll();
handled = true;
}
else if (Match(keymap.Copy))
{
if (!IsPasswordBox)
{
Copy();
}
handled = true;
}
else if (Match(keymap.Cut))
{
if (!IsPasswordBox)
{
Cut();
}
handled = true;
}
else if (Match(keymap.Paste))
{
Paste();
handled = true;
}
else if (Match(keymap.Undo) && IsUndoEnabled)
{
try
{
SnapshotUndoRedo();
_isUndoingRedoing = true;
_undoRedoHelper.Undo();
}
finally
{
_isUndoingRedoing = false;
}
handled = true;
}
else if (Match(keymap.Redo) && IsUndoEnabled)
{
try
{
_isUndoingRedoing = true;
_undoRedoHelper.Redo();
}
finally
{
_isUndoingRedoing = false;
}
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfDocument))
{
MoveHome(true);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfDocument))
{
MoveEnd(true);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfLine))
{
MoveHome(false);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfLine))
{
MoveEnd(false);
movement = true;
selection = false;
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfDocumentWithSelection))
{
MoveHome(true);
movement = true;
selection = true;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfDocumentWithSelection))
{
MoveEnd(true);
movement = true;
selection = true;
handled = true;
}
else if (Match(keymap.MoveCursorToTheStartOfLineWithSelection))
{
MoveHome(false);
movement = true;
selection = true;
handled = true;
}
else if (Match(keymap.MoveCursorToTheEndOfLineWithSelection))
{
MoveEnd(false);
movement = true;
selection = true;
handled = true;
}
else
{
bool hasWholeWordModifiers = modifiers.HasAllFlags(keymap.WholeWordTextActionModifiers);
switch (e.Key)
{
case Key.Left:
selection = DetectSelection();
MoveHorizontal(-1, hasWholeWordModifiers, selection);
movement = true;
break;
case Key.Right:
selection = DetectSelection();
MoveHorizontal(1, hasWholeWordModifiers, selection);
movement = true;
break;
case Key.Up:
movement = MoveVertical(-1);
selection = DetectSelection();
break;
case Key.Down:
movement = MoveVertical(1);
selection = DetectSelection();
break;
case Key.Back:
SnapshotUndoRedo();
if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
{
SetSelectionForControlBackspace();
}
if (!DeleteSelection() && CaretIndex > 0)
{
var removedCharacters = 1;
// handle deleting /r/n
// you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
// a /r should also be deleted.
if (CaretIndex > 1 &&
text[CaretIndex - 1] == '\n' &&
text[CaretIndex - 2] == '\r')
{
removedCharacters = 2;
}
SetTextInternal(text.Substring(0, caretIndex - removedCharacters) +
text.Substring(caretIndex));
CaretIndex -= removedCharacters;
ClearSelection();
}
handled = true;
break;
case Key.Delete:
SnapshotUndoRedo();
if (hasWholeWordModifiers && SelectionStart == SelectionEnd)
{
SetSelectionForControlDelete();
}
if (!DeleteSelection() && caretIndex < text.Length)
{
var removedCharacters = 1;
// handle deleting /r/n
// you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
// a /r should also be deleted.
if (CaretIndex < text.Length - 1 &&
text[caretIndex + 1] == '\n' &&
text[caretIndex] == '\r')
{
removedCharacters = 2;
}
SetTextInternal(text.Substring(0, caretIndex) +
text.Substring(caretIndex + removedCharacters));
}
handled = true;
break;
case Key.Enter:
if (AcceptsReturn)
{
SnapshotUndoRedo();
HandleTextInput(NewLine);
handled = true;
}
break;
case Key.Tab:
if (AcceptsTab)
{
SnapshotUndoRedo();
HandleTextInput("\t");
handled = true;
}
else
{
base.OnKeyDown(e);
}
break;
case Key.Space:
SnapshotUndoRedo(); // always snapshot in between words
break;
default:
handled = false;
break;
}
}
if (movement && selection)
{
SelectionEnd = CaretIndex;
}
else if (movement)
{
ClearSelection();
}
if (handled || movement)
{
e.Handled = true;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
var text = Text;
var clickInfo = e.GetCurrentPoint(this);
if (text != null && clickInfo.Properties.IsLeftButtonPressed && !(clickInfo.Pointer?.Captured is Border))
{
var point = e.GetPosition(_presenter);
var index = CaretIndex = _presenter.GetCaretIndex(point);
#pragma warning disable CS0618 // Type or member is obsolete
switch (e.ClickCount)
#pragma warning restore CS0618 // Type or member is obsolete
{
case 1:
SelectionStart = SelectionEnd = index;
break;
case 2:
if (!StringUtils.IsStartOfWord(text, index))
{
SelectionStart = StringUtils.PreviousWord(text, index);
}
SelectionEnd = StringUtils.NextWord(text, index);
break;
case 3:
SelectAll();
break;
}
}
e.Pointer.Capture(_presenter);
e.Handled = true;
}
protected override void OnPointerMoved(PointerEventArgs e)
{
// selection should not change during pointer move if the user right clicks
if (_presenter != null && e.Pointer.Captured == _presenter && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
{
var point = e.GetPosition(_presenter);
point = new Point(
MathUtilities.Clamp(point.X, 0, Math.Max(_presenter.Bounds.Width - 1, 0)),
MathUtilities.Clamp(point.Y, 0, Math.Max(_presenter.Bounds.Height - 1, 0)));
CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
if (_presenter != null && e.Pointer.Captured == _presenter)
{
if (e.InitialPressMouseButton == MouseButton.Right)
{
var point = e.GetPosition(_presenter);
var caretIndex = _presenter.GetCaretIndex(point);
// see if mouse clicked inside current selection
// if it did not, we change the selection to where the user clicked
var firstSelection = Math.Min(SelectionStart, SelectionEnd);
var lastSelection = Math.Max(SelectionStart, SelectionEnd);
var didClickInSelection = SelectionStart != SelectionEnd &&
caretIndex >= firstSelection && caretIndex <= lastSelection;
if (!didClickInSelection)
{
CaretIndex = SelectionEnd = SelectionStart = caretIndex;
}
}
e.Pointer.Capture(null);
}
}
protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
{
if (property == TextProperty)
{
DataValidationErrors.SetError(this, value.Error);
}
}
private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text);
private int CoerceCaretIndex(int value, string text)
{
if (text == null)
{
return 0;
}
var length = text.Length;
if (value < 0)
{
return 0;
}
else if (value > length)
{
return length;
}
else if (value > 0 && text[value - 1] == '\r' && value < length && text[value] == '\n')
{
return value + 1;
}
else
{
return value;
}
}
public void Clear()
{
Text = string.Empty;
}
private int DeleteCharacter(int index)
{
var start = index + 1;
var text = Text;
var c = text[index];
var result = 1;
if (c == '\n' && index > 0 && text[index - 1] == '\r')
{
--index;
++result;
}
else if (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n')
{
++start;
++result;
}
Text = text.Substring(0, index) + text.Substring(start);
return result;
}
private void MoveHorizontal(int direction, bool wholeWord, bool isSelecting)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if (!wholeWord)
{
if (SelectionStart != SelectionEnd && !isSelecting)
{
var start = Math.Min(SelectionStart, SelectionEnd);
var end = Math.Max(SelectionStart, SelectionEnd);
CaretIndex = direction < 0 ? start : end;
return;
}
var index = caretIndex + direction;
if (index < 0 || index > text.Length)
{
return;
}
else if (index == text.Length)
{
CaretIndex = index;
return;
}
var c = text[index];
if (direction > 0)
{
CaretIndex += (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n') ? 2 : 1;
}
else
{
CaretIndex -= (c == '\n' && index > 0 && text[index - 1] == '\r') ? 2 : 1;
}
}
else
{
if (direction > 0)
{
CaretIndex += StringUtils.NextWord(text, caretIndex) - caretIndex;
}
else
{
CaretIndex += StringUtils.PreviousWord(text, caretIndex) - caretIndex;
}
}
}
private bool MoveVertical(int count)
{
if (_presenter is null)
{
return false;
}
var formattedText = _presenter.FormattedText;
var lines = formattedText.GetLines().ToList();
var caretIndex = CaretIndex;
var lineIndex = GetLine(caretIndex, lines) + count;
if (lineIndex >= 0 && lineIndex < lines.Count)
{
var line = lines[lineIndex];
var rect = formattedText.HitTestTextPosition(caretIndex);
var y = count < 0 ? rect.Y : rect.Bottom;
var point = new Point(rect.X, y + (count * (line.Height / 2)));
var hit = formattedText.HitTestPoint(point);
CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
return true;
}
return false;
}
private void MoveHome(bool document)
{
if (_presenter is null)
{
return;
}
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if (document)
{
caretIndex = 0;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
{
break;
}
pos += line.Length;
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
private void MoveEnd(bool document)
{
if (_presenter is null)
{
return;
}
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if (document)
{
caretIndex = text.Length;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
pos += line.Length;
if (pos > caretIndex)
{
if (pos < text.Length)
{
--pos;
if (pos > 0 && text[pos - 1] == '\r' && text[pos] == '\n')
{
--pos;
}
}
break;
}
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
/// <summary>
/// Select all text in the TextBox
/// </summary>
public void SelectAll()
{
SelectionStart = 0;
SelectionEnd = Text?.Length ?? 0;
CaretIndex = SelectionEnd;
}
private bool DeleteSelection()
{
if (!IsReadOnly)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
var text = Text;
SetTextInternal(text.Substring(0, start) + text.Substring(end));
CaretIndex = start;
ClearSelection();
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
private string GetSelection()
{
var text = Text;
if (string.IsNullOrEmpty(text))
return "";
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
if (start == end || (Text?.Length ?? 0) < end)
{
return "";
}
return text.Substring(start, end - start);
}
private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
{
int pos = 0;
int i;
for (i = 0; i < lines.Count - 1; ++i)
{
var line = lines[i];
pos += line.Length;
if (pos > caretIndex)
{
break;
}
}
return i;
}
private void SetTextInternal(string value)
{
try
{
_ignoreTextChanges = true;
SetAndRaise(TextProperty, ref _text, value);
}
finally
{
_ignoreTextChanges = false;
}
}
private void SetSelectionForControlBackspace()
{
SelectionStart = CaretIndex;
MoveHorizontal(-1, true, false);
SelectionEnd = CaretIndex;
}
private void SetSelectionForControlDelete()
{
SelectionStart = CaretIndex;
MoveHorizontal(1, true, false);
SelectionEnd = CaretIndex;
}
private void UpdatePseudoclasses()
{
PseudoClasses.Set(":empty", string.IsNullOrEmpty(Text));
}
private bool IsPasswordBox => PasswordChar != default(char);
UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
{
get { return new UndoRedoState(Text, CaretIndex); }
set
{
Text = value.Text;
CaretIndex = value.CaretPosition;
ClearSelection();
}
}
private void SnapshotUndoRedo(bool ignoreChangeCount = true)
{
if (IsUndoEnabled)
{
if (ignoreChangeCount ||
!_hasDoneSnapshotOnce ||
(!ignoreChangeCount &&
_selectedTextChangesMadeSinceLastUndoSnapshot >= _maxCharsBeforeUndoSnapshot))
{
_undoRedoHelper.Snapshot();
_selectedTextChangesMadeSinceLastUndoSnapshot = 0;
_hasDoneSnapshotOnce = true;
}
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type CalendarCalendarViewCollectionRequest.
/// </summary>
public partial class CalendarCalendarViewCollectionRequest : BaseRequest, ICalendarCalendarViewCollectionRequest
{
/// <summary>
/// Constructs a new CalendarCalendarViewCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public CalendarCalendarViewCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="calendarViewEvent">The Event to add.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event calendarViewEvent)
{
return this.AddAsync(calendarViewEvent, CancellationToken.None);
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="calendarViewEvent">The Event to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event calendarViewEvent, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Event>(calendarViewEvent, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<ICalendarCalendarViewCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<ICalendarCalendarViewCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<CalendarCalendarViewCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Expand(Expression<Func<Event, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Select(Expression<Func<Event, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
using System.ComponentModel.Composition;
using System.Windows.Media;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace NQuery.Authoring.VSEditorWpf.Classification
{
internal sealed class NQuerySemanticClassificationMetadata
{
public const string PunctuationClassificationFormatName = "NQuery.Punctuation.Format";
public const string PunctuationClassificationTypeName = "NQuery.Punctuation";
public const string SchemaTableClassificationFormatName = "NQuery.SchemaTable.Format";
public const string SchemaTableClassificationTypeName = "NQuery.SchemaTable";
public const string DerivedTableClassificationFormatName = "NQuery.DerivedTable.Format";
public const string DerivedTableClassificationTypeName = "NQuery.DerivedTable";
public const string CommonTableExpressionClassificationFormatName = "NQuery.CommonTableExpression.Format";
public const string CommonTableExpressionClassificationTypeName = "NQuery.CommonTableExpression";
public const string ColumnClassificationFormatName = "NQuery.Column.Format";
public const string ColumnClassificationTypeName = "NQuery.Column";
public const string MethodClassificationFormatName = "NQuery.Method.Format";
public const string MethodClassificationTypeName = "NQuery.Method";
public const string PropertyClassificationFormatName = "NQuery.Property.Format";
public const string PropertyClassificationTypeName = "NQuery.Property";
public const string FunctionClassificationFormatName = "NQuery.Function.Format";
public const string FunctionClassificationTypeName = "NQuery.Function";
public const string AggregateClassificationFormatName = "NQuery.Aggregate.Format";
public const string AggregateClassificationTypeName = "NQuery.Aggregate";
public const string VariableClassificationFormatName = "NQuery.Variable.Format";
public const string VariableClassificationTypeName = "NQuery.Variable";
public const string UnnecessaryClassificationFormatName = "NQuery.Unnecessary.Format";
public const string UnnecessaryClassificationTypeName = "NQuery.Unnecessary";
// Types ------------------
#pragma warning disable 649
[Export]
[Name(PunctuationClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition PunctuationType;
[Export]
[Name(SchemaTableClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition ClassType;
[Export]
[Name(DerivedTableClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition DelegateType;
[Export]
[Name(CommonTableExpressionClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition EnumType;
[Export]
[Name(FunctionClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition EventType;
[Export]
[Name(ColumnClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition FieldType;
[Export]
[Name(MethodClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition MethodType;
[Export]
[Name(AggregateClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition MutableLocalVariableType;
[Export]
[Name(PropertyClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition NamespaceType;
[Export]
[Name(VariableClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition VariableType;
[Export]
[Name(UnnecessaryClassificationTypeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
public ClassificationTypeDefinition UnnecessaryType;
#pragma warning restore 649
// Formats ----------------
[Export(typeof(EditorFormatDefinition))]
[Name(PunctuationClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = PunctuationClassificationTypeName)]
[UserVisible(true)]
public sealed class PunctuationFormat : ClassificationFormatDefinition
{
public PunctuationFormat()
{
DisplayName = Resources.ClassificationFormatPunctuation;
ForegroundColor = Colors.DarkCyan;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(SchemaTableClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = SchemaTableClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class SchemaTableFormat : ClassificationFormatDefinition
{
public SchemaTableFormat()
{
DisplayName = Resources.ClassificationFormatSchemaTable;
ForegroundColor = Colors.DarkBlue;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(DerivedTableClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = DerivedTableClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class DerivedTableFormat : ClassificationFormatDefinition
{
public DerivedTableFormat()
{
DisplayName = Resources.ClassificationFormatDerivedTable;
ForegroundColor = Colors.DarkBlue;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(CommonTableExpressionClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = CommonTableExpressionClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class CommonTableExpressionFormat : ClassificationFormatDefinition
{
public CommonTableExpressionFormat()
{
DisplayName = Resources.ClassificationFormatCommonTableExpression;
ForegroundColor = Colors.DarkBlue;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(FunctionClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = FunctionClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class FunctionFormat : ClassificationFormatDefinition
{
public FunctionFormat()
{
DisplayName = Resources.ClassificationFormatFunction;
ForegroundColor = Colors.Fuchsia;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(ColumnClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = ColumnClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class ColumnFormat : ClassificationFormatDefinition
{
public ColumnFormat()
{
DisplayName = Resources.ClassificationFormatColumn;
ForegroundColor = Colors.Purple;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(MethodClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = MethodClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class MethodFormat : ClassificationFormatDefinition
{
public MethodFormat()
{
DisplayName = Resources.ClassificationFormatMethod;
ForegroundColor = Colors.DarkCyan;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(AggregateClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = AggregateClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class AggregateFormat : ClassificationFormatDefinition
{
public AggregateFormat()
{
DisplayName = Resources.ClassificationFormatAggregate;
ForegroundColor = Colors.OrangeRed;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(PropertyClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = PropertyClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class PropertyFormat : ClassificationFormatDefinition
{
public PropertyFormat()
{
DisplayName = Resources.ClassificationFormatProperty;
ForegroundColor = Colors.DarkCyan;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(VariableClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = VariableClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class VariableFormat : ClassificationFormatDefinition
{
public VariableFormat()
{
DisplayName = Resources.ClassificationFormatVariable;
ForegroundColor = Colors.DarkCyan;
}
}
[Export(typeof(EditorFormatDefinition))]
[Name(UnnecessaryClassificationFormatName)]
[ClassificationType(ClassificationTypeNames = UnnecessaryClassificationTypeName)]
[UserVisible(true)]
[Order(After = PredefinedClassificationTypeNames.Identifier)]
[Order(After = PredefinedClassificationTypeNames.Keyword)]
public sealed class UnnecessaryFormat : ClassificationFormatDefinition
{
public UnnecessaryFormat()
{
DisplayName = Resources.ClassificationFormatUnnecessary;
ForegroundOpacity = 0.6;
}
}
}
}
| |
using System;
namespace StructureMap.Testing.Widget4
{
public interface IStrategy
{
void DoSomething();
}
public class Strategy : IStrategy
{
public Strategy(string name, int count, double rating, long quantity, bool isCalculated)
{
Name = name;
Count = count;
Rating = rating;
Quantity = quantity;
IsCalculated = isCalculated;
}
public string Name { get; set; }
public int Count { get; set; }
public double Rating { get; set; }
public long Quantity { get; set; }
public bool IsCalculated { get; set; }
#region IStrategy Members
public void DoSomething()
{
}
#endregion
public override bool Equals(object obj)
{
if (obj is Strategy)
{
var peer = (Strategy) obj;
bool returnValue = Name.Equals(peer.Name);
returnValue = returnValue && Count.Equals(peer.Count);
returnValue = returnValue && Rating.Equals(peer.Rating);
returnValue = returnValue && Quantity.Equals(peer.Quantity);
returnValue = returnValue && IsCalculated.Equals(peer.IsCalculated);
return returnValue;
}
else
{
return false;
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public enum StrategyType
{
LongTerm,
ShortTerm,
OverTheHorizon
}
public class ComplexStrategy : IStrategy
{
private readonly IStrategy _defaultStrategy;
private readonly IStrategy[] _innerStrategies;
private readonly string _name;
private readonly long _quantity;
private readonly StrategyType _strategyType;
public ComplexStrategy(IStrategy[] innerStrategies, string name, long quantity,
IStrategy defaultStrategy, StrategyType strategyType)
{
_innerStrategies = innerStrategies;
_name = name;
_quantity = quantity;
_defaultStrategy = defaultStrategy;
_strategyType = strategyType;
}
#region IStrategy Members
public void DoSomething()
{
}
#endregion
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is ComplexStrategy)
{
var peer = (ComplexStrategy) obj;
if (_innerStrategies.Length != peer._innerStrategies.Length)
{
return false;
}
bool returnValue = _strategyType.Equals(peer._strategyType);
returnValue = returnValue && _defaultStrategy.Equals(peer._defaultStrategy);
returnValue = returnValue && _quantity.Equals(peer._quantity);
returnValue = returnValue && _name.Equals(peer._name);
for (int i = 0; i < _innerStrategies.Length; i++)
{
returnValue = returnValue && _innerStrategies[i].Equals(peer._innerStrategies[i]);
}
return returnValue;
}
else
{
return false;
}
}
}
public class RandomStrategy : IStrategy
{
public RandomStrategy(double seed)
{
Seed = seed;
}
public double Seed { get; set; }
#region IStrategy Members
public void DoSomething()
{
}
#endregion
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is RandomStrategy)
{
var peer = (RandomStrategy) obj;
return (Seed == peer.Seed);
}
else
{
return false;
}
}
}
public class ColorStrategy : IStrategy
{
private readonly string _color;
public ColorStrategy(string color)
{
_color = color;
}
public string Color { get { return _color; } }
#region IStrategy Members
public void DoSomething()
{
}
#endregion
public override bool Equals(object obj)
{
if (obj is ColorStrategy)
{
var peer = (ColorStrategy) obj;
return (Color == peer.Color);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class StrategyDecorator : IStrategy
{
public StrategyDecorator(IStrategy innerStrategy)
{
InnerStrategy = innerStrategy;
}
public IStrategy InnerStrategy { get; set; }
#region IStrategy Members
public void DoSomething()
{
}
#endregion
public override bool Equals(object obj)
{
if (obj is StrategyDecorator)
{
var peer = (StrategyDecorator) obj;
return InnerStrategy.Equals(peer.InnerStrategy);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class CompoundStrategy : IStrategy
{
private readonly IStrategy[] _innerStrategies;
public CompoundStrategy(IStrategy[] innerStrategies)
{
_innerStrategies = innerStrategies;
}
public IStrategy[] InnerStrategies { get { return _innerStrategies; } }
#region IStrategy Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj is CompoundStrategy)
{
var peer = (CompoundStrategy) obj;
bool returnValue = (InnerStrategies.Length == peer.InnerStrategies.Length);
if (returnValue)
{
for (int i = 0; i < InnerStrategies.Length; i++)
{
returnValue = returnValue && (InnerStrategies[i].Equals(peer.InnerStrategies[i]));
}
}
return returnValue;
}
else
{
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Examine;
using Examine.LuceneEngine;
using Lucene.Net.Documents;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Scoping;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
using UmbracoExamine;
using Content = umbraco.cms.businesslogic.Content;
using Document = umbraco.cms.businesslogic.web.Document;
namespace Umbraco.Web.Search
{
/// <summary>
/// Used to wire up events for Examine
/// </summary>
public sealed class ExamineEvents : ApplicationEventHandler
{
// the default enlist priority is 100
// enlist with a lower priority to ensure that anything "default" runs after us
// but greater that SafeXmlReaderWriter priority which is 60
private const int EnlistPriority = 80;
/// <summary>
/// Once the application has started we should bind to all events and initialize the providers.
/// </summary>
/// <param name="httpApplication"></param>
/// <param name="applicationContext"></param>
/// <remarks>
/// We need to do this on the Started event as to guarantee that all resolvers are setup properly.
/// </remarks>
protected override void ApplicationStarted(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
{
LogHelper.Info<ExamineEvents>("Initializing Examine and binding to business logic events");
var registeredProviders = ExamineManager.Instance.IndexProviderCollection
.OfType<BaseUmbracoIndexer>().Count(x => x.EnableDefaultEventHandler);
LogHelper.Info<ExamineEvents>("Adding examine event handlers for index providers: {0}", () => registeredProviders);
//don't bind event handlers if we're not suppose to listen
if (registeredProviders == 0)
return;
//Bind to distributed cache events - this ensures that this logic occurs on ALL servers that are taking part
// in a load balanced environment.
CacheRefresherBase<UnpublishedPageCacheRefresher>.CacheUpdated += UnpublishedPageCacheRefresherCacheUpdated;
CacheRefresherBase<PageCacheRefresher>.CacheUpdated += PublishedPageCacheRefresherCacheUpdated;
CacheRefresherBase<MediaCacheRefresher>.CacheUpdated += MediaCacheRefresherCacheUpdated;
CacheRefresherBase<MemberCacheRefresher>.CacheUpdated += MemberCacheRefresherCacheUpdated;
CacheRefresherBase<ContentTypeCacheRefresher>.CacheUpdated += ContentTypeCacheRefresherCacheUpdated;
var contentIndexer = ExamineManager.Instance.IndexProviderCollection[Constants.Examine.InternalIndexer] as UmbracoContentIndexer;
if (contentIndexer != null)
{
contentIndexer.DocumentWriting += IndexerDocumentWriting;
}
var memberIndexer = ExamineManager.Instance.IndexProviderCollection[Constants.Examine.InternalMemberIndexer] as UmbracoMemberIndexer;
if (memberIndexer != null)
{
memberIndexer.DocumentWriting += IndexerDocumentWriting;
}
}
/// <summary>
/// This is used to refresh content indexers IndexData based on the DataService whenever a content type is changed since
/// properties may have been added/removed, then we need to re-index any required data if aliases have been changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// See: http://issues.umbraco.org/issue/U4-4798, http://issues.umbraco.org/issue/U4-7833
/// </remarks>
static void ContentTypeCacheRefresherCacheUpdated(ContentTypeCacheRefresher sender, CacheRefresherEventArgs e)
{
if (Suspendable.ExamineEvents.CanIndex == false)
return;
var indexersToUpdated = ExamineManager.Instance.IndexProviderCollection.OfType<UmbracoContentIndexer>();
foreach (var provider in indexersToUpdated)
{
provider.RefreshIndexerDataFromDataService();
}
if (e.MessageType == MessageType.RefreshByJson)
{
var contentTypesChanged = new HashSet<string>();
var mediaTypesChanged = new HashSet<string>();
var memberTypesChanged = new HashSet<string>();
var payloads = ContentTypeCacheRefresher.DeserializeFromJsonPayload(e.MessageObject.ToString());
foreach (var payload in payloads)
{
if (payload.IsNew == false
&& (payload.WasDeleted || payload.AliasChanged || payload.PropertyRemoved || payload.PropertyTypeAliasChanged))
{
//if we get here it means that some aliases have changed and the indexes for those particular doc types will need to be updated
if (payload.Type == typeof(IContentType).Name)
{
//if it is content
contentTypesChanged.Add(payload.Alias);
}
else if (payload.Type == typeof(IMediaType).Name)
{
//if it is media
mediaTypesChanged.Add(payload.Alias);
}
else if (payload.Type == typeof(IMemberType).Name)
{
//if it is members
memberTypesChanged.Add(payload.Alias);
}
}
}
//TODO: We need to update Examine to support re-indexing multiple items at once instead of one by one which will speed up
// the re-indexing process, we don't want to revert to rebuilding the whole thing!
if (contentTypesChanged.Count > 0)
{
foreach (var alias in contentTypesChanged)
{
var ctType = ApplicationContext.Current.Services.ContentTypeService.GetContentType(alias);
if (ctType != null)
{
var contentItems = ApplicationContext.Current.Services.ContentService.GetContentOfContentType(ctType.Id);
foreach (var contentItem in contentItems)
{
ReIndexForContent(contentItem, contentItem.HasPublishedVersion && contentItem.Trashed == false);
}
}
}
}
if (mediaTypesChanged.Count > 0)
{
foreach (var alias in mediaTypesChanged)
{
var ctType = ApplicationContext.Current.Services.ContentTypeService.GetMediaType(alias);
if (ctType != null)
{
var mediaItems = ApplicationContext.Current.Services.MediaService.GetMediaOfMediaType(ctType.Id);
foreach (var mediaItem in mediaItems)
{
ReIndexForMedia(mediaItem, mediaItem.Trashed == false);
}
}
}
}
if (memberTypesChanged.Count > 0)
{
foreach (var alias in memberTypesChanged)
{
var ctType = ApplicationContext.Current.Services.MemberTypeService.Get(alias);
if (ctType != null)
{
var memberItems = ApplicationContext.Current.Services.MemberService.GetMembersByMemberType(ctType.Id);
foreach (var memberItem in memberItems)
{
ReIndexForMember(memberItem);
}
}
}
}
}
}
static void MemberCacheRefresherCacheUpdated(MemberCacheRefresher sender, CacheRefresherEventArgs e)
{
if (Suspendable.ExamineEvents.CanIndex == false)
return;
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.MemberService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForMember(c1);
}
break;
case MessageType.RemoveById:
// This is triggered when the item is permanently deleted
DeleteIndexForEntity((int)e.MessageObject, false);
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IMember;
if (c3 != null)
{
ReIndexForMember(c3);
}
break;
case MessageType.RemoveByInstance:
// This is triggered when the item is permanently deleted
var c4 = e.MessageObject as IMember;
if (c4 != null)
{
DeleteIndexForEntity(c4.Id, false);
}
break;
case MessageType.RefreshAll:
case MessageType.RefreshByJson:
default:
//We don't support these, these message types will not fire for unpublished content
break;
}
}
/// <summary>
/// Handles index management for all media events - basically handling saving/copying/trashing/deleting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void MediaCacheRefresherCacheUpdated(MediaCacheRefresher sender, CacheRefresherEventArgs e)
{
if (Suspendable.ExamineEvents.CanIndex == false)
return;
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForMedia(c1, c1.Trashed == false);
}
break;
case MessageType.RemoveById:
var c2 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject);
if (c2 != null)
{
//This is triggered when the item has trashed.
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c2.Id, true);
//We then need to re-index this item for all indexes supporting unpublished content
ReIndexForMedia(c2, false);
}
break;
case MessageType.RefreshByJson:
var jsonPayloads = MediaCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject);
if (jsonPayloads.Any())
{
foreach (var payload in jsonPayloads)
{
switch (payload.Operation)
{
case MediaCacheRefresher.OperationType.Saved:
var media1 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id);
if (media1 != null)
{
ReIndexForMedia(media1, media1.Trashed == false);
}
break;
case MediaCacheRefresher.OperationType.Trashed:
//keep if trashed for indexes supporting unpublished
//(delete the index from all indexes not supporting unpublished content)
DeleteIndexForEntity(payload.Id, true);
//We then need to re-index this item for all indexes supporting unpublished content
var media2 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id);
if (media2 != null)
{
ReIndexForMedia(media2, false);
}
break;
case MediaCacheRefresher.OperationType.Deleted:
//permanently remove from all indexes
DeleteIndexForEntity(payload.Id, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
break;
case MessageType.RefreshByInstance:
case MessageType.RemoveByInstance:
case MessageType.RefreshAll:
default:
//We don't support these, these message types will not fire for media
break;
}
}
/// <summary>
/// Handles index management for all published content events - basically handling published/unpublished
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// This will execute on all servers taking part in load balancing
/// </remarks>
static void PublishedPageCacheRefresherCacheUpdated(PageCacheRefresher sender, CacheRefresherEventArgs e)
{
if (Suspendable.ExamineEvents.CanIndex == false)
return;
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForContent(c1, true);
}
break;
case MessageType.RemoveById:
//This is triggered when the item has been unpublished or trashed (which also performs an unpublish).
var c2 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject);
if (c2 != null)
{
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c2.Id, true);
// We then need to re-index this item for all indexes supporting unpublished content
ReIndexForContent(c2, false);
}
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IContent;
if (c3 != null)
{
ReIndexForContent(c3, true);
}
break;
case MessageType.RemoveByInstance:
//This is triggered when the item has been unpublished or trashed (which also performs an unpublish).
var c4 = e.MessageObject as IContent;
if (c4 != null)
{
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c4.Id, true);
// We then need to re-index this item for all indexes supporting unpublished content
ReIndexForContent(c4, false);
}
break;
case MessageType.RefreshAll:
case MessageType.RefreshByJson:
default:
//We don't support these for examine indexing
break;
}
}
/// <summary>
/// Handles index management for all unpublished content events - basically handling saving/copying/deleting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// This will execute on all servers taking part in load balancing
/// </remarks>
static void UnpublishedPageCacheRefresherCacheUpdated(UnpublishedPageCacheRefresher sender, CacheRefresherEventArgs e)
{
if (Suspendable.ExamineEvents.CanIndex == false)
return;
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.ContentService.GetById((int) e.MessageObject);
if (c1 != null)
{
ReIndexForContent(c1, false);
}
break;
case MessageType.RemoveById:
// This is triggered when the item is permanently deleted
DeleteIndexForEntity((int)e.MessageObject, false);
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IContent;
if (c3 != null)
{
ReIndexForContent(c3, false);
}
break;
case MessageType.RemoveByInstance:
// This is triggered when the item is permanently deleted
var c4 = e.MessageObject as IContent;
if (c4 != null)
{
DeleteIndexForEntity(c4.Id, false);
}
break;
case MessageType.RefreshByJson:
var jsonPayloads = UnpublishedPageCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject);
if (jsonPayloads.Any())
{
foreach (var payload in jsonPayloads)
{
switch (payload.Operation)
{
case UnpublishedPageCacheRefresher.OperationType.Deleted:
//permanently remove from all indexes
DeleteIndexForEntity(payload.Id, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
break;
case MessageType.RefreshAll:
default:
//We don't support these, these message types will not fire for unpublished content
break;
}
}
private static void ReIndexForMember(IMember member)
{
var actions = DeferedActions.Get(ApplicationContext.Current.ScopeProvider);
if (actions != null)
actions.Add(new DeferedReIndexForMember(member));
else
DeferedReIndexForMember.Execute(member);
}
/// <summary>
/// Event handler to create a lower cased version of the node name, this is so we can support case-insensitive searching and still
/// use the Whitespace Analyzer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void IndexerDocumentWriting(object sender, DocumentWritingEventArgs e)
{
if (e.Fields.Keys.Contains("nodeName"))
{
//TODO: This logic should really be put into the content indexer instead of hidden here!!
//add the lower cased version
e.Document.Add(new Field("__nodeName",
e.Fields["nodeName"].ToLower(),
Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.NO
));
}
}
private static void ReIndexForMedia(IMedia sender, bool isMediaPublished)
{
var actions = DeferedActions.Get(ApplicationContext.Current.ScopeProvider);
if (actions != null)
actions.Add(new DeferedReIndexForMedia(sender, isMediaPublished));
else
DeferedReIndexForMedia.Execute(sender, isMediaPublished);
}
/// <summary>
/// Remove items from any index that doesn't support unpublished content
/// </summary>
/// <param name="entityId"></param>
/// <param name="keepIfUnpublished">
/// If true, indicates that we will only delete this item from indexes that don't support unpublished content.
/// If false it will delete this from all indexes regardless.
/// </param>
private static void DeleteIndexForEntity(int entityId, bool keepIfUnpublished)
{
var actions = DeferedActions.Get(ApplicationContext.Current.ScopeProvider);
if (actions != null)
actions.Add(new DeferedDeleteIndex(entityId, keepIfUnpublished));
else
DeferedDeleteIndex.Execute(entityId, keepIfUnpublished);
}
/// <summary>
/// Re-indexes a content item whether published or not but only indexes them for indexes supporting unpublished content
/// </summary>
/// <param name="sender"></param>
/// <param name="isContentPublished">
/// Value indicating whether the item is published or not
/// </param>
private static void ReIndexForContent(IContent sender, bool isContentPublished)
{
var actions = DeferedActions.Get(ApplicationContext.Current.ScopeProvider);
if (actions != null)
actions.Add(new DeferedReIndexForContent(sender, isContentPublished));
else
DeferedReIndexForContent.Execute(sender, isContentPublished);
}
private class DeferedActions
{
private readonly List<DeferedAction> _actions = new List<DeferedAction>();
public static DeferedActions Get(IScopeProvider scopeProvider)
{
var scopeContext = scopeProvider.Context;
if (scopeContext == null) return null;
return scopeContext.Enlist("examineEvents",
() => new DeferedActions(), // creator
(completed, actions) => // action
{
if (completed) actions.Execute();
}, EnlistPriority);
}
public void Add(DeferedAction action)
{
_actions.Add(action);
}
private void Execute()
{
foreach (var action in _actions)
action.Execute();
}
}
private abstract class DeferedAction
{
public virtual void Execute()
{ }
}
private class DeferedReIndexForContent : DeferedAction
{
private readonly IContent _content;
private readonly bool _isPublished;
public DeferedReIndexForContent(IContent content, bool isPublished)
{
_content = content;
_isPublished = isPublished;
}
public override void Execute()
{
Execute(_content, _isPublished);
}
public static void Execute(IContent content, bool isPublished)
{
var xml = content.ToXml();
//add an icon attribute to get indexed
xml.Add(new XAttribute("icon", content.ContentType.Icon));
ExamineManager.Instance.ReIndexNode(
xml, IndexTypes.Content,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//Index this item for all indexers if the content is published, otherwise if the item is not published
// then only index this for indexers supporting unpublished content
.Where(x => isPublished || (x.SupportUnpublishedContent))
.Where(x => x.EnableDefaultEventHandler));
}
}
private class DeferedReIndexForMedia : DeferedAction
{
private readonly IMedia _media;
private readonly bool _isPublished;
public DeferedReIndexForMedia(IMedia media, bool isPublished)
{
_media = media;
_isPublished = isPublished;
}
public override void Execute()
{
Execute(_media, _isPublished);
}
public static void Execute(IMedia media, bool isPublished)
{
var xml = media.ToXml();
//add an icon attribute to get indexed
xml.Add(new XAttribute("icon", media.ContentType.Icon));
ExamineManager.Instance.ReIndexNode(
xml, IndexTypes.Media,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//Index this item for all indexers if the media is not trashed, otherwise if the item is trashed
// then only index this for indexers supporting unpublished media
.Where(x => isPublished || (x.SupportUnpublishedContent))
.Where(x => x.EnableDefaultEventHandler));
}
}
private class DeferedReIndexForMember : DeferedAction
{
private readonly IMember _member;
public DeferedReIndexForMember(IMember member)
{
_member = member;
}
public override void Execute()
{
Execute(_member);
}
public static void Execute(IMember member)
{
ExamineManager.Instance.ReIndexNode(
member.ToXml(), IndexTypes.Member,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//ensure that only the providers are flagged to listen execute
.Where(x => x.EnableDefaultEventHandler));
}
}
private class DeferedDeleteIndex : DeferedAction
{
private readonly int _id;
private readonly bool _keepIfUnpublished;
public DeferedDeleteIndex(int id, bool keepIfUnpublished)
{
_id = id;
_keepIfUnpublished = keepIfUnpublished;
}
public override void Execute()
{
Execute(_id, _keepIfUnpublished);
}
public static void Execute(int id, bool keepIfUnpublished)
{
ExamineManager.Instance.DeleteFromIndex(
id.ToString(CultureInfo.InvariantCulture),
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//if keepIfUnpublished == true then only delete this item from indexes not supporting unpublished content,
// otherwise if keepIfUnpublished == false then remove from all indexes
.Where(x => keepIfUnpublished == false || x.SupportUnpublishedContent == false)
.Where(x => x.EnableDefaultEventHandler));
}
}
/// <summary>
/// Converts a content node to XDocument
/// </summary>
/// <param name="node"></param>
/// <param name="cacheOnly">true if data is going to be returned from cache</param>
/// <returns></returns>
[Obsolete("This method is no longer used and will be removed from the core in future versions, the cacheOnly parameter has no effect. Use the other ToXDocument overload instead")]
public static XDocument ToXDocument(Content node, bool cacheOnly)
{
return ToXDocument(node);
}
/// <summary>
/// Converts a content node to Xml
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static XDocument ToXDocument(Content node)
{
if (TypeHelper.IsTypeAssignableFrom<Document>(node))
{
return new XDocument(((Document) node).ContentEntity.ToXml());
}
if (TypeHelper.IsTypeAssignableFrom<global::umbraco.cms.businesslogic.media.Media>(node))
{
return new XDocument(((global::umbraco.cms.businesslogic.media.Media) node).MediaItem.ToXml());
}
var xDoc = new XmlDocument();
var xNode = xDoc.CreateNode(XmlNodeType.Element, "node", "");
node.XmlPopulate(xDoc, ref xNode, false);
if (xNode.Attributes["nodeTypeAlias"] == null)
{
//we'll add the nodeTypeAlias ourselves
XmlAttribute d = xDoc.CreateAttribute("nodeTypeAlias");
d.Value = node.ContentType.Alias;
xNode.Attributes.Append(d);
}
return new XDocument(ExamineXmlExtensions.ToXElement(xNode));
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:41 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.menu
{
#region Menu
/// <inheritdocs />
/// <summary>
/// <p>A menu object. This is the container to which you may add <see cref="Ext.menu.Item">menu items</see>.</p>
/// <p>Menus may contain either <see cref="Ext.menu.Item">menu items</see>, or general <see cref="Ext.Component">Components</see>.
/// Menus may also contain <see cref="Ext.panel.AbstractPanelConfig.dockedItems">docked items</see> because it extends <see cref="Ext.panel.Panel">Ext.panel.Panel</see>.</p>
/// <p>To make a contained general <see cref="Ext.Component">Component</see> line up with other <see cref="Ext.menu.Item">menu items</see>,
/// specify <c><see cref="Ext.menu.ItemConfig.plain">plain</see>: true</c>. This reserves a space for an icon, and indents the Component
/// in line with the other menu items.</p>
/// <p>By default, Menus are absolutely positioned, floating Components. By configuring a Menu with <c><see cref="Ext.menu.MenuConfig.floating">floating</see>: false</c>,
/// a Menu may be used as a child of a <see cref="Ext.container.Container">Container</see>.</p>
/// <pre><code><see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.menu.Menu">Ext.menu.Menu</see>', {
/// width: 100,
/// margin: '0 0 10 0',
/// floating: false, // usually you want this set to True (default)
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(), // usually rendered by it's containing component
/// items: [{
/// text: 'regular item 1'
/// },{
/// text: 'regular item 2'
/// },{
/// text: 'regular item 3'
/// }]
/// });
/// <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.menu.Menu">Ext.menu.Menu</see>', {
/// width: 100,
/// plain: true,
/// floating: false, // usually you want this set to True (default)
/// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(), // usually rendered by it's containing component
/// items: [{
/// text: 'plain item 1'
/// },{
/// text: 'plain item 2'
/// },{
/// text: 'plain item 3'
/// }]
/// });
/// </code></pre>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Menu : Ext.panel.Panel
{
/// <summary>
/// True to allow multiple menus to be displayed at the same time.
/// Defaults to: <c>false</c>
/// </summary>
public bool allowOtherMenus;
/// <summary>
/// Defaults to: <c>"menu"</c>
/// </summary>
public JsString ariaRole;
/// <summary>
/// Menus are constrained to the document body by default.
/// Defaults to: <c>true</c>
/// </summary>
public bool constrain;
/// <summary>
/// The default Ext.Element#getAlignToXY anchor position value for this menu
/// relative to its element of origin.
/// Defaults to: <c>"tl-bl?"</c>
/// </summary>
public JsString defaultAlign;
/// <summary>
/// True to enable keyboard navigation for controlling the menu.
/// This option should generally be disabled when form fields are
/// being used inside the menu.
/// Defaults to: <c>true</c>
/// </summary>
public bool enableKeyNav;
/// <summary>
/// True to ignore clicks on any item in this menu that is a parent item (displays a submenu)
/// so that the submenu is not dismissed when clicking the parent item.
/// Defaults to: <c>false</c>
/// </summary>
public bool ignoreParentClicks;
/// <summary>
/// True to remove the incised line down the left side of the menu and to not indent general Component items.
/// Defaults to: <c>false</c>
/// </summary>
public bool plain;
/// <summary>
/// True to show the icon separator.
/// Defaults to: <c>true</c>
/// </summary>
public bool showSeparator;
/// <summary>
/// true in this class to identify an object as an instantiated Menu, or subclass thereof.
/// Defaults to: <c>true</c>
/// </summary>
public bool isMenu{get;set;}
/// <summary>
/// The parent Menu of this Menu.
/// </summary>
public Ext.menu.Menu parentMenu{get;set;}
/// <summary>
/// Returns whether a menu item can be activated or not.
/// </summary>
/// <param name="item">
/// </param>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div>
/// </div>
/// </returns>
public bool canActivateItem(object item){return false;}
/// <summary>
/// Deactivates the current active item on the menu, if one exists.
/// </summary>
/// <param name="andBlurFocusedItem">
/// </param>
public void deactivateActiveItem(object andBlurFocusedItem){}
/// <summary>
/// Shows the floating menu by the specified Component or Element.
/// </summary>
/// <param name="component"><p>The <see cref="Ext.Component">Ext.Component</see> or <see cref="Ext.dom.Element">Ext.Element</see> to show the menu by.</p>
/// </param>
/// <param name="position"><p>Alignment position as used by <see cref="Ext.dom.Element.getAlignToXY">Ext.Element.getAlignToXY</see>.
/// Defaults to <c><see cref="Ext.menu.MenuConfig.defaultAlign">defaultAlign</see></c>.</p>
/// </param>
/// <param name="offsets"><p>Alignment offsets as used by <see cref="Ext.dom.Element.getAlignToXY">Ext.Element.getAlignToXY</see>.</p>
/// </param>
/// <returns>
/// <span><see cref="Ext.menu.Menu">Ext.menu.Menu</see></span><div><p>This Menu.</p>
/// </div>
/// </returns>
public Ext.menu.Menu showBy(object component, object position=null, object offsets=null){return null;}
public Menu(Ext.menu.MenuConfig config){}
public Menu(){}
public Menu(params object[] args){}
}
#endregion
#region MenuConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class MenuConfig : Ext.panel.PanelConfig
{
/// <summary>
/// True to allow multiple menus to be displayed at the same time.
/// Defaults to: <c>false</c>
/// </summary>
public bool allowOtherMenus;
/// <summary>
/// Defaults to: <c>"menu"</c>
/// </summary>
public JsString ariaRole;
/// <summary>
/// Menus are constrained to the document body by default.
/// Defaults to: <c>true</c>
/// </summary>
public bool constrain;
/// <summary>
/// The default Ext.Element#getAlignToXY anchor position value for this menu
/// relative to its element of origin.
/// Defaults to: <c>"tl-bl?"</c>
/// </summary>
public JsString defaultAlign;
/// <summary>
/// True to enable keyboard navigation for controlling the menu.
/// This option should generally be disabled when form fields are
/// being used inside the menu.
/// Defaults to: <c>true</c>
/// </summary>
public bool enableKeyNav;
/// <summary>
/// True to ignore clicks on any item in this menu that is a parent item (displays a submenu)
/// so that the submenu is not dismissed when clicking the parent item.
/// Defaults to: <c>false</c>
/// </summary>
public bool ignoreParentClicks;
/// <summary>
/// True to remove the incised line down the left side of the menu and to not indent general Component items.
/// Defaults to: <c>false</c>
/// </summary>
public bool plain;
/// <summary>
/// True to show the icon separator.
/// Defaults to: <c>true</c>
/// </summary>
public bool showSeparator;
public MenuConfig(params object[] args){}
}
#endregion
#region MenuEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class MenuEvents : Ext.panel.PanelEvents
{
/// <summary>
/// Fires when this menu is clicked
/// </summary>
/// <param name="menu"><p>The menu which has been clicked</p>
/// </param>
/// <param name="item"><p>The menu item that was clicked. <c>undefined</c> if not applicable.</p>
/// </param>
/// <param name="e"><p>The underlying <see cref="Ext.EventObject">Ext.EventObject</see>.</p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void click(Ext.menu.Menu menu, Ext.Component item, EventObject e, object eOpts){}
/// <summary>
/// Fires when the mouse enters this menu
/// </summary>
/// <param name="menu"><p>The menu</p>
/// </param>
/// <param name="e"><p>The underlying <see cref="Ext.EventObject">Ext.EventObject</see></p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void mouseenter(Ext.menu.Menu menu, EventObject e, object eOpts){}
/// <summary>
/// Fires when the mouse leaves this menu
/// </summary>
/// <param name="menu"><p>The menu</p>
/// </param>
/// <param name="e"><p>The underlying <see cref="Ext.EventObject">Ext.EventObject</see></p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void mouseleave(Ext.menu.Menu menu, EventObject e, object eOpts){}
/// <summary>
/// Fires when the mouse is hovering over this menu
/// </summary>
/// <param name="menu"><p>The menu</p>
/// </param>
/// <param name="item"><p>The menu item that the mouse is over. <c>undefined</c> if not applicable.</p>
/// </param>
/// <param name="e"><p>The underlying <see cref="Ext.EventObject">Ext.EventObject</see></p>
/// </param>
/// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p>
/// </param>
public void mouseover(Ext.menu.Menu menu, Ext.Component item, EventObject e, object eOpts){}
public MenuEvents(params object[] args){}
}
#endregion
}
| |
//---------------------------------------------------------------------
// <copyright file="Sql8ExpressionRewriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Data.Common;
using System.Data.Common.CommandTrees;
using System.Data.Common.CommandTrees.Internal;
using System.Data.Metadata.Edm;
using System.Data.Common.CommandTrees.ExpressionBuilder;
namespace System.Data.SqlClient.SqlGen
{
/// <summary>
/// Rewrites an expression tree to make it suitable for translation to SQL appropriate for SQL Server 2000
/// In particular, it replaces expressions that are not directly supported on SQL Server 2000
/// with alternative translations. The following expressions are translated:
/// <list type="bullet">
/// <item><see cref="DbExceptExpression"/></item>
/// <item><see cref="DbIntersectExpression"/></item>
/// <item><see cref="DbSkipExpression"/></item>
/// </list>
///
/// The other expressions are copied unmodified.
/// The new expression belongs to a new query command tree.
/// </summary>
internal class Sql8ExpressionRewriter : DbExpressionRebinder
{
#region Entry Point
/// <summary>
/// The only entry point.
/// Rewrites the given tree by replacing expressions that are not directly supported on SQL Server 2000
/// with alterntive translations.
/// </summary>
/// <param name="originalTree">The tree to rewrite</param>
/// <returns>The new tree</returns>
internal static DbQueryCommandTree Rewrite(DbQueryCommandTree originalTree)
{
Debug.Assert(originalTree != null, "OriginalTree is null");
Sql8ExpressionRewriter rewriter = new Sql8ExpressionRewriter(originalTree.MetadataWorkspace);
DbExpression newQuery = rewriter.VisitExpression(originalTree.Query);
return DbQueryCommandTree.FromValidExpression(originalTree.MetadataWorkspace, originalTree.DataSpace, newQuery);
}
#endregion
#region Constructor
/// <summary>
/// Private Constructor.
/// </summary>
/// <param name="metadata"></param>
private Sql8ExpressionRewriter(MetadataWorkspace metadata)
:base(metadata)
{
}
#endregion
#region DbExpressionVisitor<DbExpression> Members
/// <summary>
/// <see cref="TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)"/>
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public override DbExpression Visit(DbExceptExpression e)
{
return TransformIntersectOrExcept(VisitExpression(e.Left), VisitExpression(e.Right), DbExpressionKind.Except);
}
/// <summary>
/// <see cref="TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)"/>
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public override DbExpression Visit(DbIntersectExpression e)
{
return TransformIntersectOrExcept(VisitExpression(e.Left), VisitExpression(e.Right), DbExpressionKind.Intersect);
}
/// <summary>
/// Logicaly, <see cref="DbSkipExpression"/> translates to:
/// SELECT Y.x1, Y.x2, ..., Y.xn
/// FROM (
/// SELECT X.x1, X.x2, ..., X.xn,
/// FROM input AS X
/// EXCEPT
/// SELECT TOP(count) Z.x1, Z.x2, ..., Z.xn
/// FROM input AS Z
/// ORDER BY sk1, sk2, ...
/// ) AS Y
/// ORDER BY sk1, sk2, ...
///
/// Here, input refers to the input of the <see cref="DbSkipExpression"/>, and count to the count property of the <see cref="DbSkipExpression"/>.
/// The implementation of EXCEPT is non-duplicate eliminating, and does equality comparison only over the
/// equality comparable columns of the input.
///
/// This corresponds to the following expression tree:
///
/// SORT
/// |
/// NON-DISTINCT EXCEPT (specially translated, <see cref="TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)"/>
/// |
/// | - Left: clone of input
/// | - Right:
/// |
/// Limit
/// |
/// | - Limit: Count
/// | - Input
/// |
/// Sort
/// |
/// input
///
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public override DbExpression Visit(DbSkipExpression e)
{
//Build the right input of the except
DbExpression rightInput = VisitExpressionBinding(e.Input).Sort(VisitSortOrder(e.SortOrder)).Limit(VisitExpression(e.Count));
//Build the left input for the except
DbExpression leftInput = VisitExpression(e.Input.Expression); //Another copy of the input
IList<DbSortClause> sortOrder = VisitSortOrder(e.SortOrder); //Another copy of the sort order
// Create a list of the sort expressions to be used for translating except
IList<DbPropertyExpression> sortExpressions = new List<DbPropertyExpression>(e.SortOrder.Count);
foreach (DbSortClause sortClause in sortOrder)
{
//We only care about property expressions, not about constants
if (sortClause.Expression.ExpressionKind == DbExpressionKind.Property)
{
sortExpressions.Add((DbPropertyExpression)sortClause.Expression);
}
}
DbExpression exceptExpression = TransformIntersectOrExcept(leftInput, rightInput, DbExpressionKind.Skip, sortExpressions, e.Input.VariableName);
DbExpression result = exceptExpression.BindAs(e.Input.VariableName).Sort(sortOrder);
return result;
}
#endregion
#region DbExpressionVisitor<DbExpression> Member Helpers
/// <summary>
/// This method is invoked when tranforming <see cref="DbIntersectExpression"/> and <see cref="DbExceptExpression"/> by doing comparison over all input columns.
/// <see cref="TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)"/>
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="expressionKind"></param>
/// <returns></returns>
private DbExpression TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind)
{
return TransformIntersectOrExcept( left, right, expressionKind, null, null);
}
/// <summary>
/// This method is used for translating <see cref="DbIntersectExpression"/> and <see cref="DbExceptExpression"/>,
/// and for translating the "Except" part of <see cref="DbSkipExpression"/>.
/// into the follwoing expression:
///
/// A INTERSECT B, A EXCEPT B
///
/// (DISTINCT)
/// |
/// FILTER
/// |
/// | - Input: A
/// | - Predicate:(NOT)
/// |
/// ANY
/// |
/// | - Input: B
/// | - Predicate: (B.b1 = A.a1 or (B.b1 is null and A.a1 is null))
/// AND (B.b2 = A.a2 or (B.b2 is null and A.a2 is null))
/// AND ...
/// AND (B.bn = A.an or (B.bn is null and A.an is null)))
///
/// Here, A corresponds to right and B to left.
/// (NOT) is present when transforming Except
/// for the purpose of translating <see cref="DbExceptExpression"/> or <see cref="DbSkipExpression"/>.
/// (DISTINCT) is present when transforming for the purpose of translating
/// <see cref="DbExceptExpression"/> or <see cref="DbIntersectExpression"/>.
///
/// For <see cref="DbSkipExpression"/>, the input to ANY is caped with project which projects out only
/// the columns represented in the sortExpressionsOverLeft list and only these are used in the predicate.
/// This is because we want to support skip over input with non-equal comarable columns and we have no way to recognize these.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="expressionKind"></param>
/// <param name="sortExpressionsOverLeft">note that this list gets destroyed by this method</param>
/// <param name="sortExpressionsBindingVariableName"></param>
/// <returns></returns>
private DbExpression TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)
{
bool negate = (expressionKind == DbExpressionKind.Except) || (expressionKind == DbExpressionKind.Skip);
bool distinct = (expressionKind == DbExpressionKind.Except) || (expressionKind == DbExpressionKind.Intersect);
DbExpressionBinding leftInputBinding = left.Bind();
DbExpressionBinding rightInputBinding = right.Bind();
IList<DbPropertyExpression> leftFlattenedProperties = new List<DbPropertyExpression>();
IList<DbPropertyExpression> rightFlattenedProperties = new List<DbPropertyExpression>();
FlattenProperties(leftInputBinding.Variable, leftFlattenedProperties);
FlattenProperties(rightInputBinding.Variable, rightFlattenedProperties);
//For Skip, we need to ignore any columns that are not in the original sort list. We can recognize these by comparing the left flattened properties and
// the properties in the list sortExpressionsOverLeft
// If any such columns exist, we need to add an additional project, to keep the rest of the columns from being projected, as if any among these
// are non equal comparable, SQL Server 2000 throws.
if (expressionKind == DbExpressionKind.Skip)
{
if (RemoveNonSortProperties(leftFlattenedProperties, rightFlattenedProperties, sortExpressionsOverLeft, leftInputBinding.VariableName, sortExpressionsBindingVariableName))
{
rightInputBinding = CapWithProject(rightInputBinding, rightFlattenedProperties);
}
}
Debug.Assert(leftFlattenedProperties.Count == rightFlattenedProperties.Count, "The left and the right input to INTERSECT or EXCEPT have a different number of properties");
Debug.Assert(leftFlattenedProperties.Count != 0, "The inputs to INTERSECT or EXCEPT have no properties");
//Build the predicate for the quantifier:
// (B.b1 = A.a1 or (B.b1 is null and A.a1 is null))
// AND (B.b2 = A.a2 or (B.b2 is null and A.a2 is null))
// AND ...
// AND (B.bn = A.an or (B.bn is null and A.an is null)))
DbExpression existsPredicate = null;
for (int i = 0; i < leftFlattenedProperties.Count; i++)
{
//A.ai == B.bi
DbExpression equalsExpression = leftFlattenedProperties[i].Equal(rightFlattenedProperties[i]);
//A.ai is null AND B.bi is null
DbExpression leftIsNullExpression = leftFlattenedProperties[i].IsNull();
DbExpression rightIsNullExpression = rightFlattenedProperties[i].IsNull();
DbExpression bothNullExpression = leftIsNullExpression.And(rightIsNullExpression);
DbExpression orExpression = equalsExpression.Or(bothNullExpression);
if (i == 0)
{
existsPredicate = orExpression;
}
else
{
existsPredicate = existsPredicate.And(orExpression);
}
}
//Build the quantifier
DbExpression quantifierExpression = rightInputBinding.Any(existsPredicate);
DbExpression filterPredicate;
//Negate if needed
if (negate)
{
filterPredicate = quantifierExpression.Not();
}
else
{
filterPredicate = quantifierExpression;
}
//Build the filter
DbExpression result = leftInputBinding.Filter(filterPredicate);
//Apply distinct in needed
if (distinct)
{
result = result.Distinct();
}
return result;
}
/// <summary>
/// Adds the flattened properties on the input to the flattenedProperties list.
/// </summary>
/// <param name="input"></param>
/// <param name="flattenedProperties"></param>
private void FlattenProperties(DbExpression input, IList<DbPropertyExpression> flattenedProperties)
{
IList<EdmProperty> properties = TypeHelpers.GetProperties(input.ResultType);
Debug.Assert(properties.Count != 0, "No nested properties when FlattenProperties called?");
for (int i = 0; i < properties.Count; i++)
{
DbExpression propertyInput = input;
DbPropertyExpression propertyExpression = propertyInput.Property(properties[i]);
if (TypeSemantics.IsPrimitiveType(properties[i].TypeUsage))
{
flattenedProperties.Add(propertyExpression);
}
else
{
Debug.Assert(TypeSemantics.IsEntityType(properties[i].TypeUsage) || TypeSemantics.IsRowType(properties[i].TypeUsage),
"The input to FlattenProperties is not of EntityType or RowType?");
FlattenProperties(propertyExpression, flattenedProperties);
}
}
}
/// <summary>
/// Helper method for <see cref="TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)"/>
/// Removes all pairs of property expressions from list1 and list2, for which the property expression in list1
/// does not have a 'matching' property expression in list2.
/// The lists list1 and list2 are known to not create duplicate, and the purpose of the sortList is just for this method.
/// Thus, to optimize the match process, we remove the seen property expressions from the sort list in <see cref="HasMatchInList"/>
/// when iterating both list simultaneously.
/// </summary>
/// <param name="list1"></param>
/// <param name="list2"></param>
/// <param name="sortList"></param>
/// <param name="list1BindingVariableName"></param>
/// <param name="sortExpressionsBindingVariableName"></param>
/// <returns></returns>
private static bool RemoveNonSortProperties(IList<DbPropertyExpression> list1, IList<DbPropertyExpression> list2, IList<DbPropertyExpression> sortList, string list1BindingVariableName, string sortExpressionsBindingVariableName)
{
bool result = false;
for (int i = list1.Count - 1; i >= 0; i--)
{
if (!HasMatchInList(list1[i], sortList, list1BindingVariableName, sortExpressionsBindingVariableName))
{
list1.RemoveAt(i);
list2.RemoveAt(i);
result = true;
}
}
return result;
}
/// <summary>
/// Helper method for <see cref="RemoveNonSortProperties"/>
/// Checks whether expr has a 'match' in the given list of property expressions.
/// If it does, the matching expression is removed form the list, to speed up future matching.
/// </summary>
/// <param name="expr"></param>
/// <param name="sortList"></param>
/// <param name="exprBindingVariableName"></param>
/// <param name="sortExpressionsBindingVariableName"></param>
/// <returns></returns>
private static bool HasMatchInList(DbPropertyExpression expr, IList<DbPropertyExpression> list, string exprBindingVariableName, string listExpressionsBindingVariableName)
{
for (int i=0; i<list.Count; i++)
{
if (AreMatching(expr, list[i], exprBindingVariableName, listExpressionsBindingVariableName))
{
// This method is used for matching element of two list without duplicates,
// thus if match is found, remove it from the list, to speed up future matching.
list.RemoveAt(i);
return true;
}
}
return false;
}
/// <summary>
/// Determines whether two expressions match.
/// They match if they are of the shape
/// expr1 -> DbPropertyExpression(... (DbPropertyExpression(DbVariableReferenceExpression(expr1BindingVariableName), nameX), ..., name1)
/// expr1 -> DbPropertyExpression(... (DbPropertyExpression(DbVariableReferenceExpression(expr2BindingVariableName), nameX), ..., name1),
///
/// i.e. if they only differ in the name of the binding.
/// </summary>
/// <param name="expr1"></param>
/// <param name="expr2"></param>
/// <param name="expr1BindingVariableName"></param>
/// <param name="expr2BindingVariableName"></param>
/// <returns></returns>
private static bool AreMatching(DbPropertyExpression expr1, DbPropertyExpression expr2, string expr1BindingVariableName, string expr2BindingVariableName)
{
if (expr1.Property.Name != expr2.Property.Name)
{
return false;
}
if (expr1.Instance.ExpressionKind != expr2.Instance.ExpressionKind)
{
return false;
}
if (expr1.Instance.ExpressionKind == DbExpressionKind.Property)
{
return AreMatching((DbPropertyExpression)expr1.Instance, (DbPropertyExpression)expr2.Instance, expr1BindingVariableName, expr2BindingVariableName);
}
DbVariableReferenceExpression instance1 = (DbVariableReferenceExpression)expr1.Instance;
DbVariableReferenceExpression instance2 = (DbVariableReferenceExpression)expr2.Instance;
return (String.Equals(instance1.VariableName, expr1BindingVariableName, StringComparison.Ordinal)
&& String.Equals(instance2.VariableName, expr2BindingVariableName, StringComparison.Ordinal));
}
/// <summary>
/// Helper method for <see cref="TransformIntersectOrExcept(DbExpression left, DbExpression right, DbExpressionKind expressionKind, IList<DbPropertyExpression> sortExpressionsOverLeft, string sortExpressionsBindingVariableName)"/>
/// Creates a <see cref="DbProjectExpression"/> over the given inputBinding that projects out the given flattenedProperties.
/// and updates the flattenedProperties to be over the newly created project.
/// </summary>
/// <param name="inputBinding"></param>
/// <param name="flattenedProperties"></param>
/// <returns>An <see cref="DbExpressionBinding"/> over the newly created <see cref="DbProjectExpression"/></returns>
private DbExpressionBinding CapWithProject(DbExpressionBinding inputBinding, IList<DbPropertyExpression> flattenedProperties)
{
List<KeyValuePair<string, DbExpression>> projectColumns = new List<KeyValuePair<string, DbExpression>>(flattenedProperties.Count);
//List of all the columnNames used in the projection.
Dictionary<string, int> columnNames = new Dictionary<string, int>(flattenedProperties.Count);
foreach (DbPropertyExpression pe in flattenedProperties)
{
//There may be conflicting property names, thus we may need to rename.
string name = pe.Property.Name;
int i;
if (columnNames.TryGetValue(name, out i))
{
string newName;
do
{
++i;
newName = name + i.ToString(System.Globalization.CultureInfo.InvariantCulture);
} while (columnNames.ContainsKey(newName));
columnNames[name] = i;
name = newName;
}
// Add this column name to list of known names so that there are no subsequent
// collisions
columnNames[name] = 0;
projectColumns.Add(new KeyValuePair<string, DbExpression>(name, pe));
}
//Build the project
DbExpression rowExpr = DbExpressionBuilder.NewRow(projectColumns);
DbProjectExpression projectExpression = inputBinding.Project(rowExpr);
//Create the new inputBinding
DbExpressionBinding resultBinding = projectExpression.Bind();
//Create the list of flattenedProperties over the new project
flattenedProperties.Clear();
RowType rowExprType = (RowType)rowExpr.ResultType.EdmType;
foreach (KeyValuePair<string, DbExpression> column in projectColumns)
{
EdmProperty prop = rowExprType.Properties[column.Key];
flattenedProperties.Add(resultBinding.Variable.Property(prop));
}
return resultBinding;
}
#endregion
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub,
out global::System.IntPtr returnFloatingPointReturn4Thunk,
out global::System.IntPtr returnFloatingPointReturn8Thunk)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
global::System.IntPtr unsafe_returnFloatingPointReturn4Thunk;
global::System.IntPtr unsafe_returnFloatingPointReturn8Thunk;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub),
&(unsafe_returnFloatingPointReturn4Thunk),
&(unsafe_returnFloatingPointReturn8Thunk)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
returnFloatingPointReturn8Thunk = unsafe_returnFloatingPointReturn8Thunk;
returnFloatingPointReturn4Thunk = unsafe_returnFloatingPointReturn4Thunk;
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, FormatMessage, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [out] [Mcg.CodeGen.StringBuilderMarshaller] System_Text_StringBuilder__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_System_IntPtr____w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FormatMessage")]
public static int FormatMessage(
int dwFlags,
global::System.IntPtr lpSource_mustBeNull,
uint dwMessageId,
int dwLanguageId,
global::System.Text.StringBuilder lpBuffer,
int nSize,
global::System.IntPtr[] arguments)
{
// Setup
ushort* unsafe_lpBuffer = default(ushort*);
global::System.IntPtr* unsafe_arguments;
int unsafe___value;
try
{
// Marshalling
if (lpBuffer == null)
unsafe_lpBuffer = null;
else
{
unsafe_lpBuffer = (ushort*)global::McgInterop.McgHelpers.CoTaskMemAllocAndZeroMemory(new global::System.IntPtr(checked(lpBuffer.Capacity * 2
+ 2)));
if (unsafe_lpBuffer == null)
throw new global::System.OutOfMemoryException();
}
if (unsafe_lpBuffer != null)
global::System.Runtime.InteropServices.McgMarshal.StringBuilderToUnicodeString(
lpBuffer,
unsafe_lpBuffer
);
fixed (global::System.IntPtr* pinned_arguments = global::McgInterop.McgCoreHelpers.GetArrayForCompat(arguments))
{
unsafe_arguments = (global::System.IntPtr*)pinned_arguments;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.FormatMessage(
dwFlags,
lpSource_mustBeNull,
dwMessageId,
dwLanguageId,
unsafe_lpBuffer,
nSize,
unsafe_arguments
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
}
if (lpBuffer != null)
global::System.Runtime.InteropServices.McgMarshal.UnicodeStringToStringBuilder(
unsafe_lpBuffer,
lpBuffer
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
if (unsafe_lpBuffer != null)
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_lpBuffer);
}
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore_PInvokes", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'clrcompression.dll'
/// </summary>
public unsafe static partial class clrcompression_dll
{
// Signature, deflateInit2_, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateInit2_")]
public static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateInit2_(
((byte*)stream),
level,
method,
windowBits,
memLevel,
strategy,
((byte*)version),
stream_size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateEnd")]
public static int deflateEnd(byte* strm)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateEnd(((byte*)strm));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, inflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "inflateEnd")]
public static int inflateEnd(byte* stream)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.inflateEnd(((byte*)stream));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflate, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflate")]
public static int deflate(
byte* stream,
int flush)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflate(
((byte*)stream),
flush
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-file-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_file_l1_1_0_dll
{
// Signature, GetFileType, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetFileType")]
public static int GetFileType(global::System.Runtime.InteropServices.SafeHandle hFile)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.GetFileType(hFile.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, GetFileAttributesEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem__Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem, [fwd] [in] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableStructMarshaller] Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem____Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetFileAttributesEx")]
public static bool GetFileAttributesEx(
string name,
global::Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem fileInfoLevel,
ref global::Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem lpFileInformation)
{
// Setup
ushort* unsafe_name = default(ushort*);
global::Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem unsafe_lpFileInformation;
int unsafe___value;
// Marshalling
fixed (char* pinned_name = name)
{
unsafe_name = (ushort*)pinned_name;
unsafe_lpFileInformation = lpFileInformation;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.GetFileAttributesEx(
unsafe_name,
fileInfoLevel,
&(unsafe_lpFileInformation)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
lpFileInformation = unsafe_lpFileInformation;
}
// Return
return unsafe___value != 0;
}
// Signature, SetFilePointerEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "SetFilePointerEx")]
public static bool SetFilePointerEx(
global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem hFile,
long liDistanceToMove,
out long lpNewFilePointer,
uint dwMoveMethod)
{
// Setup
bool addRefed = false;
long unsafe_lpNewFilePointer;
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.SetFilePointerEx(
hFile.DangerousGetHandle(),
liDistanceToMove,
&(unsafe_lpNewFilePointer),
dwMoveMethod
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
lpNewFilePointer = unsafe_lpNewFilePointer;
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value != 0;
}
// Signature, SetEndOfFile, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "SetEndOfFile")]
public static bool SetEndOfFile(global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem hFile)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.SetEndOfFile(hFile.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value != 0;
}
// Signature, FindFirstFileEx, [fwd] [return] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFindHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem__Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem, [fwd] [in] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.StructMarshaller] Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem____Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem__Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FindFirstFileEx")]
public static global::Microsoft.Win32.SafeHandles.SafeFindHandle__System_IO_FileSystem FindFirstFileEx(
string lpFileName,
global::Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem fInfoLevelId,
ref global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem lpFindFileData,
global::Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem fSearchOp,
global::System.IntPtr lpSearchFilter,
int dwAdditionalFlags)
{
// Setup
ushort* unsafe_lpFileName = default(ushort*);
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.UnsafeType unsafe_lpFindFileData = default(global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.UnsafeType);
global::Microsoft.Win32.SafeHandles.SafeFindHandle__System_IO_FileSystem __value;
global::System.IntPtr unsafe___value;
// Marshalling
fixed (char* pinned_lpFileName = lpFileName)
{
unsafe_lpFileName = (ushort*)pinned_lpFileName;
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.Marshal__SafeToUnsafe(
ref lpFindFileData,
out unsafe_lpFindFileData
);
__value = new global::Microsoft.Win32.SafeHandles.SafeFindHandle__System_IO_FileSystem();
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.FindFirstFileEx(
unsafe_lpFileName,
fInfoLevelId,
&(unsafe_lpFindFileData),
fSearchOp,
lpSearchFilter,
dwAdditionalFlags
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::System.Runtime.InteropServices.McgMarshal.InitializeHandle(
__value,
unsafe___value
);
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.Marshal__UnsafeToSafe(
ref unsafe_lpFindFileData,
out lpFindFileData
);
}
// Return
return __value;
}
// Signature, ReadFile, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_Threading_NativeOverlapped__System_Threading_Overlapped___ptrSystem_Threading__NativeOverlapped__System_Threading_Overlapped *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "ReadFile")]
public static int ReadFile(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToRead,
global::System.IntPtr numBytesRead_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* overlapped)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.ReadFile(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToRead,
numBytesRead_mustBeZero,
((global::System.Threading.NativeOverlapped__System_Threading_Overlapped*)overlapped)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, ReadFile__0, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "ReadFile")]
public static int ReadFile__0(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToRead,
out int numBytesRead,
global::System.IntPtr mustBeZero)
{
// Setup
bool addRefed = false;
int unsafe_numBytesRead;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.ReadFile__0(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToRead,
&(unsafe_numBytesRead),
mustBeZero
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
numBytesRead = unsafe_numBytesRead;
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, WriteFile, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_Threading_NativeOverlapped__System_Threading_Overlapped___ptrSystem_Threading__NativeOverlapped__System_Threading_Overlapped *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "WriteFile")]
public static int WriteFile(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToWrite,
global::System.IntPtr numBytesWritten_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.WriteFile(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToWrite,
numBytesWritten_mustBeZero,
((global::System.Threading.NativeOverlapped__System_Threading_Overlapped*)lpOverlapped)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, WriteFile__0, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "WriteFile")]
public static int WriteFile__0(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToWrite,
out int numBytesWritten,
global::System.IntPtr mustBeZero)
{
// Setup
bool addRefed = false;
int unsafe_numBytesWritten;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.WriteFile__0(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToWrite,
&(unsafe_numBytesWritten),
mustBeZero
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
numBytesWritten = unsafe_numBytesWritten;
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, FindClose, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FindClose")]
public static bool FindClose(global::System.IntPtr hFindFile)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.FindClose(hFindFile);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
// Signature, FlushFileBuffers, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FlushFileBuffers")]
public static bool FlushFileBuffers(global::System.Runtime.InteropServices.SafeHandle hHandle)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
hHandle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.FlushFileBuffers(hHandle.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
hHandle.DangerousRelease();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-file-l2-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_file_l2_1_0_dll
{
// Signature, GetFileInformationByHandleEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem__Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.StructMarshaller] Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem____Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetFileInformationByHandleEx")]
public static bool GetFileInformationByHandleEx(
global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem hFile,
global::Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem FileInformationClass,
out global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem lpFileInformation,
uint dwBufferSize)
{
// Setup
bool addRefed = false;
global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType unsafe_lpFileInformation = default(global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType);
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
unsafe_lpFileInformation = default(global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l2_1_0_dll_PInvokes.GetFileInformationByHandleEx(
hFile.DangerousGetHandle(),
FileInformationClass,
&(unsafe_lpFileInformation),
dwBufferSize
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.Marshal__UnsafeToSafe(
ref unsafe_lpFileInformation,
out lpFileInformation
);
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-threadpool-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_threadpool_l1_2_0_dll
{
// Signature, CreateThreadpoolIo, [fwd] [return] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeThreadPoolIOHandle__System_Threading_Overlapped____w64 int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.PInvokeDelegateMarshaller] Interop_NativeIoCompletionCallback__System_Threading_Overlapped____Interop_NativeIoCompletionCallback__System_Threading_Overlapped, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CreateThreadpoolIo")]
public static global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped CreateThreadpoolIo(
global::System.Runtime.InteropServices.SafeHandle fl,
global::Interop_NativeIoCompletionCallback__System_Threading_Overlapped pfnio,
global::System.IntPtr context,
global::System.IntPtr pcbe)
{
// Setup
bool addRefed = false;
void* unsafe_pfnio = default(void*);
global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped __value;
global::System.IntPtr unsafe___value;
try
{
// Marshalling
fl.DangerousAddRef(ref addRefed);
unsafe_pfnio = (void*)global::System.Runtime.InteropServices.McgModuleManager.GetStubForPInvokeDelegate(
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("Interop+NativeIoCompletionCallback,System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken" +
"=b03f5f7f11d50a3a"),
pfnio
);
__value = new global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped();
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.CreateThreadpoolIo(
fl.DangerousGetHandle(),
unsafe_pfnio,
context,
pcbe
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::System.Runtime.InteropServices.McgMarshal.InitializeHandle(
__value,
unsafe___value
);
if (addRefed)
fl.DangerousRelease();
// Return
return __value;
}
finally
{
// Cleanup
global::System.GC.KeepAlive(pfnio);
}
}
// Signature, CloseThreadpoolIo, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseThreadpoolIo")]
public static void CloseThreadpoolIo(global::System.IntPtr pio)
{
// Marshalling
// Call to native method
global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.CloseThreadpoolIo(pio);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, StartThreadpoolIo, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeThreadPoolIOHandle__System_Threading_Overlapped____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "StartThreadpoolIo")]
public static void StartThreadpoolIo(global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped pio)
{
// Setup
bool addRefed = false;
// Marshalling
pio.DangerousAddRef(ref addRefed);
// Call to native method
global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.StartThreadpoolIo(pio.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
if (addRefed)
pio.DangerousRelease();
// Return
}
// Signature, CancelThreadpoolIo, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeThreadPoolIOHandle__System_Threading_Overlapped____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CancelThreadpoolIo")]
public static void CancelThreadpoolIo(global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped pio)
{
// Setup
bool addRefed = false;
// Marshalling
pio.DangerousAddRef(ref addRefed);
// Call to native method
global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.CancelThreadpoolIo(pio.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
if (addRefed)
pio.DangerousRelease();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-file-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_file_l1_2_0_dll
{
// Signature, CreateFile2, [fwd] [return] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] System_IO_FileShare__System_IO_FileSystem_Primitives__FileShare__System_IO_FileSystem_Primitives, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] System_IO_FileMode__System_IO_FileSystem_Primitives__FileMode__System_IO_FileSystem_Primitives, [fwd] [in] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableStructMarshaller] Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem____Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CreateFile2")]
public static global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem CreateFile2(
string lpFileName,
int dwDesiredAccess,
global::System.IO.FileShare__System_IO_FileSystem_Primitives dwShareMode,
global::System.IO.FileMode__System_IO_FileSystem_Primitives dwCreationDisposition,
ref global::Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem parameters)
{
// Setup
ushort* unsafe_lpFileName = default(ushort*);
global::Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem unsafe_parameters;
global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem __value;
global::System.IntPtr unsafe___value;
// Marshalling
fixed (char* pinned_lpFileName = lpFileName)
{
unsafe_lpFileName = (ushort*)pinned_lpFileName;
unsafe_parameters = parameters;
__value = new global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem();
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_2_0_dll_PInvokes.CreateFile2(
unsafe_lpFileName,
dwDesiredAccess,
dwShareMode,
dwCreationDisposition,
&(unsafe_parameters)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::System.Runtime.InteropServices.McgMarshal.InitializeHandle(
__value,
unsafe___value
);
}
// Return
return __value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-handle-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll
{
// Signature, CloseHandle, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseHandle")]
public static bool CloseHandle(global::System.IntPtr handle)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_handle_l1_1_0_dll_PInvokes.CloseHandle(handle);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-io-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_io_l1_1_0_dll
{
// Signature, CancelIoEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_Threading_NativeOverlapped__System_Threading_Overlapped___ptrSystem_Threading__NativeOverlapped__System_Threading_Overlapped *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CancelIoEx")]
public static bool CancelIoEx(
global::System.Runtime.InteropServices.SafeHandle handle,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_io_l1_1_0_dll_PInvokes.CancelIoEx(
handle.DangerousGetHandle(),
((global::System.Threading.NativeOverlapped__System_Threading_Overlapped*)lpOverlapped)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value != 0;
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub,
global::System.IntPtr* returnFloatingPointReturn4Thunk,
global::System.IntPtr* returnFloatingPointReturn8Thunk);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", EntryPoint="FormatMessageW", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int FormatMessage(
int dwFlags,
global::System.IntPtr lpSource_mustBeNull,
uint dwMessageId,
int dwLanguageId,
ushort* lpBuffer,
int nSize,
global::System.IntPtr* arguments);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class clrcompression_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateEnd(byte* strm);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int inflateEnd(byte* stream);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflate(
byte* stream,
int flush);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_file_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetFileType(global::System.IntPtr hFile);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="GetFileAttributesExW", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetFileAttributesEx(
ushort* name,
global::Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem fileInfoLevel,
global::Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem* lpFileInformation);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int SetFilePointerEx(
global::System.IntPtr hFile,
long liDistanceToMove,
long* lpNewFilePointer,
uint dwMoveMethod);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int SetEndOfFile(global::System.IntPtr hFile);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="FindFirstFileExW", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static global::System.IntPtr FindFirstFileEx(
ushort* lpFileName,
global::Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem fInfoLevelId,
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.UnsafeType* lpFindFileData,
global::Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem fSearchOp,
global::System.IntPtr lpSearchFilter,
int dwAdditionalFlags);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ReadFile(
global::System.IntPtr handle,
byte* bytes,
int numBytesToRead,
global::System.IntPtr numBytesRead_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* overlapped);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="ReadFile", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ReadFile__0(
global::System.IntPtr handle,
byte* bytes,
int numBytesToRead,
int* numBytesRead,
global::System.IntPtr mustBeZero);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int WriteFile(
global::System.IntPtr handle,
byte* bytes,
int numBytesToWrite,
global::System.IntPtr numBytesWritten_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="WriteFile", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int WriteFile__0(
global::System.IntPtr handle,
byte* bytes,
int numBytesToWrite,
int* numBytesWritten,
global::System.IntPtr mustBeZero);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int FindClose(global::System.IntPtr hFindFile);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int FlushFileBuffers(global::System.IntPtr hHandle);
}
public unsafe static partial class api_ms_win_core_file_l2_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l2-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetFileInformationByHandleEx(
global::System.IntPtr hFile,
global::Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem FileInformationClass,
global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType* lpFileInformation,
uint dwBufferSize);
}
public unsafe static partial class api_ms_win_core_threadpool_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static global::System.IntPtr CreateThreadpoolIo(
global::System.IntPtr fl,
void* pfnio,
global::System.IntPtr context,
global::System.IntPtr pcbe);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CloseThreadpoolIo(global::System.IntPtr pio);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void StartThreadpoolIo(global::System.IntPtr pio);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CancelThreadpoolIo(global::System.IntPtr pio);
}
public unsafe static partial class api_ms_win_core_file_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static global::System.IntPtr CreateFile2(
ushort* lpFileName,
int dwDesiredAccess,
global::System.IO.FileShare__System_IO_FileSystem_Primitives dwShareMode,
global::System.IO.FileMode__System_IO_FileSystem_Primitives dwCreationDisposition,
global::Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem* parameters);
}
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-handle-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CloseHandle(global::System.IntPtr handle);
}
public unsafe static partial class api_ms_win_core_io_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-io-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CancelIoEx(
global::System.IntPtr handle,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal abstract class EditAndContinueTestHelpers
{
public abstract AbstractEditAndContinueAnalyzer Analyzer { get; }
public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span);
public abstract SyntaxTree ParseText(string source);
public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees);
public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method);
internal void VerifyUnchangedDocument(
string source,
ActiveStatementSpan[] oldActiveStatements,
TextSpan?[] trackingSpansOpt,
TextSpan[] expectedNewActiveStatements,
ImmutableArray<TextSpan>[] expectedOldExceptionRegions,
ImmutableArray<TextSpan>[] expectedNewExceptionRegions)
{
var text = SourceText.From(source);
var tree = ParseText(source);
var root = tree.GetRoot();
tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (trackingSpansOpt != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt);
}
else
{
trackingService = null;
}
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
Analyzer.AnalyzeUnchangedDocument(
oldActiveStatements.AsImmutable(),
text,
root,
documentId,
trackingService,
actualNewActiveStatements,
actualNewExceptionRegions);
// check active statements:
AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements, source, text);
// check new exception regions:
Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < expectedNewExceptionRegions.Length; i++)
{
AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text);
}
}
internal void VerifyRudeDiagnostics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription description,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var oldActiveStatements = description.OldSpans;
if (description.TrackingSpans != null)
{
Assert.Equal(oldActiveStatements.Length, description.TrackingSpans.Length);
}
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length];
var updatedActiveMethodMatches = new List<ValueTuple<int, Match<SyntaxNode>>>();
var editMap = Analyzer.BuildEditMap(editScript);
DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");
TestActiveStatementTrackingService trackingService;
if (description.TrackingSpans != null)
{
trackingService = new TestActiveStatementTrackingService(documentId, description.TrackingSpans);
}
else
{
trackingService = null;
}
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
documentId,
trackingService,
oldActiveStatements.AsImmutable(),
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource, expectedDiagnostics);
// check active statements:
AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText);
if (diagnostics.Count == 0)
{
// check old exception regions:
for (int i = 0; i < oldActiveStatements.Length; i++)
{
var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
oldText,
editScript.Match.OldRoot,
oldActiveStatements[i].Span,
isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0);
AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
}
// check new exception regions:
Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
for (int i = 0; i < description.NewRegions.Length; i++)
{
AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
}
}
else
{
for (int i = 0; i < oldActiveStatements.Length; i++)
{
Assert.Equal(0, description.NewRegions[i].Length);
}
}
if (description.TrackingSpans != null)
{
AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s));
}
}
internal void VerifyLineEdits(
EditScript<SyntaxNode> editScript,
IEnumerable<LineChange> expectedLineEdits,
IEnumerable<string> expectedNodeUpdates,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
var diagnostics = new List<RudeEditDiagnostic>();
var editMap = Analyzer.BuildEditMap(editScript);
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n");
var actualNodeUpdates = triviaEdits.Select(e => e.Value.ToString().ToLines().First());
AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n");
}
internal void VerifySemantics(
EditScript<SyntaxNode> editScript,
ActiveStatementsDescription activeStatements,
IEnumerable<string> additionalOldSources,
IEnumerable<string> additionalNewSources,
SemanticEditDescription[] expectedSemanticEdits,
RudeEditDiagnosticDescription[] expectedDiagnostics)
{
var editMap = Analyzer.BuildEditMap(editScript);
var oldRoot = editScript.Match.OldRoot;
var newRoot = editScript.Match.NewRoot;
var oldSource = oldRoot.SyntaxTree.ToString();
var newSource = newRoot.SyntaxTree.ToString();
var oldText = SourceText.From(oldSource);
var newText = SourceText.From(newSource);
IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree };
IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree };
if (additionalOldSources != null)
{
oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s)));
}
if (additionalOldSources != null)
{
newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s)));
}
var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
var newCompilation = CreateLibraryCompilation("New", newTrees);
oldTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
newTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify();
var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);
var oldActiveStatements = activeStatements.OldSpans.AsImmutable();
var updatedActiveMethodMatches = new List<ValueTuple<int, Match<SyntaxNode>>>();
var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>();
var actualLineEdits = new List<LineChange>();
var actualSemanticEdits = new List<SemanticEdit>();
var diagnostics = new List<RudeEditDiagnostic>();
var actualNewActiveStatements = new LinePositionSpan[activeStatements.OldSpans.Length];
var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldSpans.Length];
Analyzer.AnalyzeSyntax(
editScript,
editMap,
oldText,
newText,
null,
null,
oldActiveStatements,
actualNewActiveStatements,
actualNewExceptionRegions,
updatedActiveMethodMatches,
diagnostics);
diagnostics.Verify(newSource);
Analyzer.AnalyzeTrivia(
oldText,
newText,
editScript.Match,
editMap,
triviaEdits,
actualLineEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource);
Analyzer.AnalyzeSemantics(
editScript,
editMap,
oldText,
oldActiveStatements,
triviaEdits,
updatedActiveMethodMatches,
oldModel,
newModel,
actualSemanticEdits,
diagnostics,
default(CancellationToken));
diagnostics.Verify(newSource, expectedDiagnostics);
if (expectedSemanticEdits == null)
{
return;
}
Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count);
for (int i = 0; i < actualSemanticEdits.Count; i++)
{
var editKind = expectedSemanticEdits[i].Kind;
Assert.Equal(editKind, actualSemanticEdits[i].Kind);
var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null;
var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation);
var actualOldSymbol = actualSemanticEdits[i].OldSymbol;
var actualNewSymbol = actualSemanticEdits[i].NewSymbol;
Assert.Equal(expectedOldSymbol, actualOldSymbol);
Assert.Equal(expectedNewSymbol, actualNewSymbol);
var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap;
var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap;
Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables);
if (expectedSyntaxMap != null)
{
Assert.NotNull(actualSyntaxMap);
Assert.True(expectedSemanticEdits[i].PreserveLocalVariables);
var newNodes = new List<SyntaxNode>();
foreach (var expectedSpanMapping in expectedSyntaxMap)
{
var newNode = FindNode(newRoot, expectedSpanMapping.Value);
var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key);
var actualOldNode = actualSyntaxMap(newNode);
Assert.Equal(expectedOldNode, actualOldNode);
newNodes.Add(newNode);
}
AssertEx.SetEqual(newNodes, GetDeclarators(actualNewSymbol));
}
else
{
Assert.Null(actualSyntaxMap);
}
}
}
private static void AssertSpansEqual(IList<TextSpan> expected, IList<LinePositionSpan> actual, string newSource, SourceText newText)
{
AssertEx.Equal(
expected,
actual.Select(span => newText.Lines.GetTextSpan(span)),
itemSeparator: "\r\n",
itemInspector: s => DisplaySpan(newSource, s));
}
private static string DisplaySpan(string source, TextSpan span)
{
return span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]";
}
}
internal static class EditScriptTestUtils
{
public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected)
{
AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n");
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PCSComUtils.Common;
namespace PCSUtils.Utils
{
/// <summary>
/// Summary description for MessageBoxFormForItems.
/// </summary>
public class MessageBoxFormForItems : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnClose;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public string FormTitle;
public string MessageDescription;
private C1.Win.C1TrueDBGrid.C1TrueDBGrid dgrdData;
public System.Windows.Forms.Label lblPrimaryVendor;
public System.Windows.Forms.Label lblListPrice;
public System.Windows.Forms.Label lblTitle;
public System.Windows.Forms.Label lblVendorCurrency;
public System.Windows.Forms.Label lblExchangeRate;
public System.Windows.Forms.Label lblVendorLoc;
public System.Windows.Forms.Label lblProductionLine;
public System.Windows.Forms.Label lblVendorDeliverySchedule;
public DataTable BugReason;
public MessageBoxFormForItems()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
private void btnClose_Click(object sender, System.EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
this.Close();
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
private void MessageBoxFormForItems_Load(object sender, System.EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
new Security().SetRightForUserOnForm(this, SystemProperty.UserName);
DataTable dtbGridLayOut = FormControlComponents.StoreGridLayout(dgrdData);
dgrdData.DataSource = BugReason;
//Restore layout
FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayOut);
this.MaximizeBox = false;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
/// <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(MessageBoxFormForItems));
this.lblTitle = new System.Windows.Forms.Label();
this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.btnClose = new System.Windows.Forms.Button();
this.lblPrimaryVendor = new System.Windows.Forms.Label();
this.lblListPrice = new System.Windows.Forms.Label();
this.lblVendorLoc = new System.Windows.Forms.Label();
this.lblVendorCurrency = new System.Windows.Forms.Label();
this.lblExchangeRate = new System.Windows.Forms.Label();
this.lblProductionLine = new System.Windows.Forms.Label();
this.lblVendorDeliverySchedule = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit();
this.SuspendLayout();
//
// lblTitle
//
this.lblTitle.Location = new System.Drawing.Point(6, 2);
this.lblTitle.Name = "lblTitle";
this.lblTitle.Size = new System.Drawing.Size(672, 23);
this.lblTitle.TabIndex = 0;
this.lblTitle.Text = "The list of items which is not enough information";
this.lblTitle.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// dgrdData
//
this.dgrdData.AllowUpdate = false;
this.dgrdData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dgrdData.CaptionHeight = 17;
this.dgrdData.CollapseColor = System.Drawing.Color.Black;
this.dgrdData.ExpandColor = System.Drawing.Color.Black;
this.dgrdData.GroupByCaption = "Drag a column header here to group by that column";
this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.dgrdData.Location = new System.Drawing.Point(6, 26);
this.dgrdData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.dgrdData.Name = "dgrdData";
this.dgrdData.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.dgrdData.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.dgrdData.PreviewInfo.ZoomFactor = 75;
this.dgrdData.PrintInfo.ShowOptionsDialog = false;
this.dgrdData.RecordSelectorWidth = 16;
this.dgrdData.RowDivider.Color = System.Drawing.Color.DarkGray;
this.dgrdData.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.Single;
this.dgrdData.RowHeight = 15;
this.dgrdData.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.dgrdData.Size = new System.Drawing.Size(622, 397);
this.dgrdData.TabIndex = 1;
this.dgrdData.PropBag = "<?xml version=\"1.0\"?><Blob><DataCols><C1DataColumn Level=\"0\" Caption=\"Part Number" +
"\" DataField=\"Code\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level" +
"=\"0\" Caption=\"Part Name\" DataField=\"Description\"><ValueItems /><GroupInfo /></C1" +
"DataColumn><C1DataColumn Level=\"0\" Caption=\"Model\" DataField=\"Revision\"><ValueIt" +
"ems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Lack of infor" +
"mation\" DataField=\"Reason\"><ValueItems /><GroupInfo /></C1DataColumn></DataCols>" +
"<Styles type=\"C1.Win.C1TrueDBGrid.Design.ContextWrapper\"><Data>HighlightRow{Fore" +
"Color:HighlightText;BackColor:Highlight;}Caption{AlignHorz:Center;}Normal{}Style" +
"25{}Selected{ForeColor:HighlightText;BackColor:Highlight;}Editor{}Style18{}Style" +
"19{}Style14{}Style15{}Style16{AlignHorz:Center;}Style17{AlignHorz:Near;}Style10{" +
"AlignHorz:Near;}Style11{}OddRow{}Style13{}Style12{}Style32{}Style33{}Style31{}Fo" +
"oter{}Style29{AlignHorz:Near;}Style28{AlignHorz:Center;}Style27{}Style26{}Record" +
"Selector{AlignImage:Center;}Style24{}Style23{AlignHorz:Near;}Style22{AlignHorz:C" +
"enter;}Style21{}Style20{}Group{BackColor:ControlDark;Border:None,,0, 0, 0, 0;Ali" +
"gnVert:Center;}Inactive{ForeColor:InactiveCaptionText;BackColor:InactiveCaption;" +
"}EvenRow{BackColor:Aqua;}Heading{Wrap:True;AlignVert:Center;Border:Raised,,1, 1," +
" 1, 1;ForeColor:ControlText;BackColor:Control;}Style7{}Style8{}FilterBar{}Style5" +
"{}Style4{}Style9{}Style38{}Style39{}Style36{}Style37{}Style34{AlignHorz:Center;}" +
"Style35{AlignHorz:Near;}Style6{}Style1{}Style30{}Style3{}Style2{}</Data></Styles" +
"><Splits><C1.Win.C1TrueDBGrid.MergeView Name=\"\" CaptionHeight=\"17\" ColumnCaption" +
"Height=\"17\" ColumnFooterHeight=\"17\" MarqueeStyle=\"DottedCellBorder\" RecordSelect" +
"orWidth=\"16\" DefRecSelWidth=\"16\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"" +
"1\"><ClientRect>0, 0, 618, 393</ClientRect><BorderSide>0</BorderSide><CaptionStyl" +
"e parent=\"Style2\" me=\"Style10\" /><EditorStyle parent=\"Editor\" me=\"Style5\" /><Eve" +
"nRowStyle parent=\"EvenRow\" me=\"Style8\" /><FilterBarStyle parent=\"FilterBar\" me=\"" +
"Style13\" /><FooterStyle parent=\"Footer\" me=\"Style3\" /><GroupStyle parent=\"Group\"" +
" me=\"Style12\" /><HeadingStyle parent=\"Heading\" me=\"Style2\" /><HighLightRowStyle " +
"parent=\"HighlightRow\" me=\"Style7\" /><InactiveStyle parent=\"Inactive\" me=\"Style4\"" +
" /><OddRowStyle parent=\"OddRow\" me=\"Style9\" /><RecordSelectorStyle parent=\"Recor" +
"dSelector\" me=\"Style11\" /><SelectedStyle parent=\"Selected\" me=\"Style6\" /><Style " +
"parent=\"Normal\" me=\"Style1\" /><internalCols><C1DisplayColumn><HeadingStyle paren" +
"t=\"Style2\" me=\"Style16\" /><Style parent=\"Style1\" me=\"Style17\" /><FooterStyle par" +
"ent=\"Style3\" me=\"Style18\" /><EditorStyle parent=\"Style5\" me=\"Style19\" /><GroupHe" +
"aderStyle parent=\"Style1\" me=\"Style21\" /><GroupFooterStyle parent=\"Style1\" me=\"S" +
"tyle20\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><" +
"Width>128</Width><Height>15</Height><DCIdx>0</DCIdx></C1DisplayColumn><C1Display" +
"Column><HeadingStyle parent=\"Style2\" me=\"Style22\" /><Style parent=\"Style1\" me=\"S" +
"tyle23\" /><FooterStyle parent=\"Style3\" me=\"Style24\" /><EditorStyle parent=\"Style" +
"5\" me=\"Style25\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style27\" /><GroupFooterS" +
"tyle parent=\"Style1\" me=\"Style26\" /><Visible>True</Visible><ColumnDivider>DarkGr" +
"ay,Single</ColumnDivider><Width>201</Width><Height>15</Height><DCIdx>1</DCIdx></" +
"C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style28\" /><S" +
"tyle parent=\"Style1\" me=\"Style29\" /><FooterStyle parent=\"Style3\" me=\"Style30\" />" +
"<EditorStyle parent=\"Style5\" me=\"Style31\" /><GroupHeaderStyle parent=\"Style1\" me" +
"=\"Style33\" /><GroupFooterStyle parent=\"Style1\" me=\"Style32\" /><Visible>True</Vis" +
"ible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>70</Width><Height>15</" +
"Height><DCIdx>2</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"" +
"Style2\" me=\"Style34\" /><Style parent=\"Style1\" me=\"Style35\" /><FooterStyle parent" +
"=\"Style3\" me=\"Style36\" /><EditorStyle parent=\"Style5\" me=\"Style37\" /><GroupHeade" +
"rStyle parent=\"Style1\" me=\"Style39\" /><GroupFooterStyle parent=\"Style1\" me=\"Styl" +
"e38\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Wid" +
"th>248</Width><Height>15</Height><DCIdx>3</DCIdx></C1DisplayColumn></internalCol" +
"s></C1.Win.C1TrueDBGrid.MergeView></Splits><NamedStyles><Style parent=\"\" me=\"Nor" +
"mal\" /><Style parent=\"Normal\" me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\"" +
" /><Style parent=\"Heading\" me=\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" " +
"/><Style parent=\"Normal\" me=\"Selected\" /><Style parent=\"Normal\" me=\"Editor\" /><S" +
"tyle parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=\"EvenRow\" /><" +
"Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"RecordSelector\" " +
"/><Style parent=\"Normal\" me=\"FilterBar\" /><Style parent=\"Caption\" me=\"Group\" /><" +
"/NamedStyles><vertSplits>1</vertSplits><horzSplits>1</horzSplits><Layout>Modifie" +
"d</Layout><DefaultRecSelWidth>16</DefaultRecSelWidth><ClientArea>0, 0, 618, 393<" +
"/ClientArea><PrintPageHeaderStyle parent=\"\" me=\"Style14\" /><PrintPageFooterStyle" +
" parent=\"\" me=\"Style15\" /></Blob>";
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.Location = new System.Drawing.Point(558, 428);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(70, 23);
this.btnClose.TabIndex = 2;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// lblPrimaryVendor
//
this.lblPrimaryVendor.Location = new System.Drawing.Point(56, 80);
this.lblPrimaryVendor.Name = "lblPrimaryVendor";
this.lblPrimaryVendor.TabIndex = 3;
this.lblPrimaryVendor.Text = "Primary Vendor";
this.lblPrimaryVendor.Visible = false;
//
// lblListPrice
//
this.lblListPrice.Location = new System.Drawing.Point(56, 100);
this.lblListPrice.Name = "lblListPrice";
this.lblListPrice.TabIndex = 4;
this.lblListPrice.Text = "Purchasing Price";
this.lblListPrice.Visible = false;
//
// lblVendorLoc
//
this.lblVendorLoc.Location = new System.Drawing.Point(56, 122);
this.lblVendorLoc.Name = "lblVendorLoc";
this.lblVendorLoc.TabIndex = 5;
this.lblVendorLoc.Text = "Vendor\'s Location";
this.lblVendorLoc.Visible = false;
//
// lblVendorCurrency
//
this.lblVendorCurrency.Location = new System.Drawing.Point(56, 144);
this.lblVendorCurrency.Name = "lblVendorCurrency";
this.lblVendorCurrency.TabIndex = 6;
this.lblVendorCurrency.Text = "Vendor\'s Currency";
this.lblVendorCurrency.Visible = false;
//
// lblExchangeRate
//
this.lblExchangeRate.Location = new System.Drawing.Point(222, 130);
this.lblExchangeRate.Name = "lblExchangeRate";
this.lblExchangeRate.Size = new System.Drawing.Size(140, 23);
this.lblExchangeRate.TabIndex = 7;
this.lblExchangeRate.Text = "Currency Exchange Rate";
this.lblExchangeRate.Visible = false;
//
// lblProductionLine
//
this.lblProductionLine.Location = new System.Drawing.Point(224, 152);
this.lblProductionLine.Name = "lblProductionLine";
this.lblProductionLine.Size = new System.Drawing.Size(140, 23);
this.lblProductionLine.TabIndex = 8;
this.lblProductionLine.Text = "Production Line";
this.lblProductionLine.Visible = false;
//
// lblVendorDeliverySchedule
//
this.lblVendorDeliverySchedule.Location = new System.Drawing.Point(222, 176);
this.lblVendorDeliverySchedule.Name = "lblVendorDeliverySchedule";
this.lblVendorDeliverySchedule.Size = new System.Drawing.Size(148, 23);
this.lblVendorDeliverySchedule.TabIndex = 9;
this.lblVendorDeliverySchedule.Text = "Vendor\'s Delivery Schedule";
this.lblVendorDeliverySchedule.Visible = false;
//
// MessageBoxFormForItems
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(634, 455);
this.Controls.Add(this.lblVendorDeliverySchedule);
this.Controls.Add(this.lblProductionLine);
this.Controls.Add(this.lblExchangeRate);
this.Controls.Add(this.lblVendorCurrency);
this.Controls.Add(this.lblVendorLoc);
this.Controls.Add(this.lblListPrice);
this.Controls.Add(this.lblPrimaryVendor);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.dgrdData);
this.Controls.Add(this.lblTitle);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Name = "MessageBoxFormForItems";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "PCS Message Box";
this.Load += new System.EventHandler(this.MessageBoxFormForItems_Load);
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit();
this.ResumeLayout(false);
}
#endregion
public MessageBoxFormForItems(string pstrFormTitle, string pstrMessageDes, DataTable pdtbSource)
{
FormTitle = pstrFormTitle;
if (pstrFormTitle != null && pstrFormTitle.Trim() != string.Empty)
lblTitle.Text = pstrFormTitle;
MessageDescription = pstrMessageDes;
BugReason = pdtbSource;
}
public MessageBoxFormForItems(DataTable pdtbSource)
{
BugReason = pdtbSource;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace iNQUIRE.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
namespace Schema.NET.Test;
using System;
using Xunit;
public class ThingTest
{
private readonly Thing thing = new()
{
Name = "New Object",
Description = "This is the description of a new object we can't deserialize",
Image = new Uri("https://example.com/image.jpg"),
};
private readonly string json =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"NewObject\"," +
"\"name\":\"New Object\"," +
"\"description\":\"This is the description of a new object we can't deserialize\"," +
"\"image\":\"https://example.com/image.jpg\"," +
"\"someProperty\":\"not supported\"" +
"}";
[Fact]
public void Deserializing_NewObjectJsonLd_ReturnsThing() =>
Assert.Equal(
this.thing.ToString(),
SchemaSerializer.DeserializeObject<Thing>(this.json)!.ToString());
[Fact]
public void Equality_AreEqual_Default() => CompareEqual(new Thing(), new Thing());
[Fact]
public void Equality_AreEqual_SinglePropertyValue() => CompareEqual(
new Thing
{
Name = "Custom Name",
},
new Thing
{
Name = "Custom Name",
});
[Fact]
public void Equality_AreEqual_MultiPropertyValue() => CompareEqual(
new Thing
{
Name = "Custom Name",
Url = new Uri("https://schema.net"),
},
new Thing
{
Name = "Custom Name",
Url = new Uri("https://schema.net"),
});
[Fact]
public void Equality_AreNotEqual_Null() => CompareNotEqual(
new Thing
{
Name = "A",
},
null!);
[Fact]
public void Equality_AreNotEqual_SinglePropertyValue() => CompareNotEqual(
new Thing
{
Name = "A",
},
new Thing
{
Name = "B",
});
[Fact]
public void Equality_AreNotEqual_MultiPropertyValue() => CompareNotEqual(
new Thing
{
Name = "A",
Url = new Uri("https://schema.net"),
},
new Thing
{
Name = "B",
Url = new Uri("https://schema.net/Thing"),
});
[Fact]
public void Equality_AreNotEqual_DifferentTypes_SameBaseProperties() => CompareNotEqual(
new Thing
{
Name = "Person Name",
Url = new Uri("https://schema.net"),
},
new Person
{
Name = "Person Name",
Url = new Uri("https://schema.net"),
});
[Fact]
public void Equality_AreEqual_SameDerivedType_SameBaseProperties() => CompareEqual(
new Person
{
Name = "Person Name",
Url = new Uri("https://schema.net"),
},
new Person
{
Name = "Person Name",
Url = new Uri("https://schema.net"),
});
[Fact]
public void Equality_AreEqual_SameDerivedType_SameDerivedProperties() => CompareEqual(
new Person
{
AdditionalName = "Extra Name",
},
new Person
{
AdditionalName = "Extra Name",
});
[Fact]
public void Equality_AreNotEqual_SameDerivedType_DifferentBaseProperties() => CompareNotEqual(
new Person
{
Name = "A",
},
new Person
{
Name = "B",
});
[Fact]
public void Equality_AreNotEqual_SameDerivedType_DifferentDerivedProperties() => CompareNotEqual(
new Person
{
AdditionalName = "A",
},
new Person
{
AdditionalName = "B",
});
[Fact]
public void ToString_UnsafeStringData_ReturnsExpectedJsonLd()
{
var expectedJson =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"Thing\"," +
"\"name\":\"Test</script><script>alert('gotcha');</script>\"" +
"}";
var thing = new Thing
{
Name = "Test</script><script>alert('gotcha');</script>",
};
Assert.Equal(expectedJson, thing.ToString());
}
[Fact]
public void ToHtmlEscapedString_UnsafeStringData_ReturnsExpectedJsonLd()
{
var expectedJson =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"Thing\"," +
"\"name\":\"Test\\u003c/script\\u003e\\u003cscript\\u003ealert(\\u0027gotcha\\u0027);\\u003c/script\\u003e\"" +
"}";
var thing = new Thing
{
Name = "Test</script><script>alert('gotcha');</script>",
};
Assert.Equal(expectedJson, thing.ToHtmlEscapedString(), ignoreCase: true);
}
[Fact]
public void ToStringWithNullAssignedProperty_ReturnsExpectedJsonLd()
{
var expectedJson =
"{" +
"\"@context\":\"https://schema.org\"," +
"\"@type\":\"Thing\"" +
"}";
var thing = new Thing
{
Name = (string)null!,
};
Assert.Equal(expectedJson, thing.ToString());
}
[Fact]
public void TrySetValue_ValidProperty()
{
var thing = new Thing();
Assert.True(thing.TrySetValue("Name", new[] { "TestName" }));
Assert.Equal("TestName", thing.Name);
}
[Fact]
public void TrySetValue_InvalidProperty()
{
var thing = new Thing();
Assert.False(thing.TrySetValue("InvalidName", new[] { "TestName" }));
}
[Fact]
public void TrySetValue_CaseInsensitive()
{
var thing = new Thing();
Assert.True(thing.TrySetValue("name", new[] { "TestName" }));
Assert.Equal("TestName", thing.Name);
}
[Fact]
public void TryGetValue_ValidProperty_OneOrMany()
{
var thing = new Thing
{
Name = "TestName",
};
Assert.True(thing.TryGetValue("Name", out var result));
var name = Assert.Single(result);
Assert.Equal("TestName", name);
}
[Fact]
public void TryGetValue_ValidProperty_Values()
{
var thing = new Thing
{
Identifier = new Uri("https://example.org/test-identifier"),
};
Assert.True(thing.TryGetValue("Identifier", out var result));
var identifier = Assert.Single(result);
Assert.Equal(new Uri("https://example.org/test-identifier"), identifier);
}
[Fact]
public void TryGetValue_InvalidProperty_InvalidName()
{
var thing = new Thing();
Assert.False(thing.TryGetValue("InvalidName", out _));
}
[Fact]
public void TryGetValue_CaseInsensitive()
{
var thing = new Thing
{
Name = "TestName",
};
Assert.True(thing.TryGetValue("name", out var result));
var name = Assert.Single(result);
Assert.Equal("TestName", name);
}
[Fact]
public void TryGetValue_Generic_ValidProperty_OneOrMany()
{
var thing = new Thing
{
Name = "TestName",
};
Assert.True(thing.TryGetValue<string>("Name", out var result));
Assert.Equal("TestName", result);
}
[Fact]
public void TryGetValue_Generic_ValidProperty_Values()
{
var thing = new Thing
{
Identifier = new Uri("https://example.org/test-identifier"),
};
Assert.True(thing.TryGetValue<Uri>("Identifier", out var result));
var identifier = Assert.Single(result);
Assert.Equal(new Uri("https://example.org/test-identifier"), identifier);
}
[Fact]
public void TryGetValue_Generic_InvalidProperty_InvalidName()
{
var thing = new Thing();
Assert.False(thing.TryGetValue<string>("InvalidName", out _));
}
[Fact]
public void TryGetValue_Generic_InvalidProperty_InvalidType()
{
var thing = new Thing
{
Name = "TestName",
};
Assert.False(thing.TryGetValue<Uri>("Name", out _));
}
[Fact]
public void TryGetValue_Generic_CaseInsensitive()
{
var thing = new Thing
{
Name = "TestName",
};
Assert.True(thing.TryGetValue<string>("name", out var result));
Assert.Equal("TestName", result);
}
private static void CompareEqual<T>(T a, T? b)
{
Assert.NotNull(a);
Assert.Equal(a!.GetHashCode(), b?.GetHashCode());
Assert.True(a.Equals(b));
}
private static void CompareNotEqual<T>(T a, T? b)
{
Assert.NotNull(a);
Assert.NotEqual(a!.GetHashCode(), b?.GetHashCode());
Assert.False(a.Equals(b));
}
}
| |
#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.Specialized;
using System.ComponentModel;
#if !(NET20 || NET35 || PORTABLE)
using System.Numerics;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
using System.Collections;
#if !(NETFX_CORE || DNXCORE50)
using System.Web.UI;
#endif
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JObjectTests : TestFixtureBase
{
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void EmbedJValueStringInNewJObject()
{
string s = null;
var v = new JValue(s);
dynamic o = JObject.FromObject(new { title = v });
string output = o.ToString();
StringAssert.AreEqual(@"{
""title"": null
}", output);
Assert.AreEqual(null, v.Value);
Assert.IsNull((string)o.title);
}
#endif
[Test]
public void ReadWithSupportMultipleContent()
{
string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }";
IList<JObject> roles = new List<JObject>();
JsonTextReader reader = new JsonTextReader(new StringReader(json));
reader.SupportMultipleContent = true;
while (true)
{
JObject role = (JObject)JToken.ReadFrom(reader);
roles.Add(role);
if (!reader.Read())
break;
}
Assert.AreEqual(2, roles.Count);
Assert.AreEqual("Admin", (string)roles[0]["name"]);
Assert.AreEqual("Publisher", (string)roles[1]["name"]);
}
[Test]
public void JObjectWithComments()
{
string json = @"{ /*comment2*/
""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/
""ExpiryDate"": ""\/Date(1230422400000)\/"",
""Price"": 3.99,
""Sizes"": /*comment6*/ [ /*comment7*/
""Small"", /*comment8*/
""Medium"" /*comment9*/,
/*comment10*/ ""Large""
/*comment11*/ ] /*comment12*/
} /*comment13*/";
JToken o = JToken.Parse(json);
Assert.AreEqual("Apple", (string) o["Name"]);
}
[Test]
public void WritePropertyWithNoValue()
{
var o = new JObject();
o.Add(new JProperty("novalue"));
StringAssert.AreEqual(@"{
""novalue"": null
}", o.ToString());
}
[Test]
public void Keys()
{
var o = new JObject();
var d = (IDictionary<string, JToken>)o;
Assert.AreEqual(0, d.Keys.Count);
o["value"] = true;
Assert.AreEqual(1, d.Keys.Count);
}
[Test]
public void TryGetValue()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(false, o.TryGetValue("sdf", out t));
Assert.AreEqual(null, t);
Assert.AreEqual(false, o.TryGetValue(null, out t));
Assert.AreEqual(null, t);
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
}
[Test]
public void DictionaryItemShouldSet()
{
JObject o = new JObject();
o["PropertyNameValue"] = new JValue(1);
Assert.AreEqual(1, o.Children().Count());
JToken t;
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t));
o["PropertyNameValue"] = new JValue(2);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t));
o["PropertyNameValue"] = null;
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t));
Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t));
}
[Test]
public void Remove()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, o.Remove("sdf"));
Assert.AreEqual(false, o.Remove(null));
Assert.AreEqual(true, o.Remove("PropertyNameValue"));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void GenericCollectionRemove()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))));
Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))));
Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v)));
Assert.AreEqual(0, o.Children().Count());
}
[Test]
public void DuplicatePropertyNameShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", null);
o.Add("PropertyNameValue", null);
}, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void GenericDictionaryAdd()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
o.Add("PropertyNameValue1", null);
Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value);
Assert.AreEqual(2, o.Children().Count());
}
[Test]
public void GenericCollectionAdd()
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(1, (int)o["PropertyNameValue"]);
Assert.AreEqual(1, o.Children().Count());
}
[Test]
public void GenericCollectionClear()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
JProperty p = (JProperty)o.Children().ElementAt(0);
((ICollection<KeyValuePair<string, JToken>>)o).Clear();
Assert.AreEqual(0, o.Children().Count());
Assert.AreEqual(null, p.Parent);
}
[Test]
public void GenericCollectionContains()
{
JValue v = new JValue(1);
JObject o = new JObject();
o.Add("PropertyNameValue", v);
Assert.AreEqual(1, o.Children().Count());
bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v));
Assert.AreEqual(true, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)));
Assert.AreEqual(false, contains);
contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>));
Assert.AreEqual(false, contains);
}
[Test]
public void GenericDictionaryContains()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
Assert.AreEqual(1, o.Children().Count());
bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue");
Assert.AreEqual(true, contains);
}
[Test]
public void GenericCollectionCopyTo()
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
Assert.AreEqual(3, o.Children().Count());
KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5];
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]);
Assert.AreEqual("PropertyNameValue", a[1].Key);
Assert.AreEqual(1, (int)a[1].Value);
Assert.AreEqual("PropertyNameValue2", a[2].Key);
Assert.AreEqual(2, (int)a[2].Value);
Assert.AreEqual("PropertyNameValue3", a[3].Key);
Assert.AreEqual(3, (int)a[3].Value);
Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]);
}
[Test]
public void GenericCollectionCopyToNullArrayShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0);
}, @"Value cannot be null.
Parameter name: array");
}
[Test]
public void GenericCollectionCopyToNegativeArrayIndexShouldThrow()
{
ExceptionAssert.Throws<ArgumentOutOfRangeException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1);
}, @"arrayIndex is less than 0.
Parameter name: arrayIndex");
}
[Test]
public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1);
}, @"arrayIndex is equal to or greater than the length of array.");
}
[Test]
public void GenericCollectionCopyToInsufficientArrayCapacity()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add("PropertyNameValue", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
o.Add("PropertyNameValue3", new JValue(3));
((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1);
}, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
}
[Test]
public void FromObjectRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
Assert.AreEqual("FirstNameValue", (string)o["first_name"]);
Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type);
Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]);
Assert.AreEqual("LastNameValue", (string)o["last_name"]);
}
[Test]
public void JTokenReader()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.StartObject, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.Raw, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.String, reader.TokenType);
Assert.IsTrue(reader.Read());
Assert.AreEqual(JsonToken.EndObject, reader.TokenType);
Assert.IsFalse(reader.Read());
}
[Test]
public void DeserializeFromRaw()
{
PersonRaw raw = new PersonRaw
{
FirstName = "FirstNameValue",
RawContent = new JRaw("[1,2,3,4,5]"),
LastName = "LastNameValue"
};
JObject o = JObject.FromObject(raw);
JsonReader reader = new JTokenReader(o);
JsonSerializer serializer = new JsonSerializer();
raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw));
Assert.AreEqual("FirstNameValue", raw.FirstName);
Assert.AreEqual("LastNameValue", raw.LastName);
Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value);
}
[Test]
public void Parse_ShouldThrowOnUnexpectedToken()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[""prop""]";
JObject.Parse(json);
}, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.");
}
[Test]
public void ParseJavaScriptDate()
{
string json = @"[new Date(1207285200000)]";
JArray a = (JArray)JsonConvert.DeserializeObject(json);
JValue v = (JValue)a[0];
Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v);
}
[Test]
public void GenericValueCast()
{
string json = @"{""foo"":true}";
JObject o = (JObject)JsonConvert.DeserializeObject(json);
bool? value = o.Value<bool?>("foo");
Assert.AreEqual(true, value);
json = @"{""foo"":null}";
o = (JObject)JsonConvert.DeserializeObject(json);
value = o.Value<bool?>("foo");
Assert.AreEqual(null, value);
}
[Test]
public void Blog()
{
ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{
""name"": ""James"",
]!#$THIS IS: BAD JSON![{}}}}]
}"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 4.");
}
[Test]
public void RawChildValues()
{
JObject o = new JObject();
o["val1"] = new JRaw("1");
o["val2"] = new JRaw("1");
string json = o.ToString();
StringAssert.AreEqual(@"{
""val1"": 1,
""val2"": 1
}", json);
}
[Test]
public void Iterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
JToken t = o;
int i = 1;
foreach (JProperty property in t)
{
Assert.AreEqual("PropertyNameValue" + i, property.Name);
Assert.AreEqual(i, (int)property.Value);
i++;
}
}
[Test]
public void KeyValuePairIterate()
{
JObject o = new JObject();
o.Add("PropertyNameValue1", new JValue(1));
o.Add("PropertyNameValue2", new JValue(2));
int i = 1;
foreach (KeyValuePair<string, JToken> pair in o)
{
Assert.AreEqual("PropertyNameValue" + i, pair.Key);
Assert.AreEqual(i, (int)pair.Value);
i++;
}
}
[Test]
public void WriteObjectNullStringValue()
{
string s = null;
JValue v = new JValue(s);
Assert.AreEqual(null, v.Value);
Assert.AreEqual(JTokenType.String, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
StringAssert.AreEqual(@"{
""title"": null
}", output);
}
[Test]
public void Example()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Assert.AreEqual("Apple", name);
Assert.AreEqual("Small", smallest);
}
[Test]
public void DeserializeClassManually()
{
string jsonText = @"{
""short"":
{
""original"":""http://www.foo.com/"",
""short"":""krehqk"",
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JObject json = JObject.Parse(jsonText);
Shortie shortie = new Shortie
{
Original = (string)json["short"]["original"],
Short = (string)json["short"]["short"],
Error = new ShortieException
{
Code = (int)json["short"]["error"]["code"],
ErrorMessage = (string)json["short"]["error"]["msg"]
}
};
Assert.AreEqual("http://www.foo.com/", shortie.Original);
Assert.AreEqual("krehqk", shortie.Short);
Assert.AreEqual(null, shortie.Shortened);
Assert.AreEqual(0, shortie.Error.Code);
Assert.AreEqual("No action taken", shortie.Error.ErrorMessage);
}
[Test]
public void JObjectContainingHtml()
{
JObject o = new JObject();
o["rc"] = new JValue(200);
o["m"] = new JValue("");
o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>");
StringAssert.AreEqual(@"{
""rc"": 200,
""m"": """",
""o"": ""<div class='s1'>\r\n</div>""
}", o.ToString());
}
[Test]
public void ImplicitValueConversions()
{
JObject moss = new JObject();
moss["FirstName"] = new JValue("Maurice");
moss["LastName"] = new JValue("Moss");
moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30));
moss["Department"] = new JValue("IT");
moss["JobTitle"] = new JValue("Support");
StringAssert.AreEqual(@"{
""FirstName"": ""Maurice"",
""LastName"": ""Moss"",
""BirthDate"": ""1977-12-30T00:00:00"",
""Department"": ""IT"",
""JobTitle"": ""Support""
}", moss.ToString());
JObject jen = new JObject();
jen["FirstName"] = "Jen";
jen["LastName"] = "Barber";
jen["BirthDate"] = new DateTime(1978, 3, 15);
jen["Department"] = "IT";
jen["JobTitle"] = "Manager";
StringAssert.AreEqual(@"{
""FirstName"": ""Jen"",
""LastName"": ""Barber"",
""BirthDate"": ""1978-03-15T00:00:00"",
""Department"": ""IT"",
""JobTitle"": ""Manager""
}", jen.ToString());
}
[Test]
public void ReplaceJPropertyWithJPropertyWithSameName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
IList l = o;
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p2, l[1]);
JProperty p3 = new JProperty("Test1", "III");
p1.Replace(p3);
Assert.AreEqual(null, p1.Parent);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
Assert.AreEqual(2, l.Count);
Assert.AreEqual(2, o.Properties().Count());
JProperty p4 = new JProperty("Test4", "IV");
p2.Replace(p4);
Assert.AreEqual(null, p2.Parent);
Assert.AreEqual(l, p4.Parent);
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p4, l[1]);
}
#if !(NET20 || PORTABLE || PORTABLE40)
[Test]
public void PropertyChanging()
{
object changing = null;
object changed = null;
int changingCount = 0;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanging += (sender, args) =>
{
JObject s = (JObject)sender;
changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changingCount++;
};
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual(null, changing);
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changingCount);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value1", changing);
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changingCount);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual("value2", changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changingCount);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changing);
Assert.AreEqual(null, changed);
Assert.AreEqual(JValue.CreateNull(), o["NullValue"]);
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changingCount);
Assert.AreEqual(4, changedCount);
}
#endif
[Test]
public void PropertyChanged()
{
object changed = null;
int changedCount = 0;
JObject o = new JObject();
o.PropertyChanged += (sender, args) =>
{
JObject s = (JObject)sender;
changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null;
changedCount++;
};
o["StringValue"] = "value1";
Assert.AreEqual("value1", changed);
Assert.AreEqual("value1", (string)o["StringValue"]);
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value1";
Assert.AreEqual(1, changedCount);
o["StringValue"] = "value2";
Assert.AreEqual("value2", changed);
Assert.AreEqual("value2", (string)o["StringValue"]);
Assert.AreEqual(2, changedCount);
o["StringValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(null, (string)o["StringValue"]);
Assert.AreEqual(3, changedCount);
o["NullValue"] = null;
Assert.AreEqual(null, changed);
Assert.AreEqual(JValue.CreateNull(), o["NullValue"]);
Assert.AreEqual(4, changedCount);
o["NullValue"] = null;
Assert.AreEqual(4, changedCount);
}
[Test]
public void IListContains()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void IListIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void IListClear()
{
JProperty p = new JProperty("Test", 1);
IList l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
object[] a = new object[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void IListAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
public void IListAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void IListAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l.Add("Bad!");
}, "Argument is not a JToken.");
}
[Test]
public void IListAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void IListRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
l.Remove(p3);
Assert.AreEqual(2, l.Count);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
l.Remove(p2);
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void IListRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void IListInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void IListIsReadOnly()
{
IList l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void IListIsFixedSize()
{
IList l = new JObject();
Assert.IsFalse(l.IsFixedSize);
}
[Test]
public void IListSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
public void IListSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void IListSetItemInvalid()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
l[0] = new JValue(true);
}, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void IListSyncRoot()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsNotNull(l.SyncRoot);
}
[Test]
public void IListIsSynchronized()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList l = new JObject(p1, p2);
Assert.IsFalse(l.IsSynchronized);
}
[Test]
public void GenericListJTokenContains()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.IsTrue(l.Contains(p));
Assert.IsFalse(l.Contains(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenIndexOf()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(0, l.IndexOf(p));
Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1)));
}
[Test]
public void GenericListJTokenClear()
{
JProperty p = new JProperty("Test", 1);
IList<JToken> l = new JObject(p);
Assert.AreEqual(1, l.Count);
l.Clear();
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenCopyTo()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JToken[] a = new JToken[l.Count];
l.CopyTo(a, 0);
Assert.AreEqual(p1, a[0]);
Assert.AreEqual(p2, a[1]);
}
[Test]
public void GenericListJTokenAdd()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Add(p3);
Assert.AreEqual(3, l.Count);
Assert.AreEqual(p3, l[2]);
}
[Test]
public void GenericListJTokenAddBadToken()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
l.Add(new JValue("Bad!"));
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void GenericListJTokenAddBadValue()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// string is implicitly converted to JValue
l.Add("Bad!");
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void GenericListJTokenAddPropertyWithExistingName()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test2", "II");
l.Add(p3);
}, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
[Test]
public void GenericListJTokenRemove()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
// won't do anything
Assert.IsFalse(l.Remove(p3));
Assert.AreEqual(2, l.Count);
Assert.IsTrue(l.Remove(p1));
Assert.AreEqual(1, l.Count);
Assert.IsFalse(l.Contains(p1));
Assert.IsTrue(l.Contains(p2));
Assert.IsTrue(l.Remove(p2));
Assert.AreEqual(0, l.Count);
Assert.IsFalse(l.Contains(p2));
Assert.AreEqual(null, p2.Parent);
}
[Test]
public void GenericListJTokenRemoveAt()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
// won't do anything
l.RemoveAt(0);
l.Remove(p1);
Assert.AreEqual(1, l.Count);
l.Remove(p2);
Assert.AreEqual(0, l.Count);
}
[Test]
public void GenericListJTokenInsert()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l.Insert(1, p3);
Assert.AreEqual(l, p3.Parent);
Assert.AreEqual(p1, l[0]);
Assert.AreEqual(p3, l[1]);
Assert.AreEqual(p2, l[2]);
}
[Test]
public void GenericListJTokenIsReadOnly()
{
IList<JToken> l = new JObject();
Assert.IsFalse(l.IsReadOnly);
}
[Test]
public void GenericListJTokenSetItem()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
Assert.AreEqual(p3, l[0]);
Assert.AreEqual(p2, l[1]);
}
[Test]
public void GenericListJTokenSetItemAlreadyExists()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
IList<JToken> l = new JObject(p1, p2);
JProperty p3 = new JProperty("Test3", "III");
l[0] = p3;
l[1] = p3;
}, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.");
}
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
[Test]
public void IBindingListSortDirection()
{
IBindingList l = new JObject();
Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection);
}
[Test]
public void IBindingListSortProperty()
{
IBindingList l = new JObject();
Assert.AreEqual(null, l.SortProperty);
}
[Test]
public void IBindingListSupportsChangeNotification()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.SupportsChangeNotification);
}
[Test]
public void IBindingListSupportsSearching()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSearching);
}
[Test]
public void IBindingListSupportsSorting()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.SupportsSorting);
}
[Test]
public void IBindingListAllowEdit()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowEdit);
}
[Test]
public void IBindingListAllowNew()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowNew);
}
[Test]
public void IBindingListAllowRemove()
{
IBindingList l = new JObject();
Assert.AreEqual(true, l.AllowRemove);
}
[Test]
public void IBindingListAddIndex()
{
IBindingList l = new JObject();
// do nothing
l.AddIndex(null);
}
[Test]
public void IBindingListApplySort()
{
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.ApplySort(null, ListSortDirection.Ascending);
}, "Specified method is not supported.");
}
[Test]
public void IBindingListRemoveSort()
{
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.RemoveSort();
}, "Specified method is not supported.");
}
[Test]
public void IBindingListRemoveIndex()
{
IBindingList l = new JObject();
// do nothing
l.RemoveIndex(null);
}
[Test]
public void IBindingListFind()
{
ExceptionAssert.Throws<NotSupportedException>(() =>
{
IBindingList l = new JObject();
l.Find(null, null);
}, "Specified method is not supported.");
}
[Test]
public void IBindingListIsSorted()
{
IBindingList l = new JObject();
Assert.AreEqual(false, l.IsSorted);
}
[Test]
public void IBindingListAddNew()
{
ExceptionAssert.Throws<JsonException>(() =>
{
IBindingList l = new JObject();
l.AddNew();
}, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.");
}
[Test]
public void IBindingListAddNewWithEvent()
{
JObject o = new JObject();
o._addingNew += (s, e) => e.NewObject = new JProperty("Property!");
IBindingList l = o;
object newObject = l.AddNew();
Assert.IsNotNull(newObject);
JProperty p = (JProperty)newObject;
Assert.AreEqual("Property!", p.Name);
Assert.AreEqual(o, p.Parent);
}
[Test]
public void ITypedListGetListName()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
Assert.AreEqual(string.Empty, l.GetListName(null));
}
[Test]
public void ITypedListGetItemProperties()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
ITypedList l = new JObject(p1, p2);
PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null);
Assert.IsNull(propertyDescriptors);
}
[Test]
public void ListChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
ListChangedType? changedType = null;
int? index = null;
o.ListChanged += (s, a) =>
{
changedType = a.ListChangedType;
index = a.NewIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, ListChangedType.ItemAdded);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, ListChangedType.ItemChanged);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
#if !(NET20 || NET35 || PORTABLE40)
[Test]
public void CollectionChanged()
{
JProperty p1 = new JProperty("Test1", 1);
JProperty p2 = new JProperty("Test2", "Two");
JObject o = new JObject(p1, p2);
NotifyCollectionChangedAction? changedType = null;
int? index = null;
o._collectionChanged += (s, a) =>
{
changedType = a.Action;
index = a.NewStartingIndex;
};
JProperty p3 = new JProperty("Test3", "III");
o.Add(p3);
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add);
Assert.AreEqual(index, 2);
Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]);
JProperty p4 = new JProperty("Test4", "IV");
((IList<JToken>)o)[index.Value] = p4;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 2);
Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]);
Assert.IsFalse(((IList<JToken>)o).Contains(p3));
Assert.IsTrue(((IList<JToken>)o).Contains(p4));
o["Test1"] = 2;
Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace);
Assert.AreEqual(index, 0);
Assert.AreEqual(2, (int)o["Test1"]);
}
#endif
[Test]
public void GetGeocodeAddress()
{
string json = @"{
""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"",
""Status"": {
""code"": 200,
""request"": ""geocode""
},
""Placemark"": [ {
""id"": ""p1"",
""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"",
""AddressDetails"": {
""Accuracy"" : 8,
""Country"" : {
""AdministrativeArea"" : {
""AdministrativeAreaName"" : ""IL"",
""SubAdministrativeArea"" : {
""Locality"" : {
""LocalityName"" : ""Rockford"",
""PostalCode"" : {
""PostalCodeNumber"" : ""61107""
},
""Thoroughfare"" : {
""ThoroughfareName"" : ""435 N Mulford Rd""
}
},
""SubAdministrativeAreaName"" : ""Winnebago""
}
},
""CountryName"" : ""USA"",
""CountryNameCode"" : ""US""
}
},
""ExtendedData"": {
""LatLonBox"": {
""north"": 42.2753076,
""south"": 42.2690124,
""east"": -88.9964645,
""west"": -89.0027597
}
},
""Point"": {
""coordinates"": [ -88.9995886, 42.2721596, 0 ]
}
} ]
}";
JObject o = JObject.Parse(json);
string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"];
Assert.AreEqual("435 N Mulford Rd", searchAddress);
}
[Test]
public void SetValueWithInvalidPropertyName()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o[0] = new JValue(3);
}, "Set JObject values with invalid key value: 0. Object property name expected.");
}
[Test]
public void SetValue()
{
object key = "TestKey";
JObject o = new JObject();
o[key] = new JValue(3);
Assert.AreEqual(3, (int)o[key]);
}
[Test]
public void ParseMultipleProperties()
{
string json = @"{
""Name"": ""Name1"",
""Name"": ""Name2""
}";
JObject o = JObject.Parse(json);
string value = (string)o["Name"];
Assert.AreEqual("Name2", value);
}
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
[Test]
public void WriteObjectNullDBNullValue()
{
DBNull dbNull = DBNull.Value;
JValue v = new JValue(dbNull);
Assert.AreEqual(DBNull.Value, v.Value);
Assert.AreEqual(JTokenType.Null, v.Type);
JObject o = new JObject();
o["title"] = v;
string output = o.ToString();
StringAssert.AreEqual(@"{
""title"": null
}", output);
}
#endif
[Test]
public void InvalidValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o["responseData"];
}, "Can not convert Object to String.");
}
[Test]
public void InvalidPropertyValueCastExceptionMessage()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
string json = @"{
""responseData"": {},
""responseDetails"": null,
""responseStatus"": 200
}";
JObject o = JObject.Parse(json);
string name = (string)o.Property("responseData");
}, "Can not convert Object to String.");
}
[Test]
public void ParseIncomplete()
{
ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.");
}
[Test]
public void LoadFromNestedObject()
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0,
""msg"":""No action taken""
}
}
}";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JObject o = (JObject)JToken.ReadFrom(reader);
Assert.IsNotNull(o);
StringAssert.AreEqual(@"{
""code"": 0,
""msg"": ""No action taken""
}", o.ToString(Formatting.Indented));
}
[Test]
public void LoadFromNestedObjectIncomplete()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string jsonText = @"{
""short"":
{
""error"":
{
""code"":0";
JsonReader reader = new JsonTextReader(new StringReader(jsonText));
reader.Read();
reader.Read();
reader.Read();
reader.Read();
reader.Read();
JToken.ReadFrom(reader);
}, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14.");
}
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
[Test]
public void GetProperties()
{
JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}");
ICustomTypeDescriptor descriptor = o;
PropertyDescriptorCollection properties = descriptor.GetProperties();
Assert.AreEqual(4, properties.Count);
PropertyDescriptor prop1 = properties[0];
Assert.AreEqual("prop1", prop1.Name);
Assert.AreEqual(typeof(object), prop1.PropertyType);
Assert.AreEqual(typeof(JObject), prop1.ComponentType);
Assert.AreEqual(false, prop1.CanResetValue(o));
Assert.AreEqual(false, prop1.ShouldSerializeValue(o));
PropertyDescriptor prop2 = properties[1];
Assert.AreEqual("prop2", prop2.Name);
Assert.AreEqual(typeof(object), prop2.PropertyType);
Assert.AreEqual(typeof(JObject), prop2.ComponentType);
Assert.AreEqual(false, prop2.CanResetValue(o));
Assert.AreEqual(false, prop2.ShouldSerializeValue(o));
PropertyDescriptor prop3 = properties[2];
Assert.AreEqual("prop3", prop3.Name);
Assert.AreEqual(typeof(object), prop3.PropertyType);
Assert.AreEqual(typeof(JObject), prop3.ComponentType);
Assert.AreEqual(false, prop3.CanResetValue(o));
Assert.AreEqual(false, prop3.ShouldSerializeValue(o));
PropertyDescriptor prop4 = properties[3];
Assert.AreEqual("prop4", prop4.Name);
Assert.AreEqual(typeof(object), prop4.PropertyType);
Assert.AreEqual(typeof(JObject), prop4.ComponentType);
Assert.AreEqual(false, prop4.CanResetValue(o));
Assert.AreEqual(false, prop4.ShouldSerializeValue(o));
}
#endif
[Test]
public void ParseEmptyObjectWithComment()
{
JObject o = JObject.Parse("{ /* A Comment */ }");
Assert.AreEqual(0, o.Count);
}
[Test]
public void FromObjectTimeSpan()
{
JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1));
Assert.AreEqual(v.Value, TimeSpan.FromDays(1));
Assert.AreEqual("1.00:00:00", v.ToString());
}
[Test]
public void FromObjectUri()
{
JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz"));
Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz"));
Assert.AreEqual("http://www.stuff.co.nz/", v.ToString());
}
[Test]
public void FromObjectGuid()
{
JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35"));
Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35"));
Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString());
}
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}, 987987";
JObject o = JObject.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 1.");
}
[Test]
public void DeepEqualsIgnoreOrder()
{
JObject o1 = new JObject(
new JProperty("null", null),
new JProperty("integer", 1),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("array", new JArray(1, 2)));
Assert.IsTrue(o1.DeepEquals(o1));
JObject o2 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1),
new JProperty("array", new JArray(1, 2)));
Assert.IsTrue(o1.DeepEquals(o2));
JObject o3 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 2),
new JProperty("array", new JArray(1, 2)));
Assert.IsFalse(o1.DeepEquals(o3));
JObject o4 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1),
new JProperty("array", new JArray(2, 1)));
Assert.IsFalse(o1.DeepEquals(o4));
JObject o5 = new JObject(
new JProperty("null", null),
new JProperty("string", "string!"),
new JProperty("decimal", 0.5m),
new JProperty("integer", 1));
Assert.IsFalse(o1.DeepEquals(o5));
Assert.IsFalse(o1.DeepEquals(null));
}
[Test]
public void ToListOnEmptyObject()
{
JObject o = JObject.Parse(@"{}");
IList<JToken> l1 = o.ToList<JToken>();
Assert.AreEqual(0, l1.Count);
IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>();
Assert.AreEqual(0, l2.Count);
o = JObject.Parse(@"{'hi':null}");
l1 = o.ToList<JToken>();
Assert.AreEqual(1, l1.Count);
l2 = o.ToList<KeyValuePair<string, JToken>>();
Assert.AreEqual(1, l2.Count);
}
[Test]
public void EmptyObjectDeepEquals()
{
Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject()));
JObject a = new JObject();
JObject b = new JObject();
b.Add("hi", "bye");
b.Remove("hi");
Assert.IsTrue(JToken.DeepEquals(a, b));
Assert.IsTrue(JToken.DeepEquals(b, a));
}
[Test]
public void GetValueBlogExample()
{
JObject o = JObject.Parse(@"{
'name': 'Lower',
'NAME': 'Upper'
}");
string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase);
// Upper
string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase);
// Lower
Assert.AreEqual("Upper", exactMatch);
Assert.AreEqual("Lower", ignoreCase);
}
[Test]
public void GetValue()
{
JObject a = new JObject();
a["Name"] = "Name!";
a["name"] = "name!";
a["title"] = "Title!";
Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal));
Assert.AreEqual(null, a.GetValue("NAME"));
Assert.AreEqual(null, a.GetValue("TITLE"));
Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase));
Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal));
Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal));
Assert.AreEqual(null, a.GetValue(null));
JToken v;
Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v));
Assert.AreEqual(null, v);
Assert.IsFalse(a.TryGetValue("NAME", out v));
Assert.IsFalse(a.TryGetValue("TITLE", out v));
Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v));
Assert.AreEqual("Name!", (string)v);
Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v));
Assert.AreEqual("name!", (string)v);
Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v));
}
public class FooJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var token = JToken.FromObject(value, new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
if (token.Type == JTokenType.Object)
{
var o = (JObject)token;
o.AddFirst(new JProperty("foo", "bar"));
o.WriteTo(writer);
}
else
token.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotSupportedException("This custom converter only supportes serialization and not deserialization.");
}
public override bool CanRead
{
get { return false; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
[Test]
public void FromObjectInsideConverterWithCustomSerializer()
{
var p = new Person
{
Name = "Daniel Wertheim",
};
var settings = new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new FooJsonConverter() },
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var json = JsonConvert.SerializeObject(p, settings);
Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json);
}
[Test]
public void Parse_NoComments()
{
string json = "{'prop':[1,2/*comment*/,3]}";
JObject o = JObject.Parse(json, new JsonLoadSettings
{
CommentHandling = CommentHandling.Ignore
});
Assert.AreEqual(3, o["prop"].Count());
Assert.AreEqual(1, (int)o["prop"][0]);
Assert.AreEqual(2, (int)o["prop"][1]);
Assert.AreEqual(3, (int)o["prop"][2]);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography
{
using Microsoft.Win32;
using System.IO;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif // FEATURE_MACL
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
#if FEATURE_IMPERSONATION
using System.Security.Principal;
#endif // FEATURE_IMPERSONATION
using System.Text;
using System.Threading;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
[Serializable]
internal enum CspAlgorithmType {
Rsa = 0,
Dss = 1
}
internal static class Constants {
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int S_OK = 0;
internal const int NTE_FILENOTFOUND = unchecked((int) 0x80070002); // The system cannot find the file specified.
internal const int NTE_NO_KEY = unchecked((int) 0x8009000D); // Key does not exist.
internal const int NTE_BAD_KEYSET = unchecked((int) 0x80090016); // Keyset does not exist.
internal const int NTE_KEYSET_NOT_DEF = unchecked((int) 0x80090019); // The keyset is not defined.
internal const int KP_IV = 1;
internal const int KP_MODE = 4;
internal const int KP_MODE_BITS = 5;
internal const int KP_EFFECTIVE_KEYLEN = 19;
internal const int ALG_CLASS_SIGNATURE = (1 << 13);
internal const int ALG_CLASS_DATA_ENCRYPT = (3 << 13);
internal const int ALG_CLASS_HASH = (4 << 13);
internal const int ALG_CLASS_KEY_EXCHANGE = (5 << 13);
internal const int ALG_TYPE_DSS = (1 << 9);
internal const int ALG_TYPE_RSA = (2 << 9);
internal const int ALG_TYPE_BLOCK = (3 << 9);
internal const int ALG_TYPE_STREAM = (4 << 9);
internal const int ALG_TYPE_ANY = (0);
internal const int CALG_MD5 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 3);
internal const int CALG_SHA1 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 4);
internal const int CALG_SHA_256 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 12);
internal const int CALG_SHA_384 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 13);
internal const int CALG_SHA_512 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 14);
internal const int CALG_RSA_KEYX = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RSA | 0);
internal const int CALG_RSA_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | 0);
internal const int CALG_DSS_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | 0);
internal const int CALG_DES = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 1);
internal const int CALG_RC2 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 2);
internal const int CALG_3DES = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 3);
internal const int CALG_3DES_112 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 9);
internal const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 14);
internal const int CALG_AES_192 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 15);
internal const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 16);
internal const int CALG_RC4 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | 1);
#endif // FEATURE_CRYPTO
internal const int PROV_RSA_FULL = 1;
internal const int PROV_DSS_DH = 13;
internal const int PROV_RSA_AES = 24;
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int AT_KEYEXCHANGE = 1;
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int AT_SIGNATURE = 2;
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int PUBLICKEYBLOB = 0x6;
internal const int PRIVATEKEYBLOB = 0x7;
internal const int CRYPT_OAEP = 0x40;
internal const uint CRYPT_VERIFYCONTEXT = 0xF0000000;
internal const uint CRYPT_NEWKEYSET = 0x00000008;
internal const uint CRYPT_DELETEKEYSET = 0x00000010;
internal const uint CRYPT_MACHINE_KEYSET = 0x00000020;
internal const uint CRYPT_SILENT = 0x00000040;
internal const uint CRYPT_EXPORTABLE = 0x00000001;
internal const uint CLR_KEYLEN = 1;
internal const uint CLR_PUBLICKEYONLY = 2;
internal const uint CLR_EXPORTABLE = 3;
internal const uint CLR_REMOVABLE = 4;
internal const uint CLR_HARDWARE = 5;
internal const uint CLR_ACCESSIBLE = 6;
internal const uint CLR_PROTECTED = 7;
internal const uint CLR_UNIQUE_CONTAINER = 8;
internal const uint CLR_ALGID = 9;
internal const uint CLR_PP_CLIENT_HWND = 10;
internal const uint CLR_PP_PIN = 11;
internal const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6";
internal const string OID_RSA_MD5 = "1.2.840.113549.2.5";
internal const string OID_RSA_RC2CBC = "1.2.840.113549.3.2";
internal const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7";
internal const string OID_OIWSEC_desCBC = "1.3.14.3.2.7";
internal const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26";
internal const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1";
internal const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2";
internal const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3";
internal const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1";
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
}
internal static class Utils {
#if FEATURE_CRYPTO
[SecuritySafeCritical]
#endif
static Utils()
{
}
// Provider type to use by default for RSA operations. We want to use RSA-AES CSP
// since it enables access to SHA-2 operations. All currently supported OSes support RSA-AES.
internal const int DefaultRsaProviderType = Constants.PROV_RSA_AES;
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject = new Object();
private static Object InternalSyncObject {
get { return s_InternalSyncObject; }
}
[System.Security.SecurityCritical] // auto-generated
private static volatile SafeProvHandle _safeProvHandle;
internal static SafeProvHandle StaticProvHandle {
[System.Security.SecurityCritical] // auto-generated
get {
if (_safeProvHandle == null) {
lock (InternalSyncObject) {
if (_safeProvHandle == null) {
_safeProvHandle = AcquireProvHandle(new CspParameters(DefaultRsaProviderType));
}
}
}
return _safeProvHandle;
}
}
[System.Security.SecurityCritical] // auto-generated
private static volatile SafeProvHandle _safeDssProvHandle;
internal static SafeProvHandle StaticDssProvHandle {
[System.Security.SecurityCritical] // auto-generated
get {
if (_safeDssProvHandle == null) {
lock (InternalSyncObject) {
if (_safeDssProvHandle == null) {
_safeDssProvHandle = CreateProvHandle(new CspParameters(Constants.PROV_DSS_DH), true);
}
}
}
return _safeDssProvHandle;
}
}
[System.Security.SecurityCritical] // auto-generated
internal static SafeProvHandle AcquireProvHandle (CspParameters parameters) {
if (parameters == null)
parameters = new CspParameters(DefaultRsaProviderType);
SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle;
Utils._AcquireCSP(parameters, ref safeProvHandle);
return safeProvHandle;
}
[System.Security.SecurityCritical] // auto-generated
internal static SafeProvHandle CreateProvHandle (CspParameters parameters, bool randomKeyContainer) {
SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle;
int hr = Utils._OpenCSP(parameters, 0, ref safeProvHandle);
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
if (hr != Constants.S_OK) {
// If UseExistingKey flag is used and the key container does not exist
// throw an exception without attempting to create the container.
if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || (hr != Constants.NTE_KEYSET_NOT_DEF && hr != Constants.NTE_BAD_KEYSET && hr != Constants.NTE_FILENOTFOUND))
throw new CryptographicException(hr);
if (!randomKeyContainer) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
Utils._CreateCSP(parameters, randomKeyContainer, ref safeProvHandle);
} else {
if (!randomKeyContainer) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
}
return safeProvHandle;
}
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
internal static CryptoKeySecurity GetKeySetSecurityInfo (SafeProvHandle hProv, AccessControlSections accessControlSections) {
SecurityInfos securityInfo = 0;
Privilege privilege = null;
if ((accessControlSections & AccessControlSections.Owner) != 0)
securityInfo |= SecurityInfos.Owner;
if ((accessControlSections & AccessControlSections.Group) != 0)
securityInfo |= SecurityInfos.Group;
if ((accessControlSections & AccessControlSections.Access) != 0)
securityInfo |= SecurityInfos.DiscretionaryAcl;
byte[] rawSecurityDescriptor = null;
int error;
RuntimeHelpers.PrepareConstrainedRegions();
try {
if ((accessControlSections & AccessControlSections.Audit) != 0) {
securityInfo |= SecurityInfos.SystemAcl;
privilege = new Privilege("SeSecurityPrivilege");
privilege.Enable();
}
rawSecurityDescriptor = _GetKeySetSecurityInfo(hProv, securityInfo, out error);
}
finally {
if (privilege != null)
privilege.Revert();
}
// This means that the object doesn't have a security descriptor. And thus we throw
// a specific exception for the caller to catch and handle properly.
if (error == Win32Native.ERROR_SUCCESS && (rawSecurityDescriptor == null || rawSecurityDescriptor.Length == 0))
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
if (error == Win32Native.ERROR_NOT_ENOUGH_MEMORY)
throw new OutOfMemoryException();
if (error == Win32Native.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException();
if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
throw new PrivilegeNotHeldException( "SeSecurityPrivilege" );
if (error != Win32Native.ERROR_SUCCESS)
throw new CryptographicException(error);
CommonSecurityDescriptor sd = new CommonSecurityDescriptor(false /* isContainer */,
false /* isDS */,
new RawSecurityDescriptor(rawSecurityDescriptor, 0),
true);
return new CryptoKeySecurity(sd);
}
[System.Security.SecurityCritical] // auto-generated
internal static void SetKeySetSecurityInfo (SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections) {
SecurityInfos securityInfo = 0;
Privilege privilege = null;
if ((accessControlSections & AccessControlSections.Owner) != 0 && cryptoKeySecurity._securityDescriptor.Owner != null)
securityInfo |= SecurityInfos.Owner;
if ((accessControlSections & AccessControlSections.Group) != 0 && cryptoKeySecurity._securityDescriptor.Group != null)
securityInfo |= SecurityInfos.Group;
if ((accessControlSections & AccessControlSections.Audit) != 0)
securityInfo |= SecurityInfos.SystemAcl;
if ((accessControlSections & AccessControlSections.Access) != 0 && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
securityInfo |= SecurityInfos.DiscretionaryAcl;
if (securityInfo == 0) {
// Nothing to persist
return;
}
int error = 0;
RuntimeHelpers.PrepareConstrainedRegions();
try {
if ((securityInfo & SecurityInfos.SystemAcl) != 0) {
privilege = new Privilege("SeSecurityPrivilege");
privilege.Enable();
}
byte[] sd = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
if (sd != null && sd.Length > 0)
error = SetKeySetSecurityInfo (hProv, securityInfo, sd);
}
finally {
if (privilege != null)
privilege.Revert();
}
if (error == Win32Native.ERROR_ACCESS_DENIED || error == Win32Native.ERROR_INVALID_OWNER || error == Win32Native.ERROR_INVALID_PRIMARY_GROUP)
throw new UnauthorizedAccessException();
else if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
throw new PrivilegeNotHeldException("SeSecurityPrivilege");
else if (error == Win32Native.ERROR_INVALID_HANDLE)
throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
else if (error != Win32Native.ERROR_SUCCESS)
throw new CryptographicException(error);
}
#endif //FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
internal static byte[] ExportCspBlobHelper (bool includePrivateParameters, CspParameters parameters, SafeKeyHandle safeKeyHandle) {
if (includePrivateParameters) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Export);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
byte[] blob = null;
Utils.ExportCspBlob(safeKeyHandle, includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB, JitHelpers.GetObjectHandleOnStack(ref blob));
return blob;
}
[System.Security.SecuritySafeCritical] // auto-generated
internal static void GetKeyPairHelper (CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) {
SafeProvHandle TempFetchedProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer);
#if FEATURE_MACL
// If the user wanted to set the security descriptor on the provider context, apply it now.
if (parameters.CryptoKeySecurity != null) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl);
kp.AccessEntries.Add(entry);
kp.Demand();
SetKeySetSecurityInfo(TempFetchedProvHandle, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections);
}
#endif //FEATURE_MACL
#if FEATURE_X509_SECURESTRINGS
// If the user wanted to specify a PIN or HWND for a smart card CSP, apply those settings now.
if (parameters.ParentWindowHandle != IntPtr.Zero)
SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_CLIENT_HWND, parameters.ParentWindowHandle);
else if (parameters.KeyPassword != null) {
IntPtr szPassword = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword);
try {
SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_PIN, szPassword);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeCoTaskMemAnsi(szPassword);
}
}
#endif //FEATURE_X509_SECURESTRINGS
safeProvHandle = TempFetchedProvHandle;
// If the key already exists, use it, else generate a new one
SafeKeyHandle TempFetchedKeyHandle = SafeKeyHandle.InvalidHandle;
int hr = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref TempFetchedKeyHandle);
if (hr != Constants.S_OK) {
if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || hr != Constants.NTE_NO_KEY)
throw new CryptographicException(hr);
// _GenerateKey will check for failures and throw an exception
Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref TempFetchedKeyHandle);
}
// check that this is indeed an RSA/DSS key.
byte[] algid = (byte[]) Utils._GetKeyParameter(TempFetchedKeyHandle, Constants.CLR_ALGID);
int dwAlgId = (algid[0] | (algid[1] << 8) | (algid[2] << 16) | (algid[3] << 24));
if ((keyType == CspAlgorithmType.Rsa && dwAlgId != Constants.CALG_RSA_KEYX && dwAlgId != Constants.CALG_RSA_SIGN) ||
(keyType == CspAlgorithmType.Dss && dwAlgId != Constants.CALG_DSS_SIGN)) {
TempFetchedKeyHandle.Dispose();
throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec"));
}
safeKeyHandle = TempFetchedKeyHandle;
}
[System.Security.SecurityCritical] // auto-generated
internal static void ImportCspBlobHelper (CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) {
// Free the current key handle
if (safeKeyHandle != null && !safeKeyHandle.IsClosed)
safeKeyHandle.Dispose();
safeKeyHandle = SafeKeyHandle.InvalidHandle;
if (publicOnly) {
parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, keyType == CspAlgorithmType.Dss ? Utils.StaticDssProvHandle : Utils.StaticProvHandle, (CspProviderFlags) 0, ref safeKeyHandle);
} else {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import);
kp.AccessEntries.Add(entry);
kp.Demand();
}
if (safeProvHandle == null)
safeProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer);
parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle);
}
}
#endif // FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
internal static CspParameters SaveCspParameters (CspAlgorithmType keyType, CspParameters userParameters, CspProviderFlags defaultFlags, ref bool randomKeyContainer) {
CspParameters parameters;
if (userParameters == null) {
parameters = new CspParameters(keyType == CspAlgorithmType.Dss ? Constants.PROV_DSS_DH : DefaultRsaProviderType, null, null, defaultFlags);
} else {
ValidateCspFlags(userParameters.Flags);
parameters = new CspParameters(userParameters);
}
if (parameters.KeyNumber == -1)
parameters.KeyNumber = keyType == CspAlgorithmType.Dss ? Constants.AT_SIGNATURE : Constants.AT_KEYEXCHANGE;
else if (parameters.KeyNumber == Constants.CALG_DSS_SIGN || parameters.KeyNumber == Constants.CALG_RSA_SIGN)
parameters.KeyNumber = Constants.AT_SIGNATURE;
else if (parameters.KeyNumber == Constants.CALG_RSA_KEYX)
parameters.KeyNumber = Constants.AT_KEYEXCHANGE;
// If no key container was specified and UseDefaultKeyContainer is not used, then use CRYPT_VERIFYCONTEXT
// to generate an ephemeral key
randomKeyContainer = (parameters.Flags & CspProviderFlags.CreateEphemeralKey) == CspProviderFlags.CreateEphemeralKey;
if (parameters.KeyContainerName == null && (parameters.Flags & CspProviderFlags.UseDefaultKeyContainer) == 0) {
parameters.Flags |= CspProviderFlags.CreateEphemeralKey;
randomKeyContainer = true;
}
return parameters;
}
[System.Security.SecurityCritical] // auto-generated
private static void ValidateCspFlags (CspProviderFlags flags) {
// check that the flags are consistent.
if ((flags & CspProviderFlags.UseExistingKey) != 0) {
CspProviderFlags keyFlags = (CspProviderFlags.UseNonExportableKey | CspProviderFlags.UseArchivableKey | CspProviderFlags.UseUserProtectedKey);
if ((flags & keyFlags) != CspProviderFlags.NoFlags)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"));
}
// make sure we are allowed to display the key protection UI if a user protected key is requested.
if ((flags & CspProviderFlags.UseUserProtectedKey) != 0) {
// UI only allowed in interactive session.
if (!System.Environment.UserInteractive)
throw new InvalidOperationException(Environment.GetResourceString("Cryptography_NotInteractive"));
// we need to demand UI permission here.
UIPermission uiPermission = new UIPermission(UIPermissionWindow.SafeTopLevelWindows);
uiPermission.Demand();
}
}
#endif // FEATURE_CRYPTO
private static volatile RNGCryptoServiceProvider _rng;
internal static RNGCryptoServiceProvider StaticRandomNumberGenerator {
get {
if (_rng == null)
_rng = new RNGCryptoServiceProvider();
return _rng;
}
}
//
// internal static methods
//
internal static byte[] GenerateRandom (int keySize) {
byte[] key = new byte[keySize];
StaticRandomNumberGenerator.GetBytes(key);
return key;
}
#if FEATURE_CRYPTO
/// <summary>
/// Read the FIPS policy from the pre-Vista registry key
/// </summary>
/// <returns>
/// True if the FIPS policy is enabled, false otherwise. An error reading the policy key is
/// interpreted as if the policy is enabled, and a missing key is interpreted as the policy being
/// disabled.
/// </returns>
[System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
[RegistryPermissionAttribute(SecurityAction.Assert, Read="HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Lsa")]
#pragma warning restore 618
internal static bool ReadLegacyFipsPolicy()
{
Contract.Assert(Environment.OSVersion.Version.Major < 6, "CryptGetFIPSAlgorithmMode should be used on Vista+");
try
{
using (RegistryKey fipsAlgorithmPolicyKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa", false))
{
if (fipsAlgorithmPolicyKey == null)
return false;
object data = fipsAlgorithmPolicyKey.GetValue("FIPSAlgorithmPolicy");
if (data == null)
{
return false;
}
else if (fipsAlgorithmPolicyKey.GetValueKind("FIPSAlgorithmPolicy") != RegistryValueKind.DWord)
{
return true;
}
else
{
return ((int)data != 0);
}
}
}
catch (SecurityException)
{
// If we could not open the registry key, we'll assume the setting is to enforce FIPS policy.
return true;
}
}
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// dwKeySize = 0 means the default key size
[System.Security.SecurityCritical] // auto-generated
internal static bool HasAlgorithm (int dwCalg, int dwKeySize) {
bool r = false;
// We need to take a lock here since we are querying the provider handle in a loop.
// If multiple threads are racing in this code, not all algorithms/key sizes combinations
// will be examined; which may lead to a situation where false is wrongfully returned.
lock (InternalSyncObject) {
r = SearchForAlgorithm(StaticProvHandle, dwCalg, dwKeySize);
}
return r;
}
internal static int ObjToAlgId(object hashAlg, OidGroup group) {
if (hashAlg == null)
throw new ArgumentNullException("hashAlg");
Contract.EndContractBlock();
string oidValue = null;
string hashAlgString = hashAlg as string;
if (hashAlgString != null) {
oidValue = CryptoConfig.MapNameToOID(hashAlgString, group);
if (oidValue == null)
oidValue = hashAlgString; // maybe we were passed the OID value
}
else if (hashAlg is HashAlgorithm) {
oidValue = CryptoConfig.MapNameToOID(hashAlg.GetType().ToString(), group);
}
else if (hashAlg is Type) {
oidValue = CryptoConfig.MapNameToOID(hashAlg.ToString(), group);
}
if (oidValue == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
return X509Utils.GetAlgIdFromOid(oidValue, group);
}
internal static HashAlgorithm ObjToHashAlgorithm (Object hashAlg) {
if (hashAlg == null)
throw new ArgumentNullException("hashAlg");
Contract.EndContractBlock();
HashAlgorithm hash = null;
if (hashAlg is String) {
hash = (HashAlgorithm) CryptoConfig.CreateFromName((string) hashAlg);
if (hash == null) {
string oidFriendlyName = X509Utils.GetFriendlyNameFromOid((string) hashAlg, OidGroup.HashAlgorithm);
if (oidFriendlyName != null)
hash = (HashAlgorithm) CryptoConfig.CreateFromName(oidFriendlyName);
}
}
else if (hashAlg is HashAlgorithm) {
hash = (HashAlgorithm) hashAlg;
}
else if (hashAlg is Type) {
hash = (HashAlgorithm) CryptoConfig.CreateFromName(hashAlg.ToString());
}
if (hash == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
return hash;
}
internal static String DiscardWhiteSpaces (string inputBuffer) {
return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length);
}
internal static String DiscardWhiteSpaces (string inputBuffer, int inputOffset, int inputCount) {
int i, iCount = 0;
for (i=0; i<inputCount; i++)
if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++;
char[] output = new char[inputCount - iCount];
iCount = 0;
for (i=0; i<inputCount; i++) {
if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i]))
output[iCount++] = inputBuffer[inputOffset + i];
}
return new String(output);
}
internal static int ConvertByteArrayToInt (byte[] input) {
// Input to this routine is always big endian
int dwOutput = 0;
for (int i = 0; i < input.Length; i++) {
dwOutput *= 256;
dwOutput += input[i];
}
return(dwOutput);
}
// output of this routine is always big endian
internal static byte[] ConvertIntToByteArray (int dwInput) {
byte[] temp = new byte[8]; // int can never be greater than Int64
int t1; // t1 is remaining value to account for
int t2; // t2 is t1 % 256
int i = 0;
if (dwInput == 0) return new byte[1];
t1 = dwInput;
while (t1 > 0) {
Contract.Assert(i < 8, "Got too big an int here!");
t2 = t1 % 256;
temp[i] = (byte) t2;
t1 = (t1 - t2)/256;
i++;
}
// Now, copy only the non-zero part of temp and reverse
byte[] output = new byte[i];
// copy and reverse in one pass
for (int j = 0; j < i; j++) {
output[j] = temp[i-j-1];
}
return output;
}
// output is little endian
internal static void ConvertIntToByteArray (uint dwInput, ref byte[] counter) {
uint t1 = dwInput; // t1 is remaining value to account for
uint t2; // t2 is t1 % 256
int i = 0;
// clear the array first
Array.Clear(counter, 0, counter.Length);
if (dwInput == 0) return;
while (t1 > 0) {
Contract.Assert(i < 4, "Got too big an int here!");
t2 = t1 % 256;
counter[3 - i] = (byte) t2;
t1 = (t1 - t2)/256;
i++;
}
}
internal static byte[] FixupKeyParity (byte[] key) {
byte[] oddParityKey = new byte[key.Length];
for (int index=0; index < key.Length; index++) {
// Get the bits we are interested in
oddParityKey[index] = (byte) (key[index] & 0xfe);
// Get the parity of the sum of the previous bits
byte tmp1 = (byte)((oddParityKey[index] & 0xF) ^ (oddParityKey[index] >> 4));
byte tmp2 = (byte)((tmp1 & 0x3) ^ (tmp1 >> 2));
byte sumBitsMod2 = (byte)((tmp2 & 0x1) ^ (tmp2 >> 1));
// We need to set the last bit in oddParityKey[index] to the negation
// of the last bit in sumBitsMod2
if (sumBitsMod2 == 0)
oddParityKey[index] |= 1;
}
return oddParityKey;
}
// digits == number of DWORDs
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void DWORDFromLittleEndian (uint* x, int digits, byte* block) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4)
x[i] = (uint) (block[j] | (block[j+1] << 8) | (block[j+2] << 16) | (block[j+3] << 24));
}
// encodes x (DWORD) into block (unsigned char), least significant byte first.
// digits == number of DWORDs
internal static void DWORDToLittleEndian (byte[] block, uint[] x, int digits) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4) {
block[j] = (byte)(x[i] & 0xff);
block[j+1] = (byte)((x[i] >> 8) & 0xff);
block[j+2] = (byte)((x[i] >> 16) & 0xff);
block[j+3] = (byte)((x[i] >> 24) & 0xff);
}
}
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// digits == number of DWORDs
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void DWORDFromBigEndian (uint* x, int digits, byte* block) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4)
x[i] = (uint)((block[j] << 24) | (block[j + 1] << 16) | (block[j + 2] << 8) | block[j + 3]);
}
// encodes x (DWORD) into block (unsigned char), most significant byte first.
// digits == number of DWORDs
internal static void DWORDToBigEndian (byte[] block, uint[] x, int digits) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4) {
block[j] = (byte)((x[i] >> 24) & 0xff);
block[j+1] = (byte)((x[i] >> 16) & 0xff);
block[j+2] = (byte)((x[i] >> 8) & 0xff);
block[j+3] = (byte)(x[i] & 0xff);
}
}
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// digits == number of QWORDs
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void QuadWordFromBigEndian (UInt64* x, int digits, byte* block) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 8)
x[i] = (
(((UInt64)block[j]) << 56) | (((UInt64)block[j+1]) << 48) |
(((UInt64)block[j+2]) << 40) | (((UInt64)block[j+3]) << 32) |
(((UInt64)block[j+4]) << 24) | (((UInt64)block[j+5]) << 16) |
(((UInt64)block[j+6]) << 8) | ((UInt64)block[j+7])
);
}
// encodes x (DWORD) into block (unsigned char), most significant byte first.
// digits = number of QWORDS
internal static void QuadWordToBigEndian (byte[] block, UInt64[] x, int digits) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 8) {
block[j] = (byte)((x[i] >> 56) & 0xff);
block[j+1] = (byte)((x[i] >> 48) & 0xff);
block[j+2] = (byte)((x[i] >> 40) & 0xff);
block[j+3] = (byte)((x[i] >> 32) & 0xff);
block[j+4] = (byte)((x[i] >> 24) & 0xff);
block[j+5] = (byte)((x[i] >> 16) & 0xff);
block[j+6] = (byte)((x[i] >> 8) & 0xff);
block[j+7] = (byte)(x[i] & 0xff);
}
}
#endif // FEATURE_CRYPTO
// encodes the integer i into a 4-byte array, in big endian.
internal static byte[] Int(uint i) {
return unchecked(new byte[] { (byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i });
}
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
internal static byte[] RsaOaepEncrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, RandomNumberGenerator rng, byte[] data) {
int cb = rsa.KeySize / 8;
// 1. Hash the parameters to get PHash
int cbHash = hash.HashSize / 8;
if ((data.Length + 2 + 2*cbHash) > cb)
throw new CryptographicException(String.Format(null, Environment.GetResourceString("Cryptography_Padding_EncDataTooBig"), cb-2-2*cbHash));
hash.ComputeHash(EmptyArray<Byte>.Value); // Use an empty octet string
// 2. Create DB object
byte[] DB = new byte[cb - cbHash];
// Structure is as follows:
// pHash || PS || 01 || M
// PS consists of all zeros
Buffer.InternalBlockCopy(hash.Hash, 0, DB, 0, cbHash);
DB[DB.Length - data.Length - 1] = 1;
Buffer.InternalBlockCopy(data, 0, DB, DB.Length-data.Length, data.Length);
// 3. Create a random value of size hLen
byte[] seed = new byte[cbHash];
rng.GetBytes(seed);
// 4. Compute the mask value
byte[] mask = mgf.GenerateMask(seed, DB.Length);
// 5. Xor maskDB into DB
for (int i=0; i < DB.Length; i++) {
DB[i] = (byte) (DB[i] ^ mask[i]);
}
// 6. Compute seed mask value
mask = mgf.GenerateMask(DB, cbHash);
// 7. Xor mask into seed
for (int i=0; i < seed.Length; i++) {
seed[i] ^= mask[i];
}
// 8. Concatenate seed and DB to form value to encrypt
byte[] pad = new byte[cb];
Buffer.InternalBlockCopy(seed, 0, pad, 0, seed.Length);
Buffer.InternalBlockCopy(DB, 0, pad, seed.Length, DB.Length);
return rsa.EncryptValue(pad);
}
[System.Security.SecurityCritical] // auto-generated
internal static byte[] RsaOaepDecrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, byte[] encryptedData) {
int cb = rsa.KeySize / 8;
// 1. Decode the input data
// It is important that the Integer to Octet String conversion errors be indistinguishable from the other decoding
// errors to protect against chosen cipher text attacks
// A lecture given by James Manger during Crypto 2001 explains the issue in details
byte[] data = null;
try {
data = rsa.DecryptValue(encryptedData);
}
catch (CryptographicException) {
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
}
// 2. Create the hash object so we can get its size info.
int cbHash = hash.HashSize / 8;
// 3. Let maskedSeed be the first hLen octects and maskedDB
// be the remaining bytes.
int zeros = cb - data.Length;
if (zeros < 0 || zeros >= cbHash)
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
byte[] seed = new byte[cbHash];
Buffer.InternalBlockCopy(data, 0, seed, zeros, seed.Length - zeros);
byte[] DB = new byte[data.Length - seed.Length + zeros];
Buffer.InternalBlockCopy(data, seed.Length - zeros, DB, 0, DB.Length);
// 4. seedMask = MGF(maskedDB, hLen);
byte[] mask = mgf.GenerateMask(DB, seed.Length);
// 5. seed = seedMask XOR maskedSeed
int i = 0;
for (i=0; i < seed.Length; i++) {
seed[i] ^= mask[i];
}
// 6. dbMask = MGF(seed, |EM| - hLen);
mask = mgf.GenerateMask(seed, DB.Length);
// 7. DB = maskedDB xor dbMask
for (i=0; i < DB.Length; i++) {
DB[i] = (byte) (DB[i] ^ mask[i]);
}
// 8. pHash = HASH(P)
hash.ComputeHash(EmptyArray<Byte>.Value);
// 9. DB = pHash' || PS || 01 || M
// 10. Check that pHash = pHash'
byte[] hashValue = hash.Hash;
for (i=0; i < cbHash; i++) {
if (DB[i] != hashValue[i])
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
}
// Check that PS is all zeros
for (; i<DB.Length; i++) {
if (DB[i] == 1)
break;
else if (DB[i] != 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
}
if (i == DB.Length)
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
i++; // skip over the one
// 11. Output M.
byte[] output = new byte[DB.Length - i];
Buffer.InternalBlockCopy(DB, i, output, 0, output.Length);
return output;
}
[System.Security.SecurityCritical] // auto-generated
internal static byte[] RsaPkcs1Padding (RSA rsa, byte[] oid, byte[] hash) {
int cb = rsa.KeySize/8;
byte[] pad = new byte[cb];
//
// We want to pad this to the following format:
//
// 00 || 01 || FF ... FF || 00 || prefix || Data
//
// We want basically to ASN 1 encode the OID + hash:
// STRUCTURE {
// STRUCTURE {
// OID <hash algorithm OID>
// NULL (0x05 0x00) // this is actually an ANY and contains the parameters of the algorithm specified by the OID, I think
// }
// OCTET STRING <hashvalue>
// }
//
// Get the correct prefix
byte[] data = new byte[oid.Length + 8 + hash.Length];
data[0] = 0x30; // a structure follows
int tmp = data.Length - 2;
data[1] = (byte) tmp;
data[2] = 0x30;
tmp = oid.Length + 2;
data[3] = (byte) tmp;
Buffer.InternalBlockCopy(oid, 0, data, 4, oid.Length);
data[4 + oid.Length] = 0x05;
data[4 + oid.Length + 1] = 0x00;
data[4 + oid.Length + 2] = 0x04; // an octet string follows
data[4 + oid.Length + 3] = (byte) hash.Length;
Buffer.InternalBlockCopy(hash, 0, data, oid.Length + 8, hash.Length);
// Construct the whole array
int cb1 = cb - data.Length;
if (cb1 <= 2)
throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_InvalidOID"));
pad[0] = 0;
pad[1] = 1;
for (int i=2; i<cb1-1; i++) {
pad[i] = 0xff;
}
pad[cb1-1] = 0;
Buffer.InternalBlockCopy(data, 0, pad, cb1, data.Length);
return pad;
}
// This routine compares 2 big ints; ignoring any leading zeros
internal static bool CompareBigIntArrays (byte[] lhs, byte[] rhs) {
if (lhs == null)
return (rhs == null);
int i = 0, j = 0;
while (i < lhs.Length && lhs[i] == 0) i++;
while (j < rhs.Length && rhs[j] == 0) j++;
int count = (lhs.Length - i);
if ((rhs.Length - j) != count)
return false;
for (int k = 0; k < count; k++) {
if (lhs[i + k] != rhs[j + k])
return false;
}
return true;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern SafeHashHandle CreateHash(SafeProvHandle hProv, int algid);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void EndHash(SafeHashHandle hHash, ObjectHandleOnStack retHash);
[System.Security.SecurityCritical] // auto-generated
internal static byte[] EndHash(SafeHashHandle hHash)
{
byte[] hash = null;
EndHash(hHash, JitHelpers.GetObjectHandleOnStack(ref hash));
return hash;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void ExportCspBlob(SafeKeyHandle hKey, int blobType, ObjectHandleOnStack retBlob);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern bool GetPersistKeyInCsp(SafeProvHandle hProv);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void HashData(SafeHashHandle hHash, byte[] data, int cbData, int ibStart, int cbSize);
[System.Security.SecurityCritical] // auto-generated
internal static void HashData(SafeHashHandle hHash, byte[] data, int ibStart, int cbSize)
{
HashData(hHash, data, data.Length, ibStart, cbSize);
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern bool SearchForAlgorithm(SafeProvHandle hProv, int algID, int keyLength);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetKeyParamDw(SafeKeyHandle hKey, int param, int dwValue);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetKeyParamRgb(SafeKeyHandle hKey, int param, byte[] value, int cbValue);
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern int SetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, byte[] sd);
#endif //FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetPersistKeyInCsp(SafeProvHandle hProv, bool fPersistKeyInCsp);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetProviderParameter(SafeProvHandle hProv, int keyNumber, uint paramID, IntPtr pbData);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash, int cbHash, ObjectHandleOnStack retSignature);
[System.Security.SecurityCritical] // auto-generated
internal static byte[] SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash)
{
byte[] signature = null;
SignValue(hKey, keyNumber, calgKey, calgHash, hash, hash.Length, JitHelpers.GetObjectHandleOnStack(ref signature));
return signature;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, int cbHash, byte[] signature, int cbSignature);
[System.Security.SecurityCritical] // auto-generated
internal static bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, byte[] signature)
{
return VerifySign(hKey, calgKey, calgHash, hash, hash.Length, signature, signature.Length);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _CreateCSP(CspParameters param, bool randomKeyContainer, ref SafeProvHandle hProv);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _DecryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _EncryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _ExportKey(SafeKeyHandle hKey, int blobType, object cspObject);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _GenerateKey(SafeProvHandle hProv, int algid, CspProviderFlags flags, int keySize, ref SafeKeyHandle hKey);
#endif // FEATURE_CRYPTO
[System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool _GetEnforceFipsPolicySetting();
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetKeyParameter(SafeKeyHandle hKey, uint paramID);
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, out int error);
#endif //FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object _GetProviderParameter(SafeProvHandle hProv, int keyNumber, uint paramID);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _GetUserKey(SafeProvHandle hProv, int keyNumber, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _ImportBulkKey(SafeProvHandle hProv, int algid, bool useSalt, byte[] key, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _ImportCspBlob(byte[] keyBlob, SafeProvHandle hProv, CspProviderFlags flags, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _ImportKey(SafeProvHandle hCSP, int keyNumber, CspProviderFlags flags, object cspObject, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool _ProduceLegacyHmacValues();
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _OpenCSP(CspParameters param, uint flags, ref SafeProvHandle hProv);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _AcquireCSP(CspParameters param, ref SafeProvHandle hProv);
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ITransactionHistoryOriginalData : ISchemaBaseOriginalData
{
int ReferenceOrderID { get; }
System.DateTime TransactionDate { get; }
string TransactionType { get; }
int Quantity { get; }
string ActualCost { get; }
int ReferenceOrderLineID { get; }
}
public partial class TransactionHistory : OGM<TransactionHistory, TransactionHistory.TransactionHistoryData, System.String>, ISchemaBase, INeo4jBase, ITransactionHistoryOriginalData
{
#region Initialize
static TransactionHistory()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, TransactionHistory> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.TransactionHistoryAlias, IWhereQuery> query)
{
q.TransactionHistoryAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.TransactionHistory.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"TransactionHistory => ReferenceOrderID : {this.ReferenceOrderID}, TransactionDate : {this.TransactionDate}, TransactionType : {this.TransactionType}, Quantity : {this.Quantity}, ActualCost : {this.ActualCost}, ReferenceOrderLineID : {this.ReferenceOrderLineID}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new TransactionHistoryData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.ReferenceOrderID == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the ReferenceOrderID cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.TransactionDate == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the TransactionDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.TransactionType == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the TransactionType cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.Quantity == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the Quantity cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ActualCost == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the ActualCost cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ReferenceOrderLineID == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the ReferenceOrderLineID cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save TransactionHistory with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class TransactionHistoryData : Data<System.String>
{
public TransactionHistoryData()
{
}
public TransactionHistoryData(TransactionHistoryData data)
{
ReferenceOrderID = data.ReferenceOrderID;
TransactionDate = data.TransactionDate;
TransactionType = data.TransactionType;
Quantity = data.Quantity;
ActualCost = data.ActualCost;
ReferenceOrderLineID = data.ReferenceOrderLineID;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "TransactionHistory";
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("ReferenceOrderID", Conversion<int, long>.Convert(ReferenceOrderID));
dictionary.Add("TransactionDate", Conversion<System.DateTime, long>.Convert(TransactionDate));
dictionary.Add("TransactionType", TransactionType);
dictionary.Add("Quantity", Conversion<int, long>.Convert(Quantity));
dictionary.Add("ActualCost", ActualCost);
dictionary.Add("ReferenceOrderLineID", Conversion<int, long>.Convert(ReferenceOrderLineID));
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("ReferenceOrderID", out value))
ReferenceOrderID = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("TransactionDate", out value))
TransactionDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("TransactionType", out value))
TransactionType = (string)value;
if (properties.TryGetValue("Quantity", out value))
Quantity = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("ActualCost", out value))
ActualCost = (string)value;
if (properties.TryGetValue("ReferenceOrderLineID", out value))
ReferenceOrderLineID = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ITransactionHistory
public int ReferenceOrderID { get; set; }
public System.DateTime TransactionDate { get; set; }
public string TransactionType { get; set; }
public int Quantity { get; set; }
public string ActualCost { get; set; }
public int ReferenceOrderLineID { get; set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ITransactionHistory
public int ReferenceOrderID { get { LazyGet(); return InnerData.ReferenceOrderID; } set { if (LazySet(Members.ReferenceOrderID, InnerData.ReferenceOrderID, value)) InnerData.ReferenceOrderID = value; } }
public System.DateTime TransactionDate { get { LazyGet(); return InnerData.TransactionDate; } set { if (LazySet(Members.TransactionDate, InnerData.TransactionDate, value)) InnerData.TransactionDate = value; } }
public string TransactionType { get { LazyGet(); return InnerData.TransactionType; } set { if (LazySet(Members.TransactionType, InnerData.TransactionType, value)) InnerData.TransactionType = value; } }
public int Quantity { get { LazyGet(); return InnerData.Quantity; } set { if (LazySet(Members.Quantity, InnerData.Quantity, value)) InnerData.Quantity = value; } }
public string ActualCost { get { LazyGet(); return InnerData.ActualCost; } set { if (LazySet(Members.ActualCost, InnerData.ActualCost, value)) InnerData.ActualCost = value; } }
public int ReferenceOrderLineID { get { LazyGet(); return InnerData.ReferenceOrderLineID; } set { if (LazySet(Members.ReferenceOrderLineID, InnerData.ReferenceOrderLineID, value)) InnerData.ReferenceOrderLineID = value; } }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static TransactionHistoryMembers members = null;
public static TransactionHistoryMembers Members
{
get
{
if (members == null)
{
lock (typeof(TransactionHistory))
{
if (members == null)
members = new TransactionHistoryMembers();
}
}
return members;
}
}
public class TransactionHistoryMembers
{
internal TransactionHistoryMembers() { }
#region Members for interface ITransactionHistory
public Property ReferenceOrderID { get; } = Datastore.AdventureWorks.Model.Entities["TransactionHistory"].Properties["ReferenceOrderID"];
public Property TransactionDate { get; } = Datastore.AdventureWorks.Model.Entities["TransactionHistory"].Properties["TransactionDate"];
public Property TransactionType { get; } = Datastore.AdventureWorks.Model.Entities["TransactionHistory"].Properties["TransactionType"];
public Property Quantity { get; } = Datastore.AdventureWorks.Model.Entities["TransactionHistory"].Properties["Quantity"];
public Property ActualCost { get; } = Datastore.AdventureWorks.Model.Entities["TransactionHistory"].Properties["ActualCost"];
public Property ReferenceOrderLineID { get; } = Datastore.AdventureWorks.Model.Entities["TransactionHistory"].Properties["ReferenceOrderLineID"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static TransactionHistoryFullTextMembers fullTextMembers = null;
public static TransactionHistoryFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(TransactionHistory))
{
if (fullTextMembers == null)
fullTextMembers = new TransactionHistoryFullTextMembers();
}
}
return fullTextMembers;
}
}
public class TransactionHistoryFullTextMembers
{
internal TransactionHistoryFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(TransactionHistory))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["TransactionHistory"];
}
}
return entity;
}
private static TransactionHistoryEvents events = null;
public static TransactionHistoryEvents Events
{
get
{
if (events == null)
{
lock (typeof(TransactionHistory))
{
if (events == null)
events = new TransactionHistoryEvents();
}
}
return events;
}
}
public class TransactionHistoryEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<TransactionHistory, EntityEventArgs> onNew;
public event EventHandler<TransactionHistory, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<TransactionHistory, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<TransactionHistory, EntityEventArgs> onDelete;
public event EventHandler<TransactionHistory, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<TransactionHistory, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<TransactionHistory, EntityEventArgs> onSave;
public event EventHandler<TransactionHistory, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<TransactionHistory, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnReferenceOrderID
private static bool onReferenceOrderIDIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onReferenceOrderID;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnReferenceOrderID
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onReferenceOrderIDIsRegistered)
{
Members.ReferenceOrderID.Events.OnChange -= onReferenceOrderIDProxy;
Members.ReferenceOrderID.Events.OnChange += onReferenceOrderIDProxy;
onReferenceOrderIDIsRegistered = true;
}
onReferenceOrderID += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onReferenceOrderID -= value;
if (onReferenceOrderID == null && onReferenceOrderIDIsRegistered)
{
Members.ReferenceOrderID.Events.OnChange -= onReferenceOrderIDProxy;
onReferenceOrderIDIsRegistered = false;
}
}
}
}
private static void onReferenceOrderIDProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onReferenceOrderID;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnTransactionDate
private static bool onTransactionDateIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onTransactionDate;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnTransactionDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onTransactionDateIsRegistered)
{
Members.TransactionDate.Events.OnChange -= onTransactionDateProxy;
Members.TransactionDate.Events.OnChange += onTransactionDateProxy;
onTransactionDateIsRegistered = true;
}
onTransactionDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onTransactionDate -= value;
if (onTransactionDate == null && onTransactionDateIsRegistered)
{
Members.TransactionDate.Events.OnChange -= onTransactionDateProxy;
onTransactionDateIsRegistered = false;
}
}
}
}
private static void onTransactionDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onTransactionDate;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnTransactionType
private static bool onTransactionTypeIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onTransactionType;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnTransactionType
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onTransactionTypeIsRegistered)
{
Members.TransactionType.Events.OnChange -= onTransactionTypeProxy;
Members.TransactionType.Events.OnChange += onTransactionTypeProxy;
onTransactionTypeIsRegistered = true;
}
onTransactionType += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onTransactionType -= value;
if (onTransactionType == null && onTransactionTypeIsRegistered)
{
Members.TransactionType.Events.OnChange -= onTransactionTypeProxy;
onTransactionTypeIsRegistered = false;
}
}
}
}
private static void onTransactionTypeProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onTransactionType;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnQuantity
private static bool onQuantityIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onQuantity;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnQuantity
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onQuantityIsRegistered)
{
Members.Quantity.Events.OnChange -= onQuantityProxy;
Members.Quantity.Events.OnChange += onQuantityProxy;
onQuantityIsRegistered = true;
}
onQuantity += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onQuantity -= value;
if (onQuantity == null && onQuantityIsRegistered)
{
Members.Quantity.Events.OnChange -= onQuantityProxy;
onQuantityIsRegistered = false;
}
}
}
}
private static void onQuantityProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onQuantity;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnActualCost
private static bool onActualCostIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onActualCost;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnActualCost
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onActualCostIsRegistered)
{
Members.ActualCost.Events.OnChange -= onActualCostProxy;
Members.ActualCost.Events.OnChange += onActualCostProxy;
onActualCostIsRegistered = true;
}
onActualCost += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onActualCost -= value;
if (onActualCost == null && onActualCostIsRegistered)
{
Members.ActualCost.Events.OnChange -= onActualCostProxy;
onActualCostIsRegistered = false;
}
}
}
}
private static void onActualCostProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onActualCost;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnReferenceOrderLineID
private static bool onReferenceOrderLineIDIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onReferenceOrderLineID;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnReferenceOrderLineID
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onReferenceOrderLineIDIsRegistered)
{
Members.ReferenceOrderLineID.Events.OnChange -= onReferenceOrderLineIDProxy;
Members.ReferenceOrderLineID.Events.OnChange += onReferenceOrderLineIDProxy;
onReferenceOrderLineIDIsRegistered = true;
}
onReferenceOrderLineID += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onReferenceOrderLineID -= value;
if (onReferenceOrderLineID == null && onReferenceOrderLineIDIsRegistered)
{
Members.ReferenceOrderLineID.Events.OnChange -= onReferenceOrderLineIDProxy;
onReferenceOrderLineIDIsRegistered = false;
}
}
}
}
private static void onReferenceOrderLineIDProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onReferenceOrderLineID;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onModifiedDate;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<TransactionHistory, PropertyEventArgs> onUid;
public static event EventHandler<TransactionHistory, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<TransactionHistory, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((TransactionHistory)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ITransactionHistoryOriginalData
public ITransactionHistoryOriginalData OriginalVersion { get { return this; } }
#region Members for interface ITransactionHistory
int ITransactionHistoryOriginalData.ReferenceOrderID { get { return OriginalData.ReferenceOrderID; } }
System.DateTime ITransactionHistoryOriginalData.TransactionDate { get { return OriginalData.TransactionDate; } }
string ITransactionHistoryOriginalData.TransactionType { get { return OriginalData.TransactionType; } }
int ITransactionHistoryOriginalData.Quantity { get { return OriginalData.Quantity; } }
string ITransactionHistoryOriginalData.ActualCost { get { return OriginalData.ActualCost; } }
int ITransactionHistoryOriginalData.ReferenceOrderLineID { get { return OriginalData.ReferenceOrderLineID; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ExceptionHandlingExpressions
{
// As this class is only used here, it is distinguished from an exception
// being thrown due to an actual error.
protected class TestException : Exception
{
public TestException()
: base("This is a test exception")
{
}
}
protected class DerivedTestException : TestException
{
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ThrowNullSameAsRethrow(bool useInterpreter)
{
UnaryExpression rethrow = Expression.Rethrow();
UnaryExpression nullThrow = Expression.Throw(null);
Assert.Equal(rethrow.GetType(), nullThrow.GetType());
TryExpression rethrowTwice = Expression.TryCatch(
Expression.TryCatch(
Expression.Throw(Expression.Constant(new TestException())),
Expression.Catch(typeof(TestException), rethrow)
),
Expression.Catch(typeof(TestException), nullThrow)
);
Action doRethrowTwice = Expression.Lambda<Action>(rethrowTwice).Compile(useInterpreter);
Assert.Throws<TestException>(doRethrowTwice);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void TypedThrowNullSameAsRethrow(bool useInterpreter)
{
UnaryExpression rethrow = Expression.Rethrow(typeof(int));
UnaryExpression nullThrow = Expression.Throw(null, typeof(int));
Assert.Equal(rethrow.GetType(), nullThrow.GetType());
TryExpression rethrowTwice = Expression.TryCatch(
Expression.TryCatch(
Expression.Throw(Expression.Constant(new TestException()), typeof(int)),
Expression.Catch(typeof(TestException), rethrow)
),
Expression.Catch(typeof(TestException), nullThrow)
);
Action doRethrowTwice = Expression.Lambda<Action>(rethrowTwice).Compile(useInterpreter);
Assert.Throws<TestException>(() => doRethrowTwice());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CannotRethrowOutsideCatch(bool useInterpreter)
{
LambdaExpression rethrowNothing = Expression.Lambda<Action>(Expression.Rethrow());
Assert.Throws<InvalidOperationException>(() => rethrowNothing.Compile(useInterpreter));
}
[Theory]
[InlineData(false)]
public void CanCatchAndThrowNonExceptions(bool useInterpreter)
{
TryExpression throwCatchString = Expression.TryCatch(
Expression.Throw(Expression.Constant("Hello")),
Expression.Catch(typeof(string), Expression.Empty())
);
Expression.Lambda<Action>(throwCatchString).Compile(useInterpreter)();
}
[Fact]
[ActiveIssue(5898)]
public void CanCatchAndThrowNonExceptionsInterpreted()
{
CanCatchAndThrowNonExceptions(true);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ThrowNullThrowsNRE(bool useInterpreter)
{
Action throwNull = Expression.Lambda<Action>(
Expression.Throw(Expression.Constant(null, typeof(Expression)))
).Compile(useInterpreter);
Assert.Throws<NullReferenceException>(throwNull);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ThrowNullThrowsCatchableNRE(bool useInterpreter)
{
Func<int> throwCatchNull = Expression.Lambda<Func<int>>(
Expression.TryCatch(
Expression.Throw(Expression.Constant(null, typeof(ArgumentException)), typeof(int)),
Expression.Catch(typeof(ArgumentException), Expression.Constant(1)),
Expression.Catch(typeof(NullReferenceException), Expression.Constant(2)),
Expression.Catch(typeof(Expression), Expression.Constant(3))
)
).Compile(useInterpreter);
Assert.Equal(2, throwCatchNull());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanCatchExceptionAsObject(bool useInterpreter)
{
Func<int> throwCatchAsObject = Expression.Lambda<Func<int>>(
Expression.TryCatch(
Expression.Throw(Expression.Constant(new Exception()), typeof(int)),
Expression.Catch(typeof(ArgumentException), Expression.Constant(1)),
Expression.Catch(typeof(object), Expression.Constant(2))
)
).Compile(useInterpreter);
Assert.Equal(2, throwCatchAsObject());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanCatchExceptionAsObjectObtainingException(bool useInterpreter)
{
Exception testException = new Exception();
ParameterExpression param = Expression.Parameter(typeof(object));
Func<object> throwCatchAsObject = Expression.Lambda<Func<object>>(
Expression.TryCatch(
Expression.Throw(Expression.Constant(testException), typeof(object)),
Expression.Catch(typeof(ArgumentException), Expression.Constant("Will be skipped", typeof(object))),
Expression.Catch(param, param)
)
).Compile(useInterpreter);
Assert.Same(testException, throwCatchAsObject());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanAccessExceptionCaught(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(Exception));
TryExpression throwCatch = Expression.TryCatch(
Expression.Throw(Expression.Constant(new TestException()), typeof(string)),
Expression.Catch(variable, Expression.Property(variable, "Message"))
);
Assert.Equal("This is a test exception", Expression.Lambda<Func<string>>(throwCatch).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FromMakeMethods(bool useInterpreter)
{
TryExpression tryExp = Expression.MakeTry(
typeof(int),
Expression.MakeUnary(ExpressionType.Throw, Expression.Constant(new TestException()), typeof(int)),
null,
null,
new[] { Expression.MakeCatchBlock(typeof(TestException), null, Expression.Constant(3), null) }
);
Assert.Equal(3, Expression.Lambda<Func<int>>(tryExp).Compile(useInterpreter)());
}
[Fact]
public void CannotReduceThrow()
{
UnaryExpression throwExp = Expression.Throw(Expression.Constant(new TestException()));
Assert.False(throwExp.CanReduce);
Assert.Same(throwExp, throwExp.Reduce());
Assert.Throws<ArgumentException>(() => throwExp.ReduceAndCheck());
}
[Fact]
public void CannotReduceTry()
{
TryExpression tryExp = Expression.TryFault(Expression.Empty(), Expression.Empty());
Assert.False(tryExp.CanReduce);
Assert.Same(tryExp, tryExp.Reduce());
Assert.Throws<ArgumentException>(() => tryExp.ReduceAndCheck());
}
[Fact]
public void CannotThrowValueType()
{
Assert.Throws<ArgumentException>(() => Expression.Throw(Expression.Constant(1)));
}
[Fact]
public void CanCatchValueType()
{
// We can't test the actual catching with just C# and Expressions, but we can
// test that creating such catch blocks doesn't throw.
Expression.Catch(typeof(int), Expression.Empty());
Expression.Catch(Expression.Variable(typeof(int)), Expression.Empty());
Expression.Catch(Expression.Variable(typeof(int)), Expression.Empty(), Expression.Constant(true));
Expression.Catch(typeof(int), Expression.Empty(), Expression.Constant(true));
}
[Fact]
public void MustHaveCatchFinallyOrFault()
{
Assert.Throws<ArgumentException>(() => Expression.MakeTry(typeof(int), Expression.Constant(1), null, null, null));
}
[Fact]
public void FaultMustNotBeWithCatch()
{
Assert.Throws<ArgumentException>(() => Expression.MakeTry(typeof(int), Expression.Constant(1), null, Expression.Constant(2), new[] { Expression.Catch(typeof(object), Expression.Constant(3)) }));
}
[Fact]
public void FaultMustNotBeWithFinally()
{
Assert.Throws<ArgumentException>(() => Expression.MakeTry(typeof(int), Expression.Constant(1), Expression.Constant(2), Expression.Constant(3), null));
}
[Fact]
public void TryMustNotHaveNullBody()
{
Assert.Throws<ArgumentNullException>("body", () => Expression.TryCatch(null, Expression.Catch(typeof(object), Expression.Constant(1))));
Assert.Throws<ArgumentNullException>("body", () => Expression.TryCatchFinally(null, Expression.Constant(1), Expression.Catch(typeof(object), Expression.Constant(1))));
Assert.Throws<ArgumentNullException>("body", () => Expression.TryFault(null, Expression.Constant(1)));
Assert.Throws<ArgumentNullException>("body", () => Expression.TryFinally(null, Expression.Constant(1)));
}
[Fact]
public void TryMustHaveReadableBody()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("body", () => Expression.TryCatch(value, Expression.Catch(typeof(object), Expression.Constant(1))));
Assert.Throws<ArgumentException>("body", () => Expression.TryCatchFinally(value, Expression.Constant(1), Expression.Catch(typeof(object), Expression.Constant(1))));
Assert.Throws<ArgumentException>("body", () => Expression.TryFault(value, Expression.Constant(1)));
Assert.Throws<ArgumentException>("body", () => Expression.TryFinally(value, Expression.Constant(1)));
}
[Fact]
public void FaultMustBeReadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("fault", () => Expression.TryFault(Expression.Constant(1), value));
}
[Fact]
public void FinallyMustBeReadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("finally", () => Expression.TryFinally(Expression.Constant(1), value));
Assert.Throws<ArgumentException>("finally", () => Expression.TryCatchFinally(Expression.Constant(1), value, Expression.Catch(typeof(object), Expression.Constant(1))));
}
[Theory]
[InlineData(false)]
public void NonExceptionDerivedExceptionWrapped(bool useInterpreter)
{
Action throwWrapped = Expression.Lambda<Action>(Expression.Throw(Expression.Constant(""))).Compile(useInterpreter);
Exception ex = Assert.ThrowsAny<Exception>(throwWrapped);
Assert.Equal("System.Runtime.CompilerServices.RuntimeWrappedException", ex.GetType().FullName);
}
[Fact]
[ActiveIssue(5898)]
public void NonExceptionDerivedExceptionWrappedInterpreted()
{
NonExceptionDerivedExceptionWrapped(true);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyDoesNotDetermineValue(bool useInterpreter)
{
TryExpression finally2 = Expression.TryFinally(Expression.Constant(1), Expression.Constant(2));
Assert.Equal(1, Expression.Lambda<Func<int>>(finally2).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyDoesNotNeedToMatchType(bool useInterpreter)
{
TryExpression finally2 = Expression.TryFinally(Expression.Constant(1), Expression.Constant(""));
Assert.Equal(1, Expression.Lambda<Func<int>>(finally2).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyCanBeVoid(bool useInterpreter)
{
TryExpression finally2 = Expression.TryFinally(Expression.Constant(1), Expression.Empty());
Assert.Equal(1, Expression.Lambda<Func<int>>(finally2).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyCanBeNonVoidWithVoidTry(bool useInterpreter)
{
TryExpression finally2 = Expression.TryFinally(Expression.Empty(), Expression.Constant(0));
Expression.Lambda<Action>(finally2).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyDoesNotDetermineValueNothingCaught(bool useInterpreter)
{
TryExpression finally2 = Expression.TryCatchFinally(
Expression.Constant(1),
Expression.Constant(2),
Expression.Catch(typeof(object), Expression.Constant(3))
);
Assert.Equal(1, Expression.Lambda<Func<int>>(finally2).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyDoesNotDetermineValueSomethingCaught(bool useInterpreter)
{
TryExpression finally2 = Expression.TryCatchFinally(
Expression.Throw(Expression.Constant(new ArgumentException()), typeof(int)),
Expression.Constant(2),
Expression.Catch(typeof(ArgumentException), Expression.Constant(3))
);
Assert.Equal(3, Expression.Lambda<Func<int>>(finally2).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
[ActiveIssue(3838)]
public void FaultNotTriggeredOnNoThrow(bool useInterpreter)
{
ParameterExpression variable = Expression.Parameter(typeof(int));
LabelTarget target = Expression.Label(typeof(int));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(1)),
Expression.TryFault(
Expression.Empty(),
Expression.Assign(variable, Expression.Constant(2))
),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(int)))
);
Assert.Equal(1, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
[ActiveIssue(3838)]
public void FaultTriggeredOnThrow(bool useInterpreter)
{
ParameterExpression variable = Expression.Parameter(typeof(int));
LabelTarget target = Expression.Label(typeof(int));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(1)),
Expression.TryCatch(
Expression.TryFault(
Expression.Throw(Expression.Constant(new TestException())),
Expression.Assign(variable, Expression.Constant(2))
),
Expression.Catch(typeof(TestException), Expression.Empty())
),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(int)))
);
Assert.Equal(2, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyTriggeredOnNoThrow(bool useInterpreter)
{
ParameterExpression variable = Expression.Parameter(typeof(int));
LabelTarget target = Expression.Label(typeof(int));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(1)),
Expression.TryFinally(
Expression.Empty(),
Expression.Assign(variable, Expression.Constant(2))
),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(int)))
);
Assert.Equal(2, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void FinallyTriggeredOnThrow(bool useInterpreter)
{
ParameterExpression variable = Expression.Parameter(typeof(int));
LabelTarget target = Expression.Label(typeof(int));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(1)),
Expression.TryCatch(
Expression.TryFinally(
Expression.Throw(Expression.Constant(new TestException())),
Expression.Assign(variable, Expression.Constant(2))
),
Expression.Catch(typeof(TestException), Expression.Empty())
),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(int)))
);
Assert.Equal(2, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CatchChaining(bool useInterpreter)
{
TryExpression chain = Expression.TryCatch(
Expression.Throw(Expression.Constant(new DerivedTestException()), typeof(int)),
Expression.Catch(typeof(InvalidOperationException), Expression.Constant(1)),
Expression.Catch(typeof(TestException), Expression.Constant(2)),
Expression.Catch(typeof(DerivedTestException), Expression.Constant(3))
);
Assert.Equal(2, Expression.Lambda<Func<int>>(chain).Compile(useInterpreter)());
}
[Fact]
public void TypeInferred()
{
TryExpression noExplicitType = Expression.TryFault(Expression.Constant(1), Expression.Empty());
Assert.Equal(typeof(int), noExplicitType.Type);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ExplicitType(bool useInterpreter)
{
TryExpression explicitType = Expression.MakeTry(typeof(object), Expression.Constant("hello"), Expression.Empty(), null, null);
Assert.Equal(typeof(object), explicitType.Type);
Assert.Equal("hello", Expression.Lambda<Func<object>>(explicitType).Compile(useInterpreter)());
}
[Fact]
public void ByRefExceptionType()
{
ParameterExpression variable = Expression.Parameter(typeof(Exception).MakeByRefType());
Assert.Throws<ArgumentException>(() => Expression.Catch(variable, Expression.Empty()));
Assert.Throws<ArgumentException>(() => Expression.Catch(variable, Expression.Empty(), Expression.Constant(true)));
}
[Fact]
public void NullTypeOnCatch()
{
Assert.Throws<ArgumentNullException>("type", () => Expression.Catch(default(Type), Expression.Empty()));
Assert.Throws<ArgumentNullException>("type", () => Expression.Catch(default(Type), Expression.Empty(), Expression.Constant(true)));
}
[Fact]
public void NullExceptionVariableOnCatch()
{
Assert.Throws<ArgumentNullException>("variable", () => Expression.Catch(default(ParameterExpression), Expression.Empty()));
Assert.Throws<ArgumentNullException>("variable", () => Expression.Catch(default(ParameterExpression), Expression.Empty(), Expression.Constant(true)));
}
[Fact]
public void CatchBodyMustBeNotBeNull()
{
Assert.Throws<ArgumentNullException>("body", () => Expression.Catch(typeof(Exception), null));
Assert.Throws<ArgumentNullException>("body", () => Expression.Catch(typeof(Exception), null, Expression.Constant(true)));
Assert.Throws<ArgumentNullException>("body", () => Expression.Catch(Expression.Parameter(typeof(Exception)), null));
Assert.Throws<ArgumentNullException>("body", () => Expression.Catch(Expression.Parameter(typeof(Exception)), null, Expression.Constant(true)));
}
[Fact]
public void CatchBodyMustBeReadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("body", () => Expression.Catch(typeof(Exception), value));
Assert.Throws<ArgumentException>("body", () => Expression.Catch(typeof(Exception), value, Expression.Constant(true)));
Assert.Throws<ArgumentException>("body", () => Expression.Catch(Expression.Parameter(typeof(Exception)), value));
Assert.Throws<ArgumentException>("body", () => Expression.Catch(Expression.Parameter(typeof(Exception)), value, Expression.Constant(true)));
}
[Fact]
public void FilterMustBeReadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<bool>), "WriteOnly");
Assert.Throws<ArgumentException>("filter", () => Expression.Catch(typeof(Exception), Expression.Empty(), value));
Assert.Throws<ArgumentException>("filter", () => Expression.Catch(Expression.Parameter(typeof(Exception)), Expression.Empty(), value));
}
[Fact]
public void FilterMustBeBoolean()
{
Assert.Throws<ArgumentException>(() => Expression.Catch(typeof(Exception), Expression.Empty(), Expression.Constant(42)));
Assert.Throws<ArgumentException>(() => Expression.Catch(Expression.Parameter(typeof(Exception)), Expression.Empty(), Expression.Constant(42)));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
[ActiveIssue(3838)]
public void FilterOnCatch(bool useInterpreter)
{
TryExpression tryExp = Expression.TryCatch(
Expression.Throw(Expression.Constant(new TestException()), typeof(int)),
Expression.Catch(typeof(TestException), Expression.Constant(1), Expression.Constant(false)),
Expression.Catch(typeof(TestException), Expression.Constant(2), Expression.Constant(true)),
Expression.Catch(typeof(TestException), Expression.Constant(3))
);
Assert.Equal(2, Expression.Lambda<Func<int>>(tryExp).Compile(useInterpreter)());
}
[Fact]
public void NonAssignableTryAndCatchTypes()
{
Assert.Throws<ArgumentException>(() => Expression.TryCatch(Expression.Constant(new Uri("http://example.net/")), Expression.Catch(typeof(Exception), Expression.Constant("hello"))));
}
[Fact]
public void BodyTypeNotAssignableToTryType()
{
Assert.Throws<ArgumentException>(() => Expression.MakeTry(typeof(int), Expression.Constant("hello"), Expression.Empty(), null, null));
}
[Fact]
public void CatchTypeNotAssignableToTryType()
{
Assert.Throws<ArgumentException>(() => Expression.MakeTry(typeof(int), Expression.Constant(2), null, null, new[] { Expression.Catch(typeof(InvalidCastException), Expression.Constant("")) }));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReturnAnythingFromExplicitVoid(bool useInterpreter)
{
TryExpression tryExp = Expression.MakeTry(
typeof(void),
Expression.Constant(1),
null,
null,
new[]
{
Expression.Catch(typeof(InvalidCastException), Expression.Constant("hello")),
Expression.Catch(typeof(Exception), Expression.Constant(2.2))
}
);
Expression.Lambda<Action>(tryExp).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReturnAnythingFromExplicitVoidVoidBody(bool useInterpreter)
{
TryExpression tryExp = Expression.MakeTry(
typeof(void),
Expression.Constant(1),
null,
null,
new[]
{
Expression.Catch(typeof(InvalidCastException), Expression.Constant("hello")),
Expression.Catch(typeof(Exception), Expression.Constant(2.2))
}
);
Expression.Lambda<Action>(tryExp).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReturnAnythingFromExplicitVoidVoidThrowingBody(bool useInterpreter)
{
TryExpression tryExp = Expression.MakeTry(
typeof(void),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
null,
null,
new[]
{
Expression.Catch(typeof(InvalidCastException), Expression.Constant("hello")),
Expression.Catch(typeof(Exception), Expression.Constant(2.2))
}
);
Expression.Lambda<Action>(tryExp).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReturnAnythingFromExplicitVoidTypedThrowingBody(bool useInterpreter)
{
TryExpression tryExp = Expression.MakeTry(
typeof(void),
Expression.Throw(Expression.Constant(new InvalidOperationException()), typeof(int)),
null,
null,
new[]
{
Expression.Catch(typeof(InvalidCastException), Expression.Constant("hello")),
Expression.Catch(typeof(Exception), Expression.Constant(2.2))
}
);
Expression.Lambda<Action>(tryExp).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanReturnAnythingFromExplicitVoidCatch(bool useInterpreter)
{
TryExpression tryExp = Expression.MakeTry(
typeof(void),
Expression.Throw(Expression.Constant(new InvalidOperationException()), typeof(int)),
null,
null,
new[]
{
Expression.Catch(typeof(InvalidCastException), Expression.Empty()),
Expression.Catch(typeof(Exception), Expression.Constant(2.2))
}
);
Expression.Lambda<Action>(tryExp).Compile(useInterpreter)();
}
[Fact]
public void CatchesMustReturnVoidWithVoidBody()
{
Assert.Throws<ArgumentException>(
() => Expression.TryCatch(
Expression.Empty(),
Expression.Catch(typeof(InvocationExpression), Expression.Constant("hello")),
Expression.Catch(typeof(Exception), Expression.Constant(2.2))
)
);
}
[Fact]
public void UpdateCatchSameChildrenSameNode()
{
ParameterExpression var = Expression.Variable(typeof(Exception));
Expression body = Expression.Empty();
Expression filter = Expression.Default(typeof(bool));
CatchBlock cb = Expression.Catch(var, body, filter);
Assert.Same(cb, cb.Update(var, filter, body));
}
[Fact]
public void UpdateCatchDifferentVariableDifferentNode()
{
Expression body = Expression.Empty();
Expression filter = Expression.Default(typeof(bool));
CatchBlock cb = Expression.Catch(Expression.Variable(typeof(Exception)), body, filter);
Assert.NotSame(cb, cb.Update(Expression.Variable(typeof(Exception)), filter, body));
}
[Fact]
public void UpdateCatchDifferentBodyDifferentNode()
{
ParameterExpression var = Expression.Variable(typeof(Exception));
Expression filter = Expression.Default(typeof(bool));
CatchBlock cb = Expression.Catch(var, Expression.Empty(), filter);
Assert.NotSame(cb, cb.Update(var, filter, Expression.Empty()));
}
[Fact]
public void UpdateCatchDifferentFilterDifferentNode()
{
ParameterExpression var = Expression.Variable(typeof(Exception));
Expression body = Expression.Empty();
CatchBlock cb = Expression.Catch(var, body, Expression.Default(typeof(bool)));
Assert.NotSame(cb, cb.Update(var, Expression.Default(typeof(bool)), body));
}
[Fact]
public void CatchToString()
{
CatchBlock cb = Expression.Catch(typeof(TestException), Expression.Empty());
Assert.Equal("catch (" + cb.Test.Name + ") { ... }", cb.ToString());
cb = Expression.Catch(Expression.Variable(typeof(TestException)), Expression.Empty());
Assert.Equal("catch (" + cb.Test.Name + ") { ... }", cb.ToString());
}
[Fact]
public void NamedExceptionCatchToString()
{
CatchBlock cb = Expression.Catch(Expression.Variable(typeof(TestException), "ex"), Expression.Empty());
Assert.Equal("catch (" + cb.Test.Name + " ex) { ... }", cb.ToString());
}
[Fact]
public void UpdateTrySameChildrenSameNode()
{
TryExpression tryExp = Expression.TryCatchFinally(Expression.Empty(), Expression.Empty(), Expression.Catch(typeof(Exception), Expression.Empty()));
Assert.Same(tryExp, tryExp.Update(tryExp.Body, tryExp.Handlers, tryExp.Finally, tryExp.Fault));
tryExp = Expression.TryFault(Expression.Empty(), Expression.Empty());
Assert.Same(tryExp, tryExp.Update(tryExp.Body, tryExp.Handlers, tryExp.Finally, tryExp.Fault));
}
[Fact]
[ActiveIssue(3958)]
public void UpdateTrySameChildrenDifferentCollectionsSameNode()
{
TryExpression tryExp = Expression.TryCatchFinally(Expression.Empty(), Expression.Empty(), Expression.Catch(typeof(Exception), Expression.Empty()));
Assert.Same(tryExp, tryExp.Update(tryExp.Body, tryExp.Handlers.ToArray(), tryExp.Finally, null));
tryExp = Expression.TryFault(Expression.Empty(), Expression.Empty());
Assert.Same(tryExp, tryExp.Update(tryExp.Body, null, null, tryExp.Fault));
}
[Fact]
public void UpdateTryDiffBodyDiffNode()
{
TryExpression tryExp = Expression.TryCatchFinally(Expression.Empty(), Expression.Empty(), Expression.Catch(typeof(Exception), Expression.Empty()));
Assert.NotSame(tryExp, tryExp.Update(Expression.Empty(), tryExp.Handlers, tryExp.Finally, null));
tryExp = Expression.TryFault(Expression.Empty(), Expression.Empty());
Assert.NotSame(tryExp, tryExp.Update(Expression.Empty(), null, null, tryExp.Fault));
}
[Fact]
public void UpdateTryDiffHandlersDiffNode()
{
TryExpression tryExp = Expression.TryCatchFinally(Expression.Empty(), Expression.Empty(), Expression.Catch(typeof(Exception), Expression.Empty()));
Assert.NotSame(tryExp, tryExp.Update(tryExp.Body, new[] { Expression.Catch(typeof(Exception), Expression.Empty()) }, tryExp.Finally, null));
}
[Fact]
public void UpdateTryDiffFinallyDiffNode()
{
TryExpression tryExp = Expression.TryCatchFinally(Expression.Empty(), Expression.Empty(), Expression.Catch(typeof(Exception), Expression.Empty()));
Assert.NotSame(tryExp, tryExp.Update(tryExp.Body, tryExp.Handlers, Expression.Empty(), null));
}
[Fact]
public void UpdateTryDiffFaultDiffNode()
{
TryExpression tryExp = Expression.TryFault(Expression.Empty(), Expression.Empty());
Assert.NotSame(tryExp, tryExp.Update(tryExp.Body, tryExp.Handlers, tryExp.Finally, Expression.Empty()));
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class NetworkStreamTest
{
[Fact]
public void Ctor_NullSocket_ThrowsArgumentNullExceptions()
{
AssertExtensions.Throws<ArgumentNullException>("socket", () => new NetworkStream(null));
AssertExtensions.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, false));
AssertExtensions.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, true));
AssertExtensions.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, FileAccess.ReadWrite));
AssertExtensions.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, FileAccess.ReadWrite, false));
}
[Fact]
public void Ctor_NotConnected_ThrowsIOException()
{
Assert.Throws<IOException>(() => new NetworkStream(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)));
}
[Fact]
public async Task Ctor_NotStream_ThrowsIOException()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port));
Assert.Throws<IOException>(() => new NetworkStream(client));
}
}
[Fact]
public async Task Ctor_NonBlockingSocket_ThrowsIOException()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
server.Blocking = false;
Assert.Throws<IOException>(() => new NetworkStream(server));
}
}
}
[Fact]
public async Task Ctor_Socket_CanReadAndWrite_DoesntOwn()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets
{
using (var serverStream = new NetworkStream(server))
using (var clientStream = new NetworkStream(client))
{
Assert.True(serverStream.CanWrite && serverStream.CanRead);
Assert.True(clientStream.CanWrite && clientStream.CanRead);
Assert.False(serverStream.CanSeek && clientStream.CanSeek);
Assert.True(serverStream.CanTimeout && clientStream.CanTimeout);
// Verify Read and Write on both streams
byte[] buffer = new byte[1];
await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1);
Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1));
Assert.Equal('a', (char)buffer[0]);
await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1);
Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1));
Assert.Equal('b', (char)buffer[0]);
}
}
}
}
}
[Theory]
[InlineData(FileAccess.ReadWrite)]
[InlineData((FileAccess)42)] // unknown values treated as ReadWrite
public async Task Ctor_SocketFileAccessBool_CanReadAndWrite_DoesntOwn(FileAccess access)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets
{
using (var serverStream = new NetworkStream(server, access, false))
using (var clientStream = new NetworkStream(client, access, false))
{
Assert.True(serverStream.CanWrite && serverStream.CanRead);
Assert.True(clientStream.CanWrite && clientStream.CanRead);
Assert.False(serverStream.CanSeek && clientStream.CanSeek);
Assert.True(serverStream.CanTimeout && clientStream.CanTimeout);
// Verify Read and Write on both streams
byte[] buffer = new byte[1];
await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1);
Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1));
Assert.Equal('a', (char)buffer[0]);
await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1);
Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1));
Assert.Equal('b', (char)buffer[0]);
}
}
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Ctor_SocketBool_CanReadAndWrite(bool ownsSocket)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets
{
Exception e = await Record.ExceptionAsync(async () =>
{
using (var serverStream = new NetworkStream(server, ownsSocket))
using (var clientStream = new NetworkStream(client, ownsSocket))
{
Assert.True(serverStream.CanWrite && serverStream.CanRead);
Assert.True(clientStream.CanWrite && clientStream.CanRead);
Assert.False(serverStream.CanSeek && clientStream.CanSeek);
Assert.True(serverStream.CanTimeout && clientStream.CanTimeout);
// Verify Read and Write on both streams
byte[] buffer = new byte[1];
await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1);
Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1));
Assert.Equal('a', (char)buffer[0]);
await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1);
Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1));
Assert.Equal('b', (char)buffer[0]);
}
});
if (i == 0)
{
Assert.Null(e);
}
else if (ownsSocket)
{
Assert.IsType<IOException>(e);
}
else
{
Assert.Null(e);
}
}
}
}
}
[Fact]
public async Task Ctor_SocketFileAccess_CanReadAndWrite()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets
{
using (var serverStream = new NetworkStream(server, FileAccess.Write))
using (var clientStream = new NetworkStream(client, FileAccess.Read))
{
Assert.True(serverStream.CanWrite && !serverStream.CanRead);
Assert.True(!clientStream.CanWrite && clientStream.CanRead);
Assert.False(serverStream.CanSeek && clientStream.CanSeek);
Assert.True(serverStream.CanTimeout && clientStream.CanTimeout);
// Verify Read and Write on both streams
byte[] buffer = new byte[1];
await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1);
Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1));
Assert.Equal('a', (char)buffer[0]);
Assert.Throws<InvalidOperationException>(() => { serverStream.BeginRead(buffer, 0, 1, null, null); });
Assert.Throws<InvalidOperationException>(() => { clientStream.BeginWrite(buffer, 0, 1, null, null); });
Assert.Throws<InvalidOperationException>(() => { serverStream.ReadAsync(buffer, 0, 1); });
Assert.Throws<InvalidOperationException>(() => { clientStream.WriteAsync(buffer, 0, 1); });
}
}
}
}
}
[Fact]
public async Task SocketProperty_SameAsProvidedSocket()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (DerivedNetworkStream serverStream = new DerivedNetworkStream(server))
{
Assert.Same(server, serverStream.Socket);
}
}
}
[OuterLoop("Spins waiting for DataAvailable")]
[Fact]
public async Task DataAvailable_ReturnsFalseOrTrueAppropriately()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
Assert.False(server.DataAvailable && client.DataAvailable);
await server.WriteAsync(new byte[1], 0, 1);
Assert.False(server.DataAvailable);
Assert.True(SpinWait.SpinUntil(() => client.DataAvailable, 10000), "DataAvailable did not return true in the allotted time");
});
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task DisposedClosed_MembersThrowObjectDisposedException(bool close)
{
await RunWithConnectedNetworkStreamsAsync((server, _) =>
{
if (close) server.Close();
else server.Dispose();
Assert.Throws<ObjectDisposedException>(() => server.DataAvailable);
Assert.Throws<ObjectDisposedException>(() => server.Read(new byte[1], 0, 1));
Assert.Throws<ObjectDisposedException>(() => server.Write(new byte[1], 0, 1));
Assert.Throws<ObjectDisposedException>(() => server.BeginRead(new byte[1], 0, 1, null, null));
Assert.Throws<ObjectDisposedException>(() => server.BeginWrite(new byte[1], 0, 1, null, null));
Assert.Throws<ObjectDisposedException>(() => server.EndRead(null));
Assert.Throws<ObjectDisposedException>(() => server.EndWrite(null));
Assert.Throws<ObjectDisposedException>(() => { server.ReadAsync(new byte[1], 0, 1); });
Assert.Throws<ObjectDisposedException>(() => { server.WriteAsync(new byte[1], 0, 1); });
Assert.Throws<ObjectDisposedException>(() => { server.CopyToAsync(new MemoryStream()); });
return Task.CompletedTask;
});
}
[Fact]
public async Task DisposeSocketDirectly_ReadWriteThrowIOException()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket serverSocket = await acceptTask)
using (DerivedNetworkStream server = new DerivedNetworkStream(serverSocket))
{
serverSocket.Dispose();
Assert.Throws<IOException>(() => server.Read(new byte[1], 0, 1));
Assert.Throws<IOException>(() => server.Write(new byte[1], 0, 1));
Assert.Throws<IOException>(() => server.BeginRead(new byte[1], 0, 1, null, null));
Assert.Throws<IOException>(() => server.BeginWrite(new byte[1], 0, 1, null, null));
Assert.Throws<IOException>(() => { server.ReadAsync(new byte[1], 0, 1); });
Assert.Throws<IOException>(() => { server.WriteAsync(new byte[1], 0, 1); });
}
}
}
[Fact]
public async Task InvalidIAsyncResult_EndReadWriteThrows()
{
await RunWithConnectedNetworkStreamsAsync((server, _) =>
{
Assert.Throws<IOException>(() => server.EndRead(Task.CompletedTask));
Assert.Throws<IOException>(() => server.EndWrite(Task.CompletedTask));
return Task.CompletedTask;
});
}
[Fact]
public async Task Close_InvalidArgument_Throws()
{
await RunWithConnectedNetworkStreamsAsync((server, _) =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => server.Close(-2));
server.Close(-1);
server.Close(0);
return Task.CompletedTask;
});
}
[Fact]
public async Task ReadWrite_InvalidArguments_Throws()
{
await RunWithConnectedNetworkStreamsAsync((server, _) =>
{
Assert.Throws<ArgumentNullException>(() => server.Read(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], 2, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], 0, 2));
Assert.Throws<ArgumentNullException>(() => server.BeginRead(null, 0, 0, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], -1, 0, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], 2, 0, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], 0, -1, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], 0, 2, null, null));
Assert.Throws<ArgumentNullException>(() => { server.ReadAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], 2, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], 0, -1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], 0, 2); });
Assert.Throws<ArgumentNullException>(() => server.Write(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], 2, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], 0, 2));
Assert.Throws<ArgumentNullException>(() => server.BeginWrite(null, 0, 0, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], -1, 0, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], 2, 0, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], 0, -1, null, null));
Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], 0, 2, null, null));
Assert.Throws<ArgumentNullException>(() => { server.WriteAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], 2, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], 0, -1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], 0, 2); });
Assert.Throws<ArgumentNullException>(() => server.EndRead(null));
Assert.Throws<ArgumentNullException>(() => server.EndWrite(null));
return Task.CompletedTask;
});
}
[Fact]
public async Task NotSeekable_OperationsThrowExceptions()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
Assert.False(server.CanSeek && client.CanSeek);
Assert.Throws<NotSupportedException>(() => server.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => server.Length);
Assert.Throws<NotSupportedException>(() => server.SetLength(1024));
Assert.Throws<NotSupportedException>(() => server.Position);
Assert.Throws<NotSupportedException>(() => server.Position = 0);
return Task.CompletedTask;
});
}
[Fact]
public async Task ReadableWriteableProperties_Roundtrip()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = listener.AcceptAsync();
await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
using (DerivedNetworkStream serverStream = new DerivedNetworkStream(server))
{
Assert.True(serverStream.Readable && serverStream.Writeable);
serverStream.Readable = false;
Assert.False(serverStream.Readable);
Assert.False(serverStream.CanRead);
Assert.Throws<InvalidOperationException>(() => serverStream.Read(new byte[1], 0, 1));
serverStream.Readable = true;
Assert.True(serverStream.Readable);
Assert.True(serverStream.CanRead);
await client.SendAsync(new ArraySegment<byte>(new byte[1], 0, 1), SocketFlags.None);
Assert.Equal(1, await serverStream.ReadAsync(new byte[1], 0, 1));
serverStream.Writeable = false;
Assert.False(serverStream.Writeable);
Assert.False(serverStream.CanWrite);
Assert.Throws<InvalidOperationException>(() => serverStream.Write(new byte[1], 0, 1));
serverStream.Writeable = true;
Assert.True(serverStream.Writeable);
Assert.True(serverStream.CanWrite);
await serverStream.WriteAsync(new byte[1], 0, 1);
Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(new byte[1], 0, 1), SocketFlags.None));
}
}
}
[Fact]
public async Task ReadWrite_Success()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
var clientData = new byte[] { 42 };
client.Write(clientData, 0, clientData.Length);
var serverData = new byte[clientData.Length];
Assert.Equal(serverData.Length, server.Read(serverData, 0, serverData.Length));
Assert.Equal(clientData, serverData);
client.Flush(); // nop
return Task.CompletedTask;
});
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(NonCanceledTokens))]
public async Task ReadWriteAsync_NonCanceled_Success(CancellationToken nonCanceledToken)
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var clientData = new byte[] { 42 };
await client.WriteAsync(clientData, 0, clientData.Length, nonCanceledToken);
var serverData = new byte[clientData.Length];
Assert.Equal(serverData.Length, await server.ReadAsync(serverData, 0, serverData.Length, nonCanceledToken));
Assert.Equal(clientData, serverData);
Assert.Equal(TaskStatus.RanToCompletion, client.FlushAsync().Status); // nop
});
}
[Fact]
public async Task BeginEndReadWrite_Sync_Success()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
var clientData = new byte[] { 42 };
client.EndWrite(client.BeginWrite(clientData, 0, clientData.Length, null, null));
var serverData = new byte[clientData.Length];
Assert.Equal(serverData.Length, server.EndRead(server.BeginRead(serverData, 0, serverData.Length, null, null)));
Assert.Equal(clientData, serverData);
return Task.CompletedTask;
});
}
[Fact]
public async Task BeginEndReadWrite_Async_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var clientData = new byte[] { 42 };
var serverData = new byte[clientData.Length];
var tcs = new TaskCompletionSource<bool>();
client.BeginWrite(clientData, 0, clientData.Length, writeIar =>
{
try
{
client.EndWrite(writeIar);
server.BeginRead(serverData, 0, serverData.Length, readIar =>
{
try
{
Assert.Equal(serverData.Length, server.EndRead(readIar));
tcs.SetResult(true);
}
catch (Exception e2) { tcs.SetException(e2); }
}, null);
}
catch (Exception e1) { tcs.SetException(e1); }
}, null);
await tcs.Task;
Assert.Equal(clientData, serverData);
});
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task ReadWriteAsync_Canceled_ThrowsOperationCanceledException()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var canceledToken = new CancellationToken(canceled: true);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.WriteAsync(new byte[1], 0, 1, canceledToken));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => server.ReadAsync(new byte[1], 0, 1, canceledToken));
});
}
public static object[][] NonCanceledTokens = new object[][]
{
new object[] { CancellationToken.None }, // CanBeCanceled == false
new object[] { new CancellationTokenSource().Token } // CanBeCanceled == true
};
[OuterLoop("Timeouts")]
[Fact]
public async Task ReadTimeout_Expires_ThrowsSocketException()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
Assert.Equal(-1, server.ReadTimeout);
server.ReadTimeout = 1;
Assert.ThrowsAny<IOException>(() => server.Read(new byte[1], 0, 1));
return Task.CompletedTask;
});
}
[Theory]
[InlineData(0)]
[InlineData(-2)]
public async Task Timeout_InvalidData_ThrowsArgumentException(int invalidTimeout)
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => server.ReadTimeout = invalidTimeout);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => server.WriteTimeout = invalidTimeout);
return Task.CompletedTask;
});
}
[Fact]
public async Task Timeout_ValidData_Roundtrips()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
Assert.Equal(-1, server.ReadTimeout);
Assert.Equal(-1, server.WriteTimeout);
server.ReadTimeout = 100;
Assert.InRange(server.ReadTimeout, 100, int.MaxValue);
server.ReadTimeout = 100; // same value again
Assert.InRange(server.ReadTimeout, 100, int.MaxValue);
server.ReadTimeout = -1;
Assert.Equal(-1, server.ReadTimeout);
server.WriteTimeout = 100;
Assert.InRange(server.WriteTimeout, 100, int.MaxValue);
server.WriteTimeout = 100; // same value again
Assert.InRange(server.WriteTimeout, 100, int.MaxValue);
server.WriteTimeout = -1;
Assert.Equal(-1, server.WriteTimeout);
return Task.CompletedTask;
});
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1024)]
[InlineData(4096)]
[InlineData(4095)]
[InlineData(1024*1024)]
public async Task CopyToAsync_AllDataCopied(int byteCount)
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var results = new MemoryStream();
byte[] dataToCopy = new byte[byteCount];
new Random().NextBytes(dataToCopy);
Task copyTask = client.CopyToAsync(results);
await server.WriteAsync(dataToCopy, 0, dataToCopy.Length);
server.Dispose();
await copyTask;
Assert.Equal(dataToCopy, results.ToArray());
});
}
[Fact]
public async Task CopyToAsync_InvalidArguments_Throws()
{
await RunWithConnectedNetworkStreamsAsync((stream, _) =>
{
// Null destination
AssertExtensions.Throws<ArgumentNullException>("destination", () => { stream.CopyToAsync(null); });
// Buffer size out-of-range
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { stream.CopyToAsync(new MemoryStream(), 0); });
AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { stream.CopyToAsync(new MemoryStream(), -1, CancellationToken.None); });
// Copying to non-writable stream
Assert.Throws<NotSupportedException>(() => { stream.CopyToAsync(new MemoryStream(new byte[0], writable: false)); });
// Copying to a disposed stream
Assert.Throws<ObjectDisposedException>(() =>
{
var disposedTarget = new MemoryStream();
disposedTarget.Dispose();
stream.CopyToAsync(disposedTarget);
});
// Already canceled
Assert.Equal(TaskStatus.Canceled, stream.CopyToAsync(new MemoryStream(new byte[1]), 1, new CancellationToken(canceled: true)).Status);
return Task.CompletedTask;
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Optimized .NET Core CopyToAsync doesn't use Begin/EndRead, skipping code that throws ObjectDisposedException on netfx")]
[Fact]
public async Task CopyToAsync_DisposedSourceStream_ThrowsOnWindows_NoThrowOnUnix()
{
await RunWithConnectedNetworkStreamsAsync(async (stream, _) =>
{
// Copying while disposing the stream
Task copyTask = stream.CopyToAsync(new MemoryStream());
stream.Dispose();
Exception e = await Record.ExceptionAsync(() => copyTask);
// Difference in shutdown/close behavior between Windows and Unix.
// On Windows, the outstanding receive is completed as aborted when the
// socket is closed. On Unix, it's completed as successful once or after
// the shutdown is issued, but depending on timing, if it's then closed
// before that takes effect, it may also complete as aborted.
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
Assert.True(
(isWindows && e is IOException) ||
(!isWindows && (e == null || e is IOException)),
$"Got unexpected exception: {e?.ToString() ?? "(null)"}");
// Copying after disposing the stream
Assert.Throws<ObjectDisposedException>(() => { stream.CopyToAsync(new MemoryStream()); });
});
}
[Fact]
public async Task CopyToAsync_NonReadableSourceStream_Throws()
{
await RunWithConnectedNetworkStreamsAsync((stream, _) =>
{
// Copying from non-readable stream
Assert.Throws<NotSupportedException>(() => { stream.CopyToAsync(new MemoryStream()); });
return Task.CompletedTask;
}, serverAccess:FileAccess.Write);
}
/// <summary>
/// Creates a pair of connected NetworkStreams and invokes the provided <paramref name="func"/>
/// with them as arguments.
/// </summary>
private static async Task RunWithConnectedNetworkStreamsAsync(Func<NetworkStream, NetworkStream, Task> func,
FileAccess serverAccess = FileAccess.ReadWrite, FileAccess clientAccess = FileAccess.ReadWrite)
{
var listener = new TcpListener(IPAddress.Loopback, 0);
try
{
listener.Start(1);
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new TcpClient(clientEndpoint.AddressFamily))
{
Task<TcpClient> remoteTask = listener.AcceptTcpClientAsync();
Task clientConnectTask = client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
await Task.WhenAll(remoteTask, clientConnectTask);
using (TcpClient remote = remoteTask.Result)
using (NetworkStream serverStream = new NetworkStream(remote.Client, serverAccess, ownsSocket:true))
using (NetworkStream clientStream = new NetworkStream(client.Client, clientAccess, ownsSocket: true))
{
await func(serverStream, clientStream);
}
}
}
finally
{
listener.Stop();
}
}
private sealed class DerivedNetworkStream : NetworkStream
{
public DerivedNetworkStream(Socket socket) : base(socket) { }
public new Socket Socket => base.Socket;
public new bool Readable
{
get { return base.Readable; }
set { base.Readable = value; }
}
public new bool Writeable
{
get { return base.Writeable; }
set { base.Writeable = value; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MusicSystem.Services.Areas.HelpPage.ModelDescriptions;
using MusicSystem.Services.Areas.HelpPage.Models;
namespace MusicSystem.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 media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <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)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction : CodeAction
{
protected readonly bool Explicitly;
protected readonly bool Abstractly;
protected readonly ISymbol ThroughMember;
protected readonly Document Document;
protected readonly State State;
protected readonly AbstractImplementInterfaceService Service;
private readonly string _equivalenceKey;
internal ImplementInterfaceCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state,
bool explicitly,
bool abstractly,
ISymbol throughMember)
{
this.Service = service;
this.Document = document;
this.State = state;
this.Abstractly = abstractly;
this.Explicitly = explicitly;
this.ThroughMember = throughMember;
_equivalenceKey = ComputeEquivalenceKey(state, explicitly, abstractly, throughMember, this.GetType().FullName);
}
public static ImplementInterfaceCodeAction CreateImplementAbstractlyCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: true, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementExplicitlyCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: true, abstractly: false, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementThroughMemberCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state,
ISymbol throughMember)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: throughMember);
}
public override string Title
{
get
{
if (Explicitly)
{
return FeaturesResources.Implement_interface_explicitly;
}
else if (Abstractly)
{
return FeaturesResources.Implement_interface_abstractly;
}
else if (ThroughMember != null)
{
return string.Format(FeaturesResources.Implement_interface_through_0, GetDescription(ThroughMember));
}
else
{
return FeaturesResources.Implement_interface;
}
}
}
private static string ComputeEquivalenceKey(
State state,
bool explicitly,
bool abstractly,
ISymbol throughMember,
string codeActionTypeName)
{
var interfaceType = state.InterfaceTypes.First();
var typeName = interfaceType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var assemblyName = interfaceType.ContainingAssembly.Name;
return GetCodeActionEquivalenceKey(assemblyName, typeName, explicitly, abstractly, throughMember, codeActionTypeName);
}
// internal for testing purposes.
internal static string GetCodeActionEquivalenceKey(
string interfaceTypeAssemblyName,
string interfaceTypeFullyQualifiedName,
bool explicitly,
bool abstractly,
ISymbol throughMember,
string codeActionTypeName)
{
if (throughMember != null)
{
return null;
}
return explicitly.ToString() + ";" +
abstractly.ToString() + ";" +
interfaceTypeAssemblyName + ";" +
interfaceTypeFullyQualifiedName + ";" +
codeActionTypeName;
}
public override string EquivalenceKey
{
get
{
return _equivalenceKey;
}
}
private static string GetDescription(ISymbol throughMember)
{
return throughMember.TypeSwitch(
(IFieldSymbol field) => field.Name,
(IPropertySymbol property) => property.Name,
_ => Contract.FailWithReturn<string>());
}
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
return GetUpdatedDocumentAsync(cancellationToken);
}
public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToken)
{
var unimplementedMembers = Explicitly ? State.UnimplementedExplicitMembers : State.UnimplementedMembers;
return GetUpdatedDocumentAsync(Document, unimplementedMembers, State.ClassOrStructType, State.ClassOrStructDecl, cancellationToken);
}
public virtual async Task<Document> GetUpdatedDocumentAsync(
Document document,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
INamedTypeSymbol classOrStructType,
SyntaxNode classOrStructDecl,
CancellationToken cancellationToken)
{
var result = document;
var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var memberDefinitions = GenerateMembers(
compilation,
unimplementedMembers,
cancellationToken);
result = await CodeGenerator.AddMemberDeclarationsAsync(
result.Project.Solution, classOrStructType, memberDefinitions,
new CodeGenerationOptions(contextLocation: classOrStructDecl.GetLocation()),
cancellationToken).ConfigureAwait(false);
return result;
}
private IList<ISymbol> GenerateMembers(
Compilation compilation,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
CancellationToken cancellationToken)
{
// As we go along generating members we may end up with conflicts. For example, say
// you have "interface IFoo { string Bar { get; } }" and "interface IQuux { int Bar
// { get; } }" and we need to implement both 'Bar' methods. The second will have to
// be explicitly implemented as it will conflict with the first. So we need to keep
// track of what we've actually implemented so that we can check further interface
// members against both the actual type and that list.
//
// Similarly, if you have two interfaces with the same member, then we don't want to
// implement that member twice.
//
// Note: if we implement a method explicitly then we do *not* add it to this list.
// That's because later members won't conflict with it even if they have the same
// signature otherwise. i.e. if we chose to implement IFoo.Bar explicitly, then we
// could implement IQuux.Bar implicitly (and vice versa).
var implementedVisibleMembers = new List<ISymbol>();
var implementedMembers = new List<ISymbol>();
foreach (var tuple in unimplementedMembers)
{
var interfaceType = tuple.Item1;
var unimplementedInterfaceMembers = tuple.Item2;
foreach (var unimplementedInterfaceMember in unimplementedInterfaceMembers)
{
var member = GenerateMember(compilation, unimplementedInterfaceMember, implementedVisibleMembers, cancellationToken);
if (member != null)
{
implementedMembers.Add(member);
if (!(member.ExplicitInterfaceImplementations().Any() && Service.HasHiddenExplicitImplementation))
{
implementedVisibleMembers.Add(member);
}
}
}
}
return implementedMembers;
}
private bool IsReservedName(string name)
{
return
IdentifiersMatch(State.ClassOrStructType.Name, name) ||
State.ClassOrStructType.TypeParameters.Any(t => IdentifiersMatch(t.Name, name));
}
private string DetermineMemberName(ISymbol member, List<ISymbol> implementedVisibleMembers)
{
if (HasConflictingMember(member, implementedVisibleMembers))
{
var memberNames = State.ClassOrStructType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(State.ClassOrStructType).Select(m => m.Name);
return NameGenerator.GenerateUniqueName(
string.Format("{0}_{1}", member.ContainingType.Name, member.Name),
n => !memberNames.Contains(n) &&
!implementedVisibleMembers.Any(m => IdentifiersMatch(m.Name, n)) &&
!IsReservedName(n));
}
return member.Name;
}
private ISymbol GenerateMember(
Compilation compilation,
ISymbol member,
List<ISymbol> implementedVisibleMembers,
CancellationToken cancellationToken)
{
// First check if we already generate a member that matches the member we want to
// generate. This can happen in C# when you have interfaces that have the same
// method, and you are implementing implicitly. For example:
//
// interface IFoo { void Foo(); }
//
// interface IBar : IFoo { new void Foo(); }
//
// class C : IBar
//
// In this case we only want to generate 'Foo' once.
if (HasMatchingMember(implementedVisibleMembers, member))
{
return null;
}
var memberName = DetermineMemberName(member, implementedVisibleMembers);
// See if we need to generate an invisible member. If we do, then reset the name
// back to what then member wants it to be.
var generateInvisibleMember = GenerateInvisibleMember(member, memberName);
memberName = generateInvisibleMember ? member.Name : memberName;
var generateAbstractly = !generateInvisibleMember && Abstractly;
// Check if we need to add 'new' to the signature we're adding. We only need to do this
// if we're not generating something explicit and we have a naming conflict with
// something in our base class hierarchy.
var addNew = !generateInvisibleMember && HasNameConflict(member, memberName, State.ClassOrStructType.GetBaseTypes());
// Check if we need to add 'unsafe' to the signature we're generating.
var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>();
var addUnsafe = member.IsUnsafe() && !syntaxFacts.IsUnsafeContext(State.Location);
return GenerateMember(compilation, member, memberName, generateInvisibleMember, generateAbstractly, addNew, addUnsafe, cancellationToken);
}
private bool GenerateInvisibleMember(ISymbol member, string memberName)
{
if (Service.HasHiddenExplicitImplementation)
{
// User asked for an explicit (i.e. invisible) member.
if (Explicitly)
{
return true;
}
// Have to create an invisible member if we have constraints we can't express
// with a visible member.
if (HasUnexpressibleConstraint(member))
{
return true;
}
// If we had a conflict with a member of the same name, then we have to generate
// as an invisible member.
if (member.Name != memberName)
{
return true;
}
}
// Can't generate an invisible member if the language doesn't support it.
return false;
}
private bool HasUnexpressibleConstraint(ISymbol member)
{
// interface IFoo<T> { void Bar<U>() where U : T; }
//
// class A : IFoo<int> { }
//
// In this case we cannot generate an implement method for Bar. That's because we'd
// need to say "where U : int" and that's disallowed by the language. So we must
// generate something explicit here.
if (member.Kind != SymbolKind.Method)
{
return false;
}
var method = member as IMethodSymbol;
return method.TypeParameters.Any(IsUnexpressibleTypeParameter);
}
private static bool IsUnexpressibleTypeParameter(ITypeParameterSymbol typeParameter)
{
var condition1 = typeParameter.ConstraintTypes.Count(t => t.TypeKind == TypeKind.Class) >= 2;
var condition2 = typeParameter.ConstraintTypes.Any(ts => ts.IsUnexpressibleTypeParameterConstraint());
var condition3 = typeParameter.HasReferenceTypeConstraint && typeParameter.ConstraintTypes.Any(ts => ts.IsReferenceType && ts.SpecialType != SpecialType.System_Object);
return condition1 || condition2 || condition3;
}
private ISymbol GenerateMember(
Compilation compilation,
ISymbol member,
string memberName,
bool generateInvisibly,
bool generateAbstractly,
bool addNew,
bool addUnsafe,
CancellationToken cancellationToken)
{
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
var modifiers = new DeclarationModifiers(isAbstract: generateAbstractly, isNew: addNew, isUnsafe: addUnsafe);
var useExplicitInterfaceSymbol = generateInvisibly || !Service.CanImplementImplicitly;
var accessibility = member.Name == memberName || generateAbstractly
? Accessibility.Public
: Accessibility.Private;
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
return GenerateMethod(compilation, method, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
}
else if (member.Kind == SymbolKind.Property)
{
var property = (IPropertySymbol)member;
return GenerateProperty(compilation, property, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
}
else if (member.Kind == SymbolKind.Event)
{
var @event = (IEventSymbol)member;
var accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: Accessibility.NotApplicable,
statements: factory.CreateThrowNotImplementedStatementBlock(compilation));
return CodeGenerationSymbolFactory.CreateEventSymbol(
@event,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? @event : null,
name: memberName,
addMethod: generateInvisibly ? accessor : null,
removeMethod: generateInvisibly ? accessor : null);
}
return null;
}
private SyntaxNode CreateThroughExpression(SyntaxGenerator factory)
{
var through = ThroughMember.IsStatic
? GenerateName(factory, State.ClassOrStructType.IsGenericType)
: factory.ThisExpression();
through = factory.MemberAccessExpression(
through, factory.IdentifierName(ThroughMember.Name));
var throughMemberType = ThroughMember.GetMemberType();
if ((State.InterfaceTypes != null) && (throughMemberType != null))
{
// In the case of 'implement interface through field / property' , we need to know what
// interface we are implementing so that we can insert casts to this interface on every
// usage of the field in the generated code. Without these casts we would end up generating
// code that fails compilation in certain situations.
//
// For example consider the following code.
// class C : IReadOnlyList<int> { int[] field; }
// When applying the 'implement interface through field' code fix in the above example,
// we need to generate the following code to implement the Count property on IReadOnlyList<int>
// class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...}
// as opposed to the following code which will fail to compile (because the array field
// doesn't have a property named .Count) -
// class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...}
//
// The 'InterfaceTypes' property on the state object always contains only one item
// in the case of C# i.e. it will contain exactly the interface we are trying to implement.
// This is also the case most of the time in the case of VB, except in certain error conditions
// (recursive / circular cases) where the span of the squiggle for the corresponding
// diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces
// in the Implements clause. For the purposes of inserting the above cast, we ignore the
// uncommon case and optimize for the common one - in other words, we only apply the cast
// in cases where we can unambiguously figure out which interface we are trying to implement.
var interfaceBeingImplemented = State.InterfaceTypes.SingleOrDefault();
if ((interfaceBeingImplemented != null) && (!throughMemberType.Equals(interfaceBeingImplemented)))
{
through = factory.CastExpression(interfaceBeingImplemented,
through.WithAdditionalAnnotations(Simplifier.Annotation));
var facts = this.Document.GetLanguageService<ISyntaxFactsService>();
through = facts.Parenthesize(through);
}
}
return through.WithAdditionalAnnotations(Simplifier.Annotation);
}
private SyntaxNode GenerateName(SyntaxGenerator factory, bool isGenericType)
{
return isGenericType
? factory.GenericName(State.ClassOrStructType.Name, State.ClassOrStructType.TypeArguments)
: factory.IdentifierName(State.ClassOrStructType.Name);
}
private bool HasNameConflict(
ISymbol member,
string memberName,
IEnumerable<INamedTypeSymbol> baseTypes)
{
// There's a naming conflict if any member in the base types chain is accessible to
// us, has our name. Note: a simple name won't conflict with a generic name (and
// vice versa). A method only conflicts with another method if they have the same
// parameter signature (return type is irrelevant).
return
baseTypes.Any(ts => ts.GetMembers(memberName)
.Where(m => m.IsAccessibleWithin(State.ClassOrStructType))
.Any(m => HasNameConflict(member, memberName, m)));
}
private static bool HasNameConflict(
ISymbol member,
string memberName,
ISymbol baseMember)
{
Contract.Requires(memberName == baseMember.Name);
if (member.Kind == SymbolKind.Method && baseMember.Kind == SymbolKind.Method)
{
// A method only conflicts with another method if they have the same parameter
// signature (return type is irrelevant).
var method1 = (IMethodSymbol)member;
var method2 = (IMethodSymbol)baseMember;
if (method1.MethodKind == MethodKind.Ordinary &&
method2.MethodKind == MethodKind.Ordinary &&
method1.TypeParameters.Length == method2.TypeParameters.Length)
{
return method1.Parameters.Select(p => p.Type)
.SequenceEqual(method2.Parameters.Select(p => p.Type));
}
}
// Any non method members with the same name simple name conflict.
return true;
}
private bool IdentifiersMatch(string identifier1, string identifier2)
{
return this.IsCaseSensitive
? identifier1 == identifier2
: StringComparer.OrdinalIgnoreCase.Equals(identifier1, identifier2);
}
private bool IsCaseSensitive
{
get
{
return this.Document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive;
}
}
private bool HasMatchingMember(List<ISymbol> implementedVisibleMembers, ISymbol member)
{
// If this is a language that doesn't support implicit implementation then no
// implemented members will ever match. For example, if you have:
//
// Interface IFoo : sub Foo() : End Interface
//
// Interface IBar : Inherits IFoo : Shadows Sub Foo() : End Interface
//
// Class C : Implements IBar
//
// We'll first end up generating:
//
// Public Sub Foo() Implements IFoo.Foo
//
// However, that same method won't be viable for IBar.Foo (unlike C#) because it
// explicitly specifies its interface).
if (!Service.CanImplementImplicitly)
{
return false;
}
return implementedVisibleMembers.Any(m => MembersMatch(m, member));
}
private bool MembersMatch(ISymbol member1, ISymbol member2)
{
if (member1.Kind != member2.Kind)
{
return false;
}
if (member1.DeclaredAccessibility != member2.DeclaredAccessibility ||
member1.IsStatic != member2.IsStatic)
{
return false;
}
if (member1.ExplicitInterfaceImplementations().Any() || member2.ExplicitInterfaceImplementations().Any())
{
return false;
}
return SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(
member1, member2, this.IsCaseSensitive);
}
}
}
}
| |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK Github:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Internals.Fibers;
namespace Microsoft.Bot.Builder.Scorables.Internals
{
public interface IBinder
{
bool TryBind(MethodBase method, IResolver resolver, out IBinding binding);
bool TryBind(Delegate lambda, IResolver resolver, out IBinding binding);
bool TryBind<R>(MethodInfo method, IResolver resolver, out IBinding<R> binding);
bool TryBind<R>(Delegate lambda, IResolver resolver, out IBinding<R> binding);
}
public static partial class Extensions
{
private static readonly ConditionalWeakTable<MethodBase, IReadOnlyList<ParameterInfo>> ParametersByMethod =
new ConditionalWeakTable<MethodBase, IReadOnlyList<ParameterInfo>>();
public static IReadOnlyList<ParameterInfo> CachedParameters(this MethodBase method)
{
return ParametersByMethod.GetValue(method, m => m.GetParameters());
}
private static readonly ConditionalWeakTable<MethodBase, IReadOnlyList<Type>> ParameterTypesByMethod =
new ConditionalWeakTable<MethodBase, IReadOnlyList<Type>>();
public static IReadOnlyList<Type> CachedParameterTypes(this MethodBase method)
{
return ParameterTypesByMethod.GetValue(method, m => m.GetParameters().ToList(p => p.ParameterType));
}
}
public sealed class Binder : IBinder
{
public static readonly IBinder Instance = new Binder();
private Binder()
{
}
public static bool TryResolveReturnType<R>(MethodInfo method)
{
var type = method.ReturnType;
if (typeof(R).IsAssignableFrom(type))
{
return true;
}
if (type.IsGenericType)
{
var definition = type.GetGenericTypeDefinition();
if (definition == typeof(Task<>))
{
var arguments = type.GetGenericArguments();
if (typeof(R).IsAssignableFrom(arguments[0]))
{
return true;
}
}
}
return false;
}
public static bool TryResolveInstance(IResolver resolver, MethodBase method, object target, out object instance)
{
if (target != null)
{
var type = target.GetType();
if (method.DeclaringType.IsAssignableFrom(type))
{
instance = target;
return true;
}
}
if (method.IsStatic)
{
instance = null;
return true;
}
return resolver.TryResolve(method.DeclaringType, null, out instance);
}
public static bool TryResolveArgument(IResolver resolver, ParameterInfo parameter, out object argument)
{
var type = parameter.ParameterType;
var entity = parameter.GetCustomAttribute<EntityAttribute>();
if (entity != null)
{
if (resolver.TryResolve(type, entity.Name, out argument))
{
return true;
}
}
if (resolver.TryResolve(type, parameter.Name, out argument))
{
return true;
}
return resolver.TryResolve(type, null, out argument);
}
public static bool TryResolveArguments(IResolver resolver, MethodBase method, out object[] arguments)
{
var parameters = method.CachedParameters();
if (parameters.Count == 0)
{
arguments = Array.Empty<object>();
return true;
}
arguments = null;
for (int index = 0; index < parameters.Count; ++index)
{
var parameter = parameters[index];
object argument;
if (!TryResolveArgument(resolver, parameter, out argument))
{
arguments = null;
return false;
}
if (arguments == null)
{
arguments = new object[parameters.Count];
}
arguments[index] = argument;
}
return arguments != null;
}
public static bool TryBind(MethodBase method, object target, IResolver resolver, out IBinding binding)
{
object instance;
if (!TryResolveInstance(resolver, method, target, out instance))
{
binding = null;
return false;
}
object[] arguments;
if (!TryResolveArguments(resolver, method, out arguments))
{
binding = null;
return false;
}
binding = new Binding(method, instance, arguments);
return true;
}
public static bool TryBind<R>(MethodInfo method, object target, IResolver resolver, out IBinding<R> binding)
{
if (!TryResolveReturnType<R>(method))
{
binding = null;
return false;
}
object instance;
if (!TryResolveInstance(resolver, method, target, out instance))
{
binding = null;
return false;
}
object[] arguments;
if (!TryResolveArguments(resolver, method, out arguments))
{
binding = null;
return false;
}
binding = new Binding<R>(method, instance, arguments);
return true;
}
bool IBinder.TryBind(MethodBase method, IResolver resolver, out IBinding binding)
{
return TryBind(method, null, resolver, out binding);
}
bool IBinder.TryBind(Delegate lambda, IResolver resolver, out IBinding binding)
{
return TryBind(lambda.Method, lambda.Target, resolver, out binding);
}
bool IBinder.TryBind<R>(MethodInfo method, IResolver resolver, out IBinding<R> binding)
{
return TryBind(method, null, resolver, out binding);
}
bool IBinder.TryBind<R>(Delegate lambda, IResolver resolver, out IBinding<R> binding)
{
return TryBind(lambda.Method, lambda.Target, resolver, out binding);
}
}
}
| |
// 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.Net.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public sealed class SocketsHttpHandler : HttpMessageHandler
{
private readonly HttpConnectionSettings _settings = new HttpConnectionSettings();
private HttpMessageHandler _handler;
private bool _disposed;
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(SocketsHttpHandler));
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_handler != null)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
public bool UseCookies
{
get => _settings._useCookies;
set
{
CheckDisposedOrStarted();
_settings._useCookies = value;
}
}
public CookieContainer CookieContainer
{
get => _settings._cookieContainer ?? (_settings._cookieContainer = new CookieContainer());
set
{
CheckDisposedOrStarted();
_settings._cookieContainer = value;
}
}
public DecompressionMethods AutomaticDecompression
{
get => _settings._automaticDecompression;
set
{
CheckDisposedOrStarted();
_settings._automaticDecompression = value;
}
}
public bool UseProxy
{
get => _settings._useProxy;
set
{
CheckDisposedOrStarted();
_settings._useProxy = value;
}
}
public IWebProxy Proxy
{
get => _settings._proxy;
set
{
CheckDisposedOrStarted();
_settings._proxy = value;
}
}
public ICredentials DefaultProxyCredentials
{
get => _settings._defaultProxyCredentials;
set
{
CheckDisposedOrStarted();
_settings._defaultProxyCredentials = value;
}
}
public bool PreAuthenticate
{
get => _settings._preAuthenticate;
set
{
CheckDisposedOrStarted();
_settings._preAuthenticate = value;
}
}
public ICredentials Credentials
{
get => _settings._credentials;
set
{
CheckDisposedOrStarted();
_settings._credentials = value;
}
}
public bool AllowAutoRedirect
{
get => _settings._allowAutoRedirect;
set
{
CheckDisposedOrStarted();
_settings._allowAutoRedirect = value;
}
}
public int MaxAutomaticRedirections
{
get => _settings._maxAutomaticRedirections;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxAutomaticRedirections = value;
}
}
public int MaxConnectionsPerServer
{
get => _settings._maxConnectionsPerServer;
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxConnectionsPerServer = value;
}
}
public int MaxResponseDrainSize
{
get => _settings._maxResponseDrainSize;
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegativeNum);
}
CheckDisposedOrStarted();
_settings._maxResponseDrainSize = value;
}
}
public TimeSpan ResponseDrainTimeout
{
get => _settings._maxResponseDrainTime;
set
{
if ((value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._maxResponseDrainTime = value;
}
}
public int MaxResponseHeadersLength
{
get => _settings._maxResponseHeadersLength;
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_settings._maxResponseHeadersLength = value;
}
}
public SslClientAuthenticationOptions SslOptions
{
get => _settings._sslOptions ?? (_settings._sslOptions = new SslClientAuthenticationOptions());
set
{
CheckDisposedOrStarted();
_settings._sslOptions = value;
}
}
public TimeSpan PooledConnectionLifetime
{
get => _settings._pooledConnectionLifetime;
set
{
if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._pooledConnectionLifetime = value;
}
}
public TimeSpan PooledConnectionIdleTimeout
{
get => _settings._pooledConnectionIdleTimeout;
set
{
if (value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._pooledConnectionIdleTimeout = value;
}
}
public TimeSpan ConnectTimeout
{
get => _settings._connectTimeout;
set
{
if ((value <= TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._connectTimeout = value;
}
}
public TimeSpan Expect100ContinueTimeout
{
get => _settings._expect100ContinueTimeout;
set
{
if ((value < TimeSpan.Zero && value != Timeout.InfiniteTimeSpan) ||
(value.TotalMilliseconds > int.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_settings._expect100ContinueTimeout = value;
}
}
public IDictionary<string, object> Properties =>
_settings._properties ?? (_settings._properties = new Dictionary<string, object>());
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
_handler?.Dispose();
}
base.Dispose(disposing);
}
private HttpMessageHandler SetupHandlerChain()
{
// Clone the settings to get a relatively consistent view that won't change after this point.
// (This isn't entirely complete, as some of the collections it contains aren't currently deeply cloned.)
HttpConnectionSettings settings = _settings.Clone();
HttpConnectionPoolManager poolManager = new HttpConnectionPoolManager(settings);
HttpMessageHandler handler;
if (settings._credentials == null)
{
handler = new HttpConnectionHandler(poolManager);
}
else
{
handler = new HttpAuthenticatedConnectionHandler(poolManager);
}
if (settings._allowAutoRedirect)
{
// Just as with WinHttpHandler and CurlHandler, for security reasons, we do not support authentication on redirects
// if the credential is anything other than a CredentialCache.
// We allow credentials in a CredentialCache since they are specifically tied to URIs.
HttpMessageHandler redirectHandler =
(settings._credentials == null || settings._credentials is CredentialCache) ?
handler :
new HttpConnectionHandler(poolManager); // will not authenticate
handler = new RedirectHandler(settings._maxAutomaticRedirections, handler, redirectHandler);
}
if (settings._automaticDecompression != DecompressionMethods.None)
{
handler = new DecompressionHandler(settings._automaticDecompression, handler);
}
// Ensure a single handler is used for all requests.
if (Interlocked.CompareExchange(ref _handler, handler, null) != null)
{
handler.Dispose();
}
return _handler;
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
CheckDisposed();
HttpMessageHandler handler = _handler ?? SetupHandlerChain();
Exception error = ValidateAndNormalizeRequest(request);
if (error != null)
{
return Task.FromException<HttpResponseMessage>(error);
}
return handler.SendAsync(request, cancellationToken);
}
private Exception ValidateAndNormalizeRequest(HttpRequestMessage request)
{
if (request.Version.Major == 0)
{
return new NotSupportedException(SR.net_http_unsupported_version);
}
// Add headers to define content transfer, if not present
if (request.HasHeaders && request.Headers.TransferEncodingChunked.GetValueOrDefault())
{
if (request.Content == null)
{
return new HttpRequestException(SR.net_http_client_execution_error,
new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content));
}
// Since the user explicitly set TransferEncodingChunked to true, we need to remove
// the Content-Length header if present, as sending both is invalid.
request.Content.Headers.ContentLength = null;
}
else if (request.Content != null && request.Content.Headers.ContentLength == null)
{
// We have content, but neither Transfer-Encoding nor Content-Length is set.
request.Headers.TransferEncodingChunked = true;
}
if (request.Version.Minor == 0 && request.Version.Major == 1 && request.HasHeaders)
{
// HTTP 1.0 does not support chunking
if (request.Headers.TransferEncodingChunked == true)
{
return new NotSupportedException(SR.net_http_unsupported_chunking);
}
// HTTP 1.0 does not support Expect: 100-continue; just disable it.
if (request.Headers.ExpectContinue == true)
{
request.Headers.ExpectContinue = false;
}
}
return null;
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\ExponentialHeightFogComponent.h:47
namespace UnrealEngine
{
[ManageType("ManageExponentialHeightFogComponent")]
public partial class ManageExponentialHeightFogComponent : UExponentialHeightFogComponent, IManageWrapper
{
public ManageExponentialHeightFogComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UExponentialHeightFogComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__UExponentialHeightFogComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__UExponentialHeightFogComponent_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__UExponentialHeightFogComponent_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__UExponentialHeightFogComponent_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__UExponentialHeightFogComponent_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__UExponentialHeightFogComponent_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__UExponentialHeightFogComponent_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__UExponentialHeightFogComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__UExponentialHeightFogComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__UExponentialHeightFogComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__UExponentialHeightFogComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__UExponentialHeightFogComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__UExponentialHeightFogComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__UExponentialHeightFogComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__UExponentialHeightFogComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__UExponentialHeightFogComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__UExponentialHeightFogComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__UExponentialHeightFogComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__UExponentialHeightFogComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__UExponentialHeightFogComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__UExponentialHeightFogComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__UExponentialHeightFogComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__UExponentialHeightFogComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__UExponentialHeightFogComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__UExponentialHeightFogComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__UExponentialHeightFogComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__UExponentialHeightFogComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__UExponentialHeightFogComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__UExponentialHeightFogComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__UExponentialHeightFogComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__UExponentialHeightFogComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__UExponentialHeightFogComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UExponentialHeightFogComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UExponentialHeightFogComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UExponentialHeightFogComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UExponentialHeightFogComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UExponentialHeightFogComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UExponentialHeightFogComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UExponentialHeightFogComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UExponentialHeightFogComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UExponentialHeightFogComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UExponentialHeightFogComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UExponentialHeightFogComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UExponentialHeightFogComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UExponentialHeightFogComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UExponentialHeightFogComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UExponentialHeightFogComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageExponentialHeightFogComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageExponentialHeightFogComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageExponentialHeightFogComponent>(PtrDesc);
}
}
}
| |
// Copyright (c) 2015-present, LeanCloud, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using LeanCloud.Storage.Internal;
using LeanCloud.Core.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace LeanCloud {
/// <summary>
/// Provides extension methods for <see cref="ParseQuery{T}"/> to support
/// Linq-style queries.
/// </summary>
public static class AVQueryExtensions {
private static readonly MethodInfo getMethod;
private static readonly MethodInfo stringContains;
private static readonly MethodInfo stringStartsWith;
private static readonly MethodInfo stringEndsWith;
private static readonly MethodInfo containsMethod;
private static readonly MethodInfo notContainsMethod;
private static readonly MethodInfo containsKeyMethod;
private static readonly MethodInfo notContainsKeyMethod;
private static readonly Dictionary<MethodInfo, MethodInfo> functionMappings;
static AVQueryExtensions() {
getMethod = GetMethod<AVObject>(obj => obj.Get<int>(null)).GetGenericMethodDefinition();
stringContains = GetMethod<string>(str => str.Contains(null));
stringStartsWith = GetMethod<string>(str => str.StartsWith(null));
stringEndsWith = GetMethod<string>(str => str.EndsWith(null));
functionMappings = new Dictionary<MethodInfo, MethodInfo> {
{
stringContains,
GetMethod<AVQuery<AVObject>>(q => q.WhereContains(null, null))
},
{
stringStartsWith,
GetMethod<AVQuery<AVObject>>(q => q.WhereStartsWith(null, null))
},
{
stringEndsWith,
GetMethod<AVQuery<AVObject>>(q => q.WhereEndsWith(null,null))
},
};
containsMethod = GetMethod<object>(
o => AVQueryExtensions.ContainsStub<object>(null, null)).GetGenericMethodDefinition();
notContainsMethod = GetMethod<object>(
o => AVQueryExtensions.NotContainsStub<object>(null, null))
.GetGenericMethodDefinition();
containsKeyMethod = GetMethod<object>(o => AVQueryExtensions.ContainsKeyStub(null, null));
notContainsKeyMethod = GetMethod<object>(
o => AVQueryExtensions.NotContainsKeyStub(null, null));
}
/// <summary>
/// Gets a MethodInfo for a top-level method call.
/// </summary>
private static MethodInfo GetMethod<T>(Expression<Action<T>> expression) {
return (expression.Body as MethodCallExpression).Method;
}
/// <summary>
/// When a query is normalized, this is a placeholder to indicate we should
/// add a WhereContainedIn() clause.
/// </summary>
private static bool ContainsStub<T>(object collection, T value) {
throw new NotImplementedException(
"Exists only for expression translation as a placeholder.");
}
/// <summary>
/// When a query is normalized, this is a placeholder to indicate we should
/// add a WhereNotContainedIn() clause.
/// </summary>
private static bool NotContainsStub<T>(object collection, T value) {
throw new NotImplementedException(
"Exists only for expression translation as a placeholder.");
}
/// <summary>
/// When a query is normalized, this is a placeholder to indicate that we should
/// add a WhereExists() clause.
/// </summary>
private static bool ContainsKeyStub(AVObject obj, string key) {
throw new NotImplementedException(
"Exists only for expression translation as a placeholder.");
}
/// <summary>
/// When a query is normalized, this is a placeholder to indicate that we should
/// add a WhereDoesNotExist() clause.
/// </summary>
private static bool NotContainsKeyStub(AVObject obj, string key) {
throw new NotImplementedException(
"Exists only for expression translation as a placeholder.");
}
/// <summary>
/// Evaluates an expression and throws if the expression has components that can't be
/// evaluated (e.g. uses the parameter that's only represented by an object on the server).
/// </summary>
private static object GetValue(Expression exp) {
try {
return Expression.Lambda(
typeof(Func<>).MakeGenericType(exp.Type), exp).Compile().DynamicInvoke();
} catch (Exception e) {
throw new InvalidOperationException("Unable to evaluate expression: " + exp, e);
}
}
/// <summary>
/// Checks whether the MethodCallExpression is a call to AVObject.Get(),
/// which is the call we normalize all indexing into the AVObject to.
/// </summary>
private static bool IsParseObjectGet(MethodCallExpression node) {
if (node == null || node.Object == null) {
return false;
}
if (!typeof(AVObject).GetTypeInfo().IsAssignableFrom(node.Object.Type.GetTypeInfo())) {
return false;
}
return node.Method.IsGenericMethod && node.Method.GetGenericMethodDefinition() == getMethod;
}
/// <summary>
/// Visits an Expression, converting AVObject.Get/AVObject[]/AVObject.Property,
/// and nested indices into a single call to AVObject.Get() with a "field path" like
/// "foo.bar.baz"
/// </summary>
private class ObjectNormalizer : ExpressionVisitor {
protected override Expression VisitIndex(IndexExpression node) {
var visitedObject = Visit(node.Object);
var indexer = visitedObject as MethodCallExpression;
if (IsParseObjectGet(indexer)) {
var indexValue = GetValue(node.Arguments[0]) as string;
if (indexValue == null) {
throw new InvalidOperationException("Index must be a string");
}
var newPath = GetValue(indexer.Arguments[0]) + "." + indexValue;
return Expression.Call(indexer.Object,
getMethod.MakeGenericMethod(node.Type),
Expression.Constant(newPath, typeof(string)));
}
return base.VisitIndex(node);
}
/// <summary>
/// Check for a ParseFieldName attribute and use that as the path component, turning
/// properties like foo.ObjectId into foo.Get("objectId")
/// </summary>
protected override Expression VisitMember(MemberExpression node) {
var fieldName = node.Member.GetCustomAttribute<AVFieldNameAttribute>();
if (fieldName != null &&
typeof(AVObject).GetTypeInfo().IsAssignableFrom(node.Expression.Type.GetTypeInfo())) {
var newPath = fieldName.FieldName;
return Expression.Call(node.Expression,
getMethod.MakeGenericMethod(node.Type),
Expression.Constant(newPath, typeof(string)));
}
return base.VisitMember(node);
}
/// <summary>
/// If a AVObject.Get() call has been cast, just change the generic parameter.
/// </summary>
protected override Expression VisitUnary(UnaryExpression node) {
var methodCall = Visit(node.Operand) as MethodCallExpression;
if ((node.NodeType == ExpressionType.Convert ||
node.NodeType == ExpressionType.ConvertChecked) &&
IsParseObjectGet(methodCall)) {
return Expression.Call(methodCall.Object,
getMethod.MakeGenericMethod(node.Type),
methodCall.Arguments);
}
return base.VisitUnary(node);
}
protected override Expression VisitMethodCall(MethodCallExpression node) {
// Turn parseObject["foo"] into parseObject.Get<object>("foo")
if (node.Method.Name == "get_Item" && node.Object is ParameterExpression) {
var indexPath = GetValue(node.Arguments[0]) as string;
return Expression.Call(node.Object,
getMethod.MakeGenericMethod(typeof(object)),
Expression.Constant(indexPath, typeof(string)));
}
// Turn parseObject.Get<object>("foo")["bar"] into parseObject.Get<object>("foo.bar")
if (node.Method.Name == "get_Item" || IsParseObjectGet(node)) {
var visitedObject = Visit(node.Object);
var indexer = visitedObject as MethodCallExpression;
if (IsParseObjectGet(indexer)) {
var indexValue = GetValue(node.Arguments[0]) as string;
if (indexValue == null) {
throw new InvalidOperationException("Index must be a string");
}
var newPath = GetValue(indexer.Arguments[0]) + "." + indexValue;
return Expression.Call(indexer.Object,
getMethod.MakeGenericMethod(node.Type),
Expression.Constant(newPath, typeof(string)));
}
}
return base.VisitMethodCall(node);
}
}
/// <summary>
/// Normalizes Where expressions.
/// </summary>
private class WhereNormalizer : ExpressionVisitor {
/// <summary>
/// Normalizes binary operators. <, >, <=, >= !=, and ==
/// This puts the AVObject.Get() on the left side of the operation
/// (reversing it if necessary), and normalizes the AVObject.Get()
/// </summary>
protected override Expression VisitBinary(BinaryExpression node) {
var leftTransformed = new ObjectNormalizer().Visit(node.Left) as MethodCallExpression;
var rightTransformed = new ObjectNormalizer().Visit(node.Right) as MethodCallExpression;
MethodCallExpression objectExpression;
Expression filterExpression;
bool inverted;
if (leftTransformed != null) {
objectExpression = leftTransformed;
filterExpression = node.Right;
inverted = false;
} else {
objectExpression = rightTransformed;
filterExpression = node.Left;
inverted = true;
}
try {
switch (node.NodeType) {
case ExpressionType.GreaterThan:
if (inverted) {
return Expression.LessThan(objectExpression, filterExpression);
} else {
return Expression.GreaterThan(objectExpression, filterExpression);
}
case ExpressionType.GreaterThanOrEqual:
if (inverted) {
return Expression.LessThanOrEqual(objectExpression, filterExpression);
} else {
return Expression.GreaterThanOrEqual(objectExpression, filterExpression);
}
case ExpressionType.LessThan:
if (inverted) {
return Expression.GreaterThan(objectExpression, filterExpression);
} else {
return Expression.LessThan(objectExpression, filterExpression);
}
case ExpressionType.LessThanOrEqual:
if (inverted) {
return Expression.GreaterThanOrEqual(objectExpression, filterExpression);
} else {
return Expression.LessThanOrEqual(objectExpression, filterExpression);
}
case ExpressionType.Equal:
return Expression.Equal(objectExpression, filterExpression);
case ExpressionType.NotEqual:
return Expression.NotEqual(objectExpression, filterExpression);
}
} catch (ArgumentException) {
throw new InvalidOperationException("Operation not supported: " + node);
}
return base.VisitBinary(node);
}
/// <summary>
/// If a ! operator is used, this removes the ! and instead calls the equivalent
/// function (so e.g. == becomes !=, < becomes >=, Contains becomes NotContains)
/// </summary>
protected override Expression VisitUnary(UnaryExpression node) {
// Normalizes inversion
if (node.NodeType == ExpressionType.Not) {
var visitedOperand = Visit(node.Operand);
var binaryOperand = visitedOperand as BinaryExpression;
if (binaryOperand != null) {
switch (binaryOperand.NodeType) {
case ExpressionType.GreaterThan:
return Expression.LessThanOrEqual(binaryOperand.Left, binaryOperand.Right);
case ExpressionType.GreaterThanOrEqual:
return Expression.LessThan(binaryOperand.Left, binaryOperand.Right);
case ExpressionType.LessThan:
return Expression.GreaterThanOrEqual(binaryOperand.Left, binaryOperand.Right);
case ExpressionType.LessThanOrEqual:
return Expression.GreaterThan(binaryOperand.Left, binaryOperand.Right);
case ExpressionType.Equal:
return Expression.NotEqual(binaryOperand.Left, binaryOperand.Right);
case ExpressionType.NotEqual:
return Expression.Equal(binaryOperand.Left, binaryOperand.Right);
}
}
var methodCallOperand = visitedOperand as MethodCallExpression;
if (methodCallOperand != null) {
if (methodCallOperand.Method.IsGenericMethod) {
if (methodCallOperand.Method.GetGenericMethodDefinition() == containsMethod) {
var genericNotContains = notContainsMethod.MakeGenericMethod(
methodCallOperand.Method.GetGenericArguments());
return Expression.Call(genericNotContains, methodCallOperand.Arguments.ToArray());
}
if (methodCallOperand.Method.GetGenericMethodDefinition() == notContainsMethod) {
var genericContains = containsMethod.MakeGenericMethod(
methodCallOperand.Method.GetGenericArguments());
return Expression.Call(genericContains, methodCallOperand.Arguments.ToArray());
}
}
if (methodCallOperand.Method == containsKeyMethod) {
return Expression.Call(notContainsKeyMethod, methodCallOperand.Arguments.ToArray());
}
if (methodCallOperand.Method == notContainsKeyMethod) {
return Expression.Call(containsKeyMethod, methodCallOperand.Arguments.ToArray());
}
}
}
return base.VisitUnary(node);
}
/// <summary>
/// Normalizes .Equals into == and Contains() into the appropriate stub.
/// </summary>
protected override Expression VisitMethodCall(MethodCallExpression node) {
// Convert .Equals() into ==
if (node.Method.Name == "Equals" &&
node.Method.ReturnType == typeof(bool) &&
node.Method.GetParameters().Length == 1) {
var obj = new ObjectNormalizer().Visit(node.Object) as MethodCallExpression;
var parameter = new ObjectNormalizer().Visit(node.Arguments[0]) as MethodCallExpression;
if ((IsParseObjectGet(obj) && (obj.Object is ParameterExpression)) ||
(IsParseObjectGet(parameter) && (parameter.Object is ParameterExpression))) {
return Expression.Equal(node.Object, node.Arguments[0]);
}
}
// Convert the .Contains() into a ContainsStub
if (node.Method != stringContains &&
node.Method.Name == "Contains" &&
node.Method.ReturnType == typeof(bool) &&
node.Method.GetParameters().Length <= 2) {
var collection = node.Method.GetParameters().Length == 1 ?
node.Object :
node.Arguments[0];
var parameterIndex = node.Method.GetParameters().Length - 1;
var parameter = new ObjectNormalizer().Visit(node.Arguments[parameterIndex])
as MethodCallExpression;
if (IsParseObjectGet(parameter) && (parameter.Object is ParameterExpression)) {
var genericContains = containsMethod.MakeGenericMethod(parameter.Type);
return Expression.Call(genericContains, collection, parameter);
}
var target = new ObjectNormalizer().Visit(collection) as MethodCallExpression;
var element = node.Arguments[parameterIndex];
if (IsParseObjectGet(target) && (target.Object is ParameterExpression)) {
var genericContains = containsMethod.MakeGenericMethod(element.Type);
return Expression.Call(genericContains, target, element);
}
}
// Convert obj["foo.bar"].ContainsKey("baz") into obj.ContainsKey("foo.bar.baz")
if (node.Method.Name == "ContainsKey" &&
node.Method.ReturnType == typeof(bool) &&
node.Method.GetParameters().Length == 1) {
var getter = new ObjectNormalizer().Visit(node.Object) as MethodCallExpression;
Expression target = null;
string path = null;
if (IsParseObjectGet(getter) && getter.Object is ParameterExpression) {
target = getter.Object;
path = GetValue(getter.Arguments[0]) + "." + GetValue(node.Arguments[0]);
return Expression.Call(containsKeyMethod, target, Expression.Constant(path));
} else if (node.Object is ParameterExpression) {
target = node.Object;
path = GetValue(node.Arguments[0]) as string;
}
if (target != null && path != null) {
return Expression.Call(containsKeyMethod, target, Expression.Constant(path));
}
}
return base.VisitMethodCall(node);
}
}
/// <summary>
/// Converts a normalized method call expression into the appropriate AVQuery clause.
/// </summary>
private static AVQuery<T> WhereMethodCall<T>(
this AVQuery<T> source, Expression<Func<T, bool>> expression, MethodCallExpression node)
where T : AVObject {
if (IsParseObjectGet(node) && (node.Type == typeof(bool) || node.Type == typeof(bool?))) {
// This is a raw boolean field access like 'where obj.Get<bool>("foo")'
return source.WhereEqualTo(GetValue(node.Arguments[0]) as string, true);
}
MethodInfo translatedMethod;
if (functionMappings.TryGetValue(node.Method, out translatedMethod)) {
var objTransformed = new ObjectNormalizer().Visit(node.Object) as MethodCallExpression;
if (!(IsParseObjectGet(objTransformed) &&
objTransformed.Object == expression.Parameters[0])) {
throw new InvalidOperationException(
"The left-hand side of a supported function call must be a AVObject field access.");
}
var fieldPath = GetValue(objTransformed.Arguments[0]);
var containedIn = GetValue(node.Arguments[0]);
var queryType = translatedMethod.DeclaringType.GetGenericTypeDefinition()
.MakeGenericType(typeof(T));
translatedMethod = ReflectionHelpers.GetMethod(queryType,
translatedMethod.Name,
translatedMethod.GetParameters().Select(p => p.ParameterType).ToArray());
return translatedMethod.Invoke(source, new[] { fieldPath, containedIn }) as AVQuery<T>;
}
if (node.Arguments[0] == expression.Parameters[0]) {
// obj.ContainsKey("foo") --> query.WhereExists("foo")
if (node.Method == containsKeyMethod) {
return source.WhereExists(GetValue(node.Arguments[1]) as string);
}
// !obj.ContainsKey("foo") --> query.WhereDoesNotExist("foo")
if (node.Method == notContainsKeyMethod) {
return source.WhereDoesNotExist(GetValue(node.Arguments[1]) as string);
}
}
if (node.Method.IsGenericMethod) {
if (node.Method.GetGenericMethodDefinition() == containsMethod) {
// obj.Get<IList<T>>("path").Contains(someValue)
if (IsParseObjectGet(node.Arguments[0] as MethodCallExpression)) {
return source.WhereEqualTo(
GetValue(((MethodCallExpression)node.Arguments[0]).Arguments[0]) as string,
GetValue(node.Arguments[1]));
}
// someList.Contains(obj.Get<T>("path"))
if (IsParseObjectGet(node.Arguments[1] as MethodCallExpression)) {
var collection = GetValue(node.Arguments[0]) as System.Collections.IEnumerable;
return source.WhereContainedIn(
GetValue(((MethodCallExpression)node.Arguments[1]).Arguments[0]) as string,
collection.Cast<object>());
}
}
if (node.Method.GetGenericMethodDefinition() == notContainsMethod) {
// !obj.Get<IList<T>>("path").Contains(someValue)
if (IsParseObjectGet(node.Arguments[0] as MethodCallExpression)) {
return source.WhereNotEqualTo(
GetValue(((MethodCallExpression)node.Arguments[0]).Arguments[0]) as string,
GetValue(node.Arguments[1]));
}
// !someList.Contains(obj.Get<T>("path"))
if (IsParseObjectGet(node.Arguments[1] as MethodCallExpression)) {
var collection = GetValue(node.Arguments[0]) as System.Collections.IEnumerable;
return source.WhereNotContainedIn(
GetValue(((MethodCallExpression)node.Arguments[1]).Arguments[0]) as string,
collection.Cast<object>());
}
}
}
throw new InvalidOperationException(node.Method + " is not a supported method call in a where expression.");
}
/// <summary>
/// Converts a normalized binary expression into the appropriate AVQuery clause.
/// </summary>
private static AVQuery<T> WhereBinaryExpression<T>(
this AVQuery<T> source, Expression<Func<T, bool>> expression, BinaryExpression node)
where T : AVObject {
var leftTransformed = new ObjectNormalizer().Visit(node.Left) as MethodCallExpression;
if (!(IsParseObjectGet(leftTransformed) &&
leftTransformed.Object == expression.Parameters[0])) {
throw new InvalidOperationException(
"Where expressions must have one side be a field operation on a AVObject.");
}
var fieldPath = GetValue(leftTransformed.Arguments[0]) as string;
var filterValue = GetValue(node.Right);
if (filterValue != null && !AVEncoder.IsValidType(filterValue)) {
throw new InvalidOperationException(
"Where clauses must use types compatible with ParseObjects.");
}
switch (node.NodeType) {
case ExpressionType.GreaterThan:
return source.WhereGreaterThan(fieldPath, filterValue);
case ExpressionType.GreaterThanOrEqual:
return source.WhereGreaterThanOrEqualTo(fieldPath, filterValue);
case ExpressionType.LessThan:
return source.WhereLessThan(fieldPath, filterValue);
case ExpressionType.LessThanOrEqual:
return source.WhereLessThanOrEqualTo(fieldPath, filterValue);
case ExpressionType.Equal:
return source.WhereEqualTo(fieldPath, filterValue);
case ExpressionType.NotEqual:
return source.WhereNotEqualTo(fieldPath, filterValue);
default:
throw new InvalidOperationException(
"Where expressions do not support this operator.");
}
}
/// <summary>
/// Filters a query based upon the predicate provided.
/// </summary>
/// <typeparam name="TSource">The type of AVObject being queried for.</typeparam>
/// <param name="source">The base <see cref="ParseQuery{TSource}"/> to which
/// the predicate will be added.</param>
/// <param name="predicate">A function to test each AVObject for a condition.
/// The predicate must be able to be represented by one of the standard Where
/// functions on AVQuery</param>
/// <returns>A new AVQuery whose results will match the given predicate as
/// well as the source's filters.</returns>
public static AVQuery<TSource> Where<TSource>(
this AVQuery<TSource> source, Expression<Func<TSource, bool>> predicate)
where TSource : AVObject {
// Handle top-level logic operators && and ||
var binaryExpression = predicate.Body as BinaryExpression;
if (binaryExpression != null) {
if (binaryExpression.NodeType == ExpressionType.AndAlso) {
return source
.Where(Expression.Lambda<Func<TSource, bool>>(
binaryExpression.Left, predicate.Parameters))
.Where(Expression.Lambda<Func<TSource, bool>>(
binaryExpression.Right, predicate.Parameters));
}
if (binaryExpression.NodeType == ExpressionType.OrElse) {
var left = source.Where(Expression.Lambda<Func<TSource, bool>>(
binaryExpression.Left, predicate.Parameters));
var right = source.Where(Expression.Lambda<Func<TSource, bool>>(
binaryExpression.Right, predicate.Parameters));
return left.Or(right);
}
}
var normalized = new WhereNormalizer().Visit(predicate.Body);
var methodCallExpr = normalized as MethodCallExpression;
if (methodCallExpr != null) {
return source.WhereMethodCall(predicate, methodCallExpr);
}
var binaryExpr = normalized as BinaryExpression;
if (binaryExpr != null) {
return source.WhereBinaryExpression(predicate, binaryExpr);
}
var unaryExpr = normalized as UnaryExpression;
if (unaryExpr != null && unaryExpr.NodeType == ExpressionType.Not) {
var node = unaryExpr.Operand as MethodCallExpression;
if (IsParseObjectGet(node) && (node.Type == typeof(bool) || node.Type == typeof(bool?))) {
// This is a raw boolean field access like 'where !obj.Get<bool>("foo")'
return source.WhereNotEqualTo(GetValue(node.Arguments[0]) as string, true);
}
}
throw new InvalidOperationException(
"Encountered an unsupported expression for ParseQueries.");
}
/// <summary>
/// Normalizes an OrderBy's keySelector expression and then extracts the path
/// from the AVObject.Get() call.
/// </summary>
private static string GetOrderByPath<TSource, TSelector>(
Expression<Func<TSource, TSelector>> keySelector) {
string result = null;
var normalized = new ObjectNormalizer().Visit(keySelector.Body);
var callExpr = normalized as MethodCallExpression;
if (IsParseObjectGet(callExpr) && callExpr.Object == keySelector.Parameters[0]) {
// We're operating on the parameter
result = GetValue(callExpr.Arguments[0]) as string;
}
if (result == null) {
throw new InvalidOperationException(
"OrderBy expression must be a field access on a AVObject.");
}
return result;
}
/// <summary>
/// Orders a query based upon the key selector provided.
/// </summary>
/// <typeparam name="TSource">The type of AVObject being queried for.</typeparam>
/// <typeparam name="TSelector">The type of key returned by keySelector.</typeparam>
/// <param name="source">The query to order.</param>
/// <param name="keySelector">A function to extract a key from the AVObject.</param>
/// <returns>A new AVQuery based on source whose results will be ordered by
/// the key specified in the keySelector.</returns>
public static AVQuery<TSource> OrderBy<TSource, TSelector>(
this AVQuery<TSource> source, Expression<Func<TSource, TSelector>> keySelector)
where TSource : AVObject {
return source.OrderBy(GetOrderByPath(keySelector));
}
/// <summary>
/// Orders a query based upon the key selector provided.
/// </summary>
/// <typeparam name="TSource">The type of AVObject being queried for.</typeparam>
/// <typeparam name="TSelector">The type of key returned by keySelector.</typeparam>
/// <param name="source">The query to order.</param>
/// <param name="keySelector">A function to extract a key from the AVObject.</param>
/// <returns>A new AVQuery based on source whose results will be ordered by
/// the key specified in the keySelector.</returns>
public static AVQuery<TSource> OrderByDescending<TSource, TSelector>(
this AVQuery<TSource> source, Expression<Func<TSource, TSelector>> keySelector)
where TSource : AVObject {
return source.OrderByDescending(GetOrderByPath(keySelector));
}
/// <summary>
/// Performs a subsequent ordering of a query based upon the key selector provided.
/// </summary>
/// <typeparam name="TSource">The type of AVObject being queried for.</typeparam>
/// <typeparam name="TSelector">The type of key returned by keySelector.</typeparam>
/// <param name="source">The query to order.</param>
/// <param name="keySelector">A function to extract a key from the AVObject.</param>
/// <returns>A new AVQuery based on source whose results will be ordered by
/// the key specified in the keySelector.</returns>
public static AVQuery<TSource> ThenBy<TSource, TSelector>(
this AVQuery<TSource> source, Expression<Func<TSource, TSelector>> keySelector)
where TSource : AVObject {
return source.ThenBy(GetOrderByPath(keySelector));
}
/// <summary>
/// Performs a subsequent ordering of a query based upon the key selector provided.
/// </summary>
/// <typeparam name="TSource">The type of AVObject being queried for.</typeparam>
/// <typeparam name="TSelector">The type of key returned by keySelector.</typeparam>
/// <param name="source">The query to order.</param>
/// <param name="keySelector">A function to extract a key from the AVObject.</param>
/// <returns>A new AVQuery based on source whose results will be ordered by
/// the key specified in the keySelector.</returns>
public static AVQuery<TSource> ThenByDescending<TSource, TSelector>(
this AVQuery<TSource> source, Expression<Func<TSource, TSelector>> keySelector)
where TSource : AVObject {
return source.ThenByDescending(GetOrderByPath(keySelector));
}
/// <summary>
/// Correlates the elements of two queries based on matching keys.
/// </summary>
/// <typeparam name="TOuter">The type of ParseObjects of the first query.</typeparam>
/// <typeparam name="TInner">The type of ParseObjects of the second query.</typeparam>
/// <typeparam name="TKey">The type of the keys returned by the key selector
/// functions.</typeparam>
/// <typeparam name="TResult">The type of the result. This must match either
/// TOuter or TInner</typeparam>
/// <param name="outer">The first query to join.</param>
/// <param name="inner">The query to join to the first query.</param>
/// <param name="outerKeySelector">A function to extract a join key from the results of
/// the first query.</param>
/// <param name="innerKeySelector">A function to extract a join key from the results of
/// the second query.</param>
/// <param name="resultSelector">A function to select either the outer or inner query
/// result to determine which query is the base query.</param>
/// <returns>A new AVQuery with a WhereMatchesQuery or WhereMatchesKeyInQuery
/// clause based upon the query indicated in the <paramref name="resultSelector"/>.</returns>
public static AVQuery<TResult> Join<TOuter, TInner, TKey, TResult>(
this AVQuery<TOuter> outer,
AVQuery<TInner> inner,
Expression<Func<TOuter, TKey>> outerKeySelector,
Expression<Func<TInner, TKey>> innerKeySelector,
Expression<Func<TOuter, TInner, TResult>> resultSelector)
where TOuter : AVObject
where TInner : AVObject
where TResult : AVObject {
// resultSelector must select either the inner object or the outer object. If it's the inner
// object, reverse the query.
if (resultSelector.Body == resultSelector.Parameters[1]) {
// The inner object was selected.
return inner.Join<TInner, TOuter, TKey, TInner>(
outer,
innerKeySelector,
outerKeySelector,
(i, o) => i) as AVQuery<TResult>;
}
if (resultSelector.Body != resultSelector.Parameters[0]) {
throw new InvalidOperationException("Joins must select either the outer or inner object.");
}
// Normalize both selectors
Expression outerNormalized = new ObjectNormalizer().Visit(outerKeySelector.Body);
Expression innerNormalized = new ObjectNormalizer().Visit(innerKeySelector.Body);
MethodCallExpression outerAsGet = outerNormalized as MethodCallExpression;
MethodCallExpression innerAsGet = innerNormalized as MethodCallExpression;
if (IsParseObjectGet(outerAsGet) && outerAsGet.Object == outerKeySelector.Parameters[0]) {
var outerKey = GetValue(outerAsGet.Arguments[0]) as string;
if (IsParseObjectGet(innerAsGet) && innerAsGet.Object == innerKeySelector.Parameters[0]) {
// Both are key accesses, so treat this as a WhereMatchesKeyInQuery
var innerKey = GetValue(innerAsGet.Arguments[0]) as string;
return outer.WhereMatchesKeyInQuery(outerKey, innerKey, inner) as AVQuery<TResult>;
}
if (innerKeySelector.Body == innerKeySelector.Parameters[0]) {
// The inner selector is on the result of the query itself, so treat this as a
// WhereMatchesQuery
return outer.WhereMatchesQuery(outerKey, inner) as AVQuery<TResult>;
}
throw new InvalidOperationException(
"The key for the joined object must be a AVObject or a field access " +
"on the AVObject.");
}
// TODO (hallucinogen): If we ever support "and" queries fully and/or support a "where this object
// matches some key in some other query" (as opposed to requiring a key on this query), we
// can add support for even more types of joins.
throw new InvalidOperationException(
"The key for the selected object must be a field access on the AVObject.");
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Hyak.Common.Internals;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Network
{
/// <summary>
/// The Network Resource Provider API includes operations for managing the
/// Virtual network Gateway for your subscription.
/// </summary>
internal partial class LocalNetworkGatewayOperations : IServiceOperations<NetworkResourceProviderClient>, ILocalNetworkGatewayOperations
{
/// <summary>
/// Initializes a new instance of the LocalNetworkGatewayOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal LocalNetworkGatewayOperations(NetworkResourceProviderClient client)
{
this._client = client;
}
private NetworkResourceProviderClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Network.NetworkResourceProviderClient.
/// </summary>
public NetworkResourceProviderClient Client
{
get { return this._client; }
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Create or update Local
/// Network Gateway operation through Network resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for PutLocalNetworkGateway Api servive call
/// </returns>
public async Task<LocalNetworkGatewayPutResponse> BeginCreateOrUpdatingAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ArgumentNullException("localNetworkGatewayName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdatingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/localNetworkGateways/";
url = url + Uri.EscapeDataString(localNetworkGatewayName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject localNetworkGatewayJsonFormatValue = new JObject();
requestDoc = localNetworkGatewayJsonFormatValue;
JObject propertiesValue = new JObject();
localNetworkGatewayJsonFormatValue["properties"] = propertiesValue;
if (parameters.GatewayIpAddress != null)
{
propertiesValue["gatewayIpAddress"] = parameters.GatewayIpAddress;
}
if (parameters.LocalNetworkSiteAddressSpace != null)
{
JObject localNetworkSiteAddressSpaceValue = new JObject();
propertiesValue["localNetworkSiteAddressSpace"] = localNetworkSiteAddressSpaceValue;
if (parameters.LocalNetworkSiteAddressSpace.AddressPrefixes != null)
{
if (parameters.LocalNetworkSiteAddressSpace.AddressPrefixes is ILazyCollection == false || ((ILazyCollection)parameters.LocalNetworkSiteAddressSpace.AddressPrefixes).IsInitialized)
{
JArray addressPrefixesArray = new JArray();
foreach (string addressPrefixesItem in parameters.LocalNetworkSiteAddressSpace.AddressPrefixes)
{
addressPrefixesArray.Add(addressPrefixesItem);
}
localNetworkSiteAddressSpaceValue["addressPrefixes"] = addressPrefixesArray;
}
}
}
if (parameters.ProvisioningState != null)
{
propertiesValue["provisioningState"] = parameters.ProvisioningState;
}
if (parameters.Etag != null)
{
localNetworkGatewayJsonFormatValue["etag"] = parameters.Etag;
}
if (parameters.Id != null)
{
localNetworkGatewayJsonFormatValue["id"] = parameters.Id;
}
if (parameters.Name != null)
{
localNetworkGatewayJsonFormatValue["name"] = parameters.Name;
}
if (parameters.Type != null)
{
localNetworkGatewayJsonFormatValue["type"] = parameters.Type;
}
localNetworkGatewayJsonFormatValue["location"] = parameters.Location;
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
localNetworkGatewayJsonFormatValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LocalNetworkGatewayPutResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LocalNetworkGatewayPutResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LocalNetworkGateway localNetworkGatewayInstance = new LocalNetworkGateway();
result.LocalNetworkGateway = localNetworkGatewayInstance;
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
JToken gatewayIpAddressValue = propertiesValue2["gatewayIpAddress"];
if (gatewayIpAddressValue != null && gatewayIpAddressValue.Type != JTokenType.Null)
{
string gatewayIpAddressInstance = ((string)gatewayIpAddressValue);
localNetworkGatewayInstance.GatewayIpAddress = gatewayIpAddressInstance;
}
JToken localNetworkSiteAddressSpaceValue2 = propertiesValue2["localNetworkSiteAddressSpace"];
if (localNetworkSiteAddressSpaceValue2 != null && localNetworkSiteAddressSpaceValue2.Type != JTokenType.Null)
{
AddressSpace localNetworkSiteAddressSpaceInstance = new AddressSpace();
localNetworkGatewayInstance.LocalNetworkSiteAddressSpace = localNetworkSiteAddressSpaceInstance;
JToken addressPrefixesArray2 = localNetworkSiteAddressSpaceValue2["addressPrefixes"];
if (addressPrefixesArray2 != null && addressPrefixesArray2.Type != JTokenType.Null)
{
foreach (JToken addressPrefixesValue in ((JArray)addressPrefixesArray2))
{
localNetworkSiteAddressSpaceInstance.AddressPrefixes.Add(((string)addressPrefixesValue));
}
}
}
JToken provisioningStateValue = propertiesValue2["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
localNetworkGatewayInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
localNetworkGatewayInstance.Etag = etagInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
localNetworkGatewayInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
localNetworkGatewayInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
localNetworkGatewayInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
localNetworkGatewayInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey2 = ((string)property.Name);
string tagsValue2 = ((string)property.Value);
localNetworkGatewayInstance.Tags.Add(tagsKey2, tagsValue2);
}
}
JToken errorValue = responseDoc["error"];
if (errorValue != null && errorValue.Type != JTokenType.Null)
{
Error errorInstance = new Error();
result.Error = errorInstance;
JToken codeValue = errorValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = errorValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = errorValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
JToken detailsArray = errorValue["details"];
if (detailsArray != null && detailsArray.Type != JTokenType.Null)
{
foreach (JToken detailsValue in ((JArray)detailsArray))
{
ErrorDetails errorDetailsInstance = new ErrorDetails();
errorInstance.Details.Add(errorDetailsInstance);
JToken codeValue2 = detailsValue["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
errorDetailsInstance.Code = codeInstance2;
}
JToken targetValue2 = detailsValue["target"];
if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
{
string targetInstance2 = ((string)targetValue2);
errorDetailsInstance.Target = targetInstance2;
}
JToken messageValue2 = detailsValue["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
errorDetailsInstance.Message = messageInstance2;
}
}
}
JToken innerErrorValue = errorValue["innerError"];
if (innerErrorValue != null && innerErrorValue.Type != JTokenType.Null)
{
string innerErrorInstance = ((string)innerErrorValue);
errorInstance.InnerError = innerErrorInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public async Task<UpdateOperationResponse> BeginDeletingAsync(string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ArgumentNullException("localNetworkGatewayName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/localNetworkGateways/";
url = url + Uri.EscapeDataString(localNetworkGatewayName);
url = url + "/";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UpdateOperationResponse result = null;
// Deserialize Response
result = new UpdateOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Azure-AsyncOperation"))
{
result.AzureAsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Create or update Local
/// Network Gateway operation through Network resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters, CancellationToken cancellationToken)
{
NetworkResourceProviderClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
LocalNetworkGatewayPutResponse response = await client.LocalNetworkGateways.BeginCreateOrUpdatingAsync(resourceGroupName, localNetworkGatewayName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken)
{
NetworkResourceProviderClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
UpdateOperationResponse response = await client.LocalNetworkGateways.BeginDeletingAsync(resourceGroupName, localNetworkGatewayName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
AzureAsyncOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != Microsoft.Azure.Management.Network.Models.OperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetLongRunningOperationStatusAsync(response.AzureAsyncOperation, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// The Get LocalNetworkGateway operation retrieves information about
/// the specified local network gateway through Network resource
/// provider.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for GetLocalNetworkgateway Api servive call.
/// </returns>
public async Task<LocalNetworkGatewayGetResponse> GetAsync(string resourceGroupName, string localNetworkGatewayName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (localNetworkGatewayName == null)
{
throw new ArgumentNullException("localNetworkGatewayName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("localNetworkGatewayName", localNetworkGatewayName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/localNetworkGateways/";
url = url + Uri.EscapeDataString(localNetworkGatewayName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LocalNetworkGatewayGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LocalNetworkGatewayGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
LocalNetworkGateway localNetworkGatewayInstance = new LocalNetworkGateway();
result.LocalNetworkGateway = localNetworkGatewayInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken gatewayIpAddressValue = propertiesValue["gatewayIpAddress"];
if (gatewayIpAddressValue != null && gatewayIpAddressValue.Type != JTokenType.Null)
{
string gatewayIpAddressInstance = ((string)gatewayIpAddressValue);
localNetworkGatewayInstance.GatewayIpAddress = gatewayIpAddressInstance;
}
JToken localNetworkSiteAddressSpaceValue = propertiesValue["localNetworkSiteAddressSpace"];
if (localNetworkSiteAddressSpaceValue != null && localNetworkSiteAddressSpaceValue.Type != JTokenType.Null)
{
AddressSpace localNetworkSiteAddressSpaceInstance = new AddressSpace();
localNetworkGatewayInstance.LocalNetworkSiteAddressSpace = localNetworkSiteAddressSpaceInstance;
JToken addressPrefixesArray = localNetworkSiteAddressSpaceValue["addressPrefixes"];
if (addressPrefixesArray != null && addressPrefixesArray.Type != JTokenType.Null)
{
foreach (JToken addressPrefixesValue in ((JArray)addressPrefixesArray))
{
localNetworkSiteAddressSpaceInstance.AddressPrefixes.Add(((string)addressPrefixesValue));
}
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
localNetworkGatewayInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
localNetworkGatewayInstance.Etag = etagInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
localNetworkGatewayInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
localNetworkGatewayInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
localNetworkGatewayInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
localNetworkGatewayInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
localNetworkGatewayInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List LocalNetworkGateways opertion retrieves all the local
/// network gateways stored.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for ListLocalNetworkGateways Api service call
/// </returns>
public async Task<LocalNetworkGatewayListResponse> ListAsync(string resourceGroupName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Network";
url = url + "/localNetworkGateways";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-05-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LocalNetworkGatewayListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new LocalNetworkGatewayListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
LocalNetworkGateway localNetworkGatewayJsonFormatInstance = new LocalNetworkGateway();
result.LocalNetworkGateways.Add(localNetworkGatewayJsonFormatInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
JToken gatewayIpAddressValue = propertiesValue["gatewayIpAddress"];
if (gatewayIpAddressValue != null && gatewayIpAddressValue.Type != JTokenType.Null)
{
string gatewayIpAddressInstance = ((string)gatewayIpAddressValue);
localNetworkGatewayJsonFormatInstance.GatewayIpAddress = gatewayIpAddressInstance;
}
JToken localNetworkSiteAddressSpaceValue = propertiesValue["localNetworkSiteAddressSpace"];
if (localNetworkSiteAddressSpaceValue != null && localNetworkSiteAddressSpaceValue.Type != JTokenType.Null)
{
AddressSpace localNetworkSiteAddressSpaceInstance = new AddressSpace();
localNetworkGatewayJsonFormatInstance.LocalNetworkSiteAddressSpace = localNetworkSiteAddressSpaceInstance;
JToken addressPrefixesArray = localNetworkSiteAddressSpaceValue["addressPrefixes"];
if (addressPrefixesArray != null && addressPrefixesArray.Type != JTokenType.Null)
{
foreach (JToken addressPrefixesValue in ((JArray)addressPrefixesArray))
{
localNetworkSiteAddressSpaceInstance.AddressPrefixes.Add(((string)addressPrefixesValue));
}
}
}
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
localNetworkGatewayJsonFormatInstance.ProvisioningState = provisioningStateInstance;
}
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
localNetworkGatewayJsonFormatInstance.Etag = etagInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
localNetworkGatewayJsonFormatInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
localNetworkGatewayJsonFormatInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
localNetworkGatewayJsonFormatInstance.Type = typeInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
localNetworkGatewayJsonFormatInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
localNetworkGatewayJsonFormatInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.HDInsight.Job;
using Microsoft.Azure.Management.HDInsight.Job.Models;
namespace Microsoft.Azure.Management.HDInsight.Job
{
/// <summary>
/// The HDInsight job client manages jobs against HDInsight clusters.
/// </summary>
public static partial class JobOperationsExtensions
{
/// <summary>
/// Gets job details from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static JobGetResponse GetJob(this IJobOperations operations, string jobId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).GetJobAsync(jobId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets job details from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static Task<JobGetResponse> GetJobAsync(this IJobOperations operations, string jobId)
{
return operations.GetJobAsync(jobId, CancellationToken.None);
}
/// <summary>
/// Initiates cancel on given running job in the specified HDInsight
/// cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static JobGetResponse KillJob(this IJobOperations operations, string jobId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).KillJobAsync(jobId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Initiates cancel on given running job in the specified HDInsight
/// cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static Task<JobGetResponse> KillJobAsync(this IJobOperations operations, string jobId)
{
return operations.KillJobAsync(jobId, CancellationToken.None);
}
/// <summary>
/// Gets the list of jobs from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static JobListResponse ListJobs(this IJobOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).ListJobsAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of jobs from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static Task<JobListResponse> ListJobsAsync(this IJobOperations operations)
{
return operations.ListJobsAsync(CancellationToken.None);
}
/// <summary>
/// Gets numOfJobs after jobId from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Optional. jobId from where to list jobs.
/// </param>
/// <param name='numOfJobs'>
/// Required. Number of jobs to fetch. Use -1 to get all.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static JobListResponse ListJobsAfterJobId(this IJobOperations operations, string jobId, int numOfJobs)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).ListJobsAfterJobIdAsync(jobId, numOfJobs);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets numOfJobs after jobId from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Optional. jobId from where to list jobs.
/// </param>
/// <param name='numOfJobs'>
/// Required. Number of jobs to fetch. Use -1 to get all.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static Task<JobListResponse> ListJobsAfterJobIdAsync(this IJobOperations operations, string jobId, int numOfJobs)
{
return operations.ListJobsAfterJobIdAsync(jobId, numOfJobs, CancellationToken.None);
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Hive job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitHiveJob(this IJobOperations operations, HiveJobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitHiveJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Hive job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static Task<JobSubmissionResponse> SubmitHiveJobAsync(this IJobOperations operations, HiveJobSubmissionParameters parameters)
{
return operations.SubmitHiveJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits a MapReduce job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitMapReduceJob(this IJobOperations operations, MapReduceJobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitMapReduceJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits a MapReduce job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static Task<JobSubmissionResponse> SubmitMapReduceJobAsync(this IJobOperations operations, MapReduceJobSubmissionParameters parameters)
{
return operations.SubmitMapReduceJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits a MapReduce streaming job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitMapReduceStreamingJob(this IJobOperations operations, MapReduceStreamingJobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitMapReduceStreamingJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits a MapReduce streaming job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static Task<JobSubmissionResponse> SubmitMapReduceStreamingJobAsync(this IJobOperations operations, MapReduceStreamingJobSubmissionParameters parameters)
{
return operations.SubmitMapReduceStreamingJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Pig job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitPigJob(this IJobOperations operations, PigJobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitPigJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Pig job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static Task<JobSubmissionResponse> SubmitPigJobAsync(this IJobOperations operations, PigJobSubmissionParameters parameters)
{
return operations.SubmitPigJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits an Sqoop job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Sqoop job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static JobSubmissionResponse SubmitSqoopJob(this IJobOperations operations, SqoopJobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitSqoopJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits an Sqoop job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Sqoop job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
public static Task<JobSubmissionResponse> SubmitSqoopJobAsync(this IJobOperations operations, SqoopJobSubmissionParameters parameters)
{
return operations.SubmitSqoopJobAsync(parameters, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using BTDB.KVDBLayer;
using NUnit.Framework;
namespace BTDBTest
{
[TestFixture, Ignore("Takes too long time")]
public class KeyValueDBCustomTest
{
[SetUp]
public void Initialization()
{
if (Directory.Exists("data"))
{
foreach (string file in Directory.EnumerateFiles("data"))
File.Delete(file);
}
else
Directory.CreateDirectory("data");
}
[Test]
public void Reader()
{
IEnumerable<KeyValuePair<long, Tick>> flow = TicksGenerator.GetFlow(1000000, KeysType.Random);
//passed
//using (var fileCollection = new OnDiskFileCollection("data"))
//failed
using (var fileCollection = new OnDiskMemoryMappedFileCollection("data"))
//passed
//using (var fileCollection = new InMemoryFileCollection())
{
using (IKeyValueDB db = new KeyValueDB(fileCollection, new SnappyCompressionStrategy(), (uint)Int16.MaxValue * 10))
{
using (var tr = db.StartTransaction())
{
foreach (KeyValuePair<long, Tick> item in flow)
{
byte[] key = Direct(item.Key);
byte[] value = FromTick(item.Value);
tr.CreateOrUpdateKeyValue(key, value);
}
tr.Commit();
}
flow = TicksGenerator.GetFlow(1000000, KeysType.Random);
foreach (KeyValuePair<long, Tick> item in flow)
{
using (var tr = db.StartTransaction())
{
byte[] key = Direct(item.Key);
bool find = tr.FindExactKey(key);
if (find)
{
var id = Reverse(tr.GetKeyAsByteArray());
var tick = ToTick(tr.GetValueAsByteArray());
Assert.AreEqual(item.Key, id);
}
}
}
}
}
}
byte[] FromTick(Tick tick)
{
using (MemoryStream stream = new MemoryStream())
{
var writer = new BinaryWriter(stream);
writer.Write(tick.Symbol);
writer.Write(tick.Timestamp.Ticks);
writer.Write(tick.Bid);
writer.Write(tick.Ask);
writer.Write(tick.BidSize);
writer.Write(tick.AskSize);
writer.Write(tick.Provider);
return stream.ToArray();
}
}
Tick ToTick(byte[] value)
{
var tick = new Tick();
using (MemoryStream stream = new MemoryStream(value))
{
var reader = new BinaryReader(stream);
tick.Symbol = reader.ReadString();
tick.Timestamp = new DateTime(reader.ReadInt64());
tick.Bid = reader.ReadDouble();
tick.Ask = reader.ReadDouble();
tick.BidSize = reader.ReadInt32();
tick.AskSize = reader.ReadInt32();
tick.Provider = reader.ReadString();
}
return tick;
}
byte[] Direct(Int64 key)
{
var val = (UInt64)(key + Int64.MaxValue + 1);
var index = BitConverter.GetBytes(val);
byte[] buf = new byte[8];
buf[0] = index[7];
buf[1] = index[6];
buf[2] = index[5];
buf[3] = index[4];
buf[4] = index[3];
buf[5] = index[2];
buf[6] = index[1];
buf[7] = index[0];
return buf;
}
Int64 Reverse(byte[] index)
{
byte[] buf = new byte[8];
buf[0] = index[7];
buf[1] = index[6];
buf[2] = index[5];
buf[3] = index[4];
buf[4] = index[3];
buf[5] = index[2];
buf[6] = index[1];
buf[7] = index[0];
UInt64 val = BitConverter.ToUInt64(buf, 0);
return (Int64)(val - (UInt64)Int64.MaxValue - 1);
}
}
public static class TicksGenerator
{
static readonly string[] symbols;
static readonly int[] digits;
static readonly double[] pipsizes;
static readonly double[] prices;
static readonly string[] providers;
static TicksGenerator()
{
//2013-11-12 13:00
var data = new string[] { "USDCHF;4;0.9197", "GBPUSD;4;1.5880", "EURUSD;4;1.3403", "USDJPY;2;99.73", "EURCHF;4;1.2324", "AUDBGN;4;1.3596", "AUDCHF;4;0.8567", "AUDJPY;2;92.96",
"BGNJPY;2;68.31", "BGNUSD;4;0.6848", "CADBGN;4;1.3901", "CADCHF;4;0.8759", "CADUSD;4;0.9527", "CHFBGN;4;1.5862", "CHFJPY;2;108.44", "CHFUSD;4;1.0875", "EURAUD;4;1.4375", "EURCAD;4;1.4064",
"EURGBP;4;0.8438", "EURJPY;4;133.66", "GBPAUD;4;1.7031", "GBPBGN;4;2.3169", "GBPCAD;4;1.6661", "GBPCHF;4;1.4603", "GBPJPY;2;158.37", "NZDUSD;4;0.8217", "USDBGN;4;1.4594", "USDCAD;4;1.0493",
"XAUUSD;2;1281.15", "XAGUSD;2;21.21", "$DAX;2;9078.20","$FTSE;2;6707.49","$NASDAQ;2;3361.02","$SP500;2;1771.32"};
symbols = new string[data.Length];
digits = new int[data.Length];
pipsizes = new double[data.Length];
prices = new double[data.Length];
providers = new string[] { "eSignal", "Gain", "NYSE", "TSE", "NASDAQ", "Euronext", "LSE", "SSE", "ASE", "SE", "NSEI" };
var format = new NumberFormatInfo();
format.NumberDecimalSeparator = ".";
for (int i = 0; i < data.Length; i++)
{
var tokens = data[i].Split(';'); //symbol;digits;price
symbols[i] = tokens[0];
digits[i] = Int32.Parse(tokens[1]);
pipsizes[i] = Math.Round(Math.Pow(10, -digits[i]), digits[i]);
prices[i] = Math.Round(Double.Parse(tokens[2], format), digits[i]);
}
}
public static IEnumerable<KeyValuePair<long, Tick>> GetFlow(long number, KeysType keysType)
{
var random = new Random(0);
//init startup prices
var prices = TicksGenerator.prices.ToArray();
DateTime timestamp = DateTime.Now;
//generate ticks
for (long i = 0; i < number; i++)
{
int id = random.Next(symbols.Length);
//random movement (Random Walk)
int direction = random.Next() % 2 == 0 ? 1 : -1;
int pips = random.Next(0, 10);
int spread = random.Next(2, 30);
int seconds = random.Next(1, 30);
string symbol = symbols[id];
int d = digits[id];
double pipSize = pipsizes[id];
//generate values
timestamp = timestamp.AddSeconds(seconds);
double bid = Math.Round(prices[id] + direction * pips * pipSize, d);
double ask = Math.Round(bid + spread * pipSize, d);
int bidSize = random.Next(0, 10000);
int askSize = random.Next(0, 10000);
string provider = providers[random.Next(providers.Length)];
//create tick
var tick = new Tick(symbol, timestamp, bid, ask, bidSize, askSize, provider);
var key = keysType == KeysType.Sequential ? i : unchecked(random.Next() * i);
var kv = new KeyValuePair<long, Tick>(key, tick);
yield return kv;
prices[id] = bid;
}
}
}
public enum KeysType : byte
{
Sequential,
Random
}
public class Tick : IComparable<Tick>
{
public string Symbol { get; set; }
public DateTime Timestamp { get; set; }
public double Bid { get; set; }
public double Ask { get; set; }
public int BidSize { get; set; }
public int AskSize { get; set; }
public string Provider { get; set; }
public Tick()
{
}
public Tick(string symbol, DateTime time, double bid, double ask, int bidSize, int askSize, string provider)
{
Symbol = symbol;
Timestamp = time;
Bid = bid;
Ask = ask;
BidSize = bidSize;
AskSize = askSize;
Provider = provider;
}
public override string ToString()
{
return String.Format("{0};{1:yyyy-MM-dd HH:mm:ss};{2};{3};{4};{5};{6}", Symbol, Timestamp, Bid, Ask, BidSize, AskSize, Provider);
}
public int CompareTo(Tick other)
{
if (other.Ask.CompareTo(this.Ask) != 0)
return -1;
if (other.AskSize != this.AskSize)
return -1;
if (Math.Abs(other.Bid - this.Bid) > 1e-50)
return -1;
if (other.BidSize != this.BidSize)
return -1;
if (!other.Provider.Equals(this.Provider))
return -1;
if (!other.Symbol.Equals(this.Symbol))
return -1;
if (!other.Timestamp.Equals(this.Timestamp))
return -1;
return 0;
}
}
}
| |
using System;
using System.IO;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Cache;
using System.Text;
using System.Web;
using System.Security.Cryptography;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using SteamKit2;
namespace SteamTrade
{
/// <summary>
/// SteamWeb class to create an API endpoint to the Steam Web.
/// </summary>
public class SteamWeb
{
/// <summary>
/// Base steam community domain.
/// </summary>
public const string SteamCommunityDomain = "steamcommunity.com";
/// <summary>
/// Token of steam. Generated after login.
/// </summary>
public string Token { get; private set; }
/// <summary>
/// Session id of Steam after Login.
/// </summary>
public string SessionId { get; private set; }
/// <summary>
/// Token secure as string. It is generated after the Login.
/// </summary>
public string TokenSecure { get; private set; }
/// <summary>
/// CookieContainer to save all cookies during the Login.
/// </summary>
private CookieContainer _cookies = new CookieContainer();
/// <summary>
/// This method is using the Request method to return the full http stream from a web request as string.
/// </summary>
/// <param name="url">URL of the http request.</param>
/// <param name="method">Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.</param>
/// <param name="data">A NameValueCollection including Headers added to the request.</param>
/// <param name="ajax">A bool to define if the http request is an ajax request.</param>
/// <param name="referer">Gets information about the URL of the client's previous request that linked to the current URL.</param>
/// <param name="fetchError">If true, response codes other than HTTP 200 will still be returned, rather than throwing exceptions</param>
/// <returns>The string of the http return stream.</returns>
/// <remarks>If you want to know how the request method works, use: <see cref="SteamWeb.Request"/></remarks>
public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "", bool fetchError = false)
{
// Reading the response as stream and read it to the end. After that happened return the result as string.
using (HttpWebResponse response = Request(url, method, data, ajax, referer, fetchError))
{
using (Stream responseStream = response.GetResponseStream())
{
// If the response stream is null it cannot be read. So return an empty string.
if (responseStream == null)
{
return "";
}
using (StreamReader reader = new StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
}
/// <summary>
/// Custom wrapper for creating a HttpWebRequest, edited for Steam.
/// </summary>
/// <param name="url">Gets information about the URL of the current request.</param>
/// <param name="method">Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.</param>
/// <param name="data">A NameValueCollection including Headers added to the request.</param>
/// <param name="ajax">A bool to define if the http request is an ajax request.</param>
/// <param name="referer">Gets information about the URL of the client's previous request that linked to the current URL.</param>
/// <param name="fetchError">Return response even if its status code is not 200</param>
/// <returns>An instance of a HttpWebResponse object.</returns>
public HttpWebResponse Request(string url, string method, NameValueCollection data = null, bool ajax = true, string referer = "", bool fetchError = false)
{
// Append the data to the URL for GET-requests.
bool isGetMethod = (method.ToLower() == "get");
string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key =>
// ReSharper disable once UseStringInterpolation
string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(data[key]))
)));
// Example working with C# 6
// string dataString = (data == null ? null : String.Join("&", Array.ConvertAll(data.AllKeys, key => $"{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(data[key])}" )));
// Append the dataString to the url if it is a GET request.
if (isGetMethod && !string.IsNullOrEmpty(dataString))
{
url += (url.Contains("?") ? "&" : "?") + dataString;
}
// Setup the request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Accept = "application/json, text/javascript;q=0.9, */*;q=0.5";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
// request.Host is set automatically.
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
request.Referer = string.IsNullOrEmpty(referer) ? "http://steamcommunity.com/trade/1" : referer;
request.Timeout = 50000; // Timeout after 50 seconds.
request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Revalidate);
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
// If the request is an ajax request we need to add various other Headers, defined below.
if (ajax)
{
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
request.Headers.Add("X-Prototype-Version", "1.7");
}
// Cookies
request.CookieContainer = _cookies;
// If the request is a GET request return now the response. If not go on. Because then we need to apply data to the request.
if (isGetMethod || string.IsNullOrEmpty(dataString))
{
return request.GetResponse() as HttpWebResponse;
}
// Write the data to the body for POST and other methods.
byte[] dataBytes = Encoding.UTF8.GetBytes(dataString);
request.ContentLength = dataBytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(dataBytes, 0, dataBytes.Length);
}
// Get the response and return it.
try
{
return request.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
//this is thrown if response code is not 200
if (fetchError)
{
var resp = ex.Response as HttpWebResponse;
if (resp != null)
{
return resp;
}
}
throw;
}
}
/// <summary>
/// Executes the login by using the Steam Website.
/// This Method is not used by Steambot repository, but it could be very helpful if you want to build a own Steambot or want to login into steam services like backpack.tf/csgolounge.com.
/// Updated: 10-02-2015.
/// </summary>
/// <param name="username">Your Steam username.</param>
/// <param name="password">Your Steam password.</param>
/// <returns>A bool containing a value, if the login was successful.</returns>
public bool DoLogin(string username, string password)
{
var data = new NameValueCollection {{"username", username}};
// First get the RSA key with which we will encrypt our password.
string response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false);
GetRsaKey rsaJson = JsonConvert.DeserializeObject<GetRsaKey>(response);
// Validate, if we could get the rsa key.
if (!rsaJson.success)
{
return false;
}
// RSA Encryption.
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters rsaParameters = new RSAParameters
{
Exponent = HexToByte(rsaJson.publickey_exp),
Modulus = HexToByte(rsaJson.publickey_mod)
};
rsa.ImportParameters(rsaParameters);
// Encrypt the password and convert it.
byte[] bytePassword = Encoding.ASCII.GetBytes(password);
byte[] encodedPassword = rsa.Encrypt(bytePassword, false);
string encryptedBase64Password = Convert.ToBase64String(encodedPassword);
SteamResult loginJson = null;
CookieCollection cookieCollection;
string steamGuardText = "";
string steamGuardId = "";
// Do this while we need a captcha or need email authentification. Probably you have misstyped the captcha or the SteamGaurd code if this comes multiple times.
do
{
Console.WriteLine("SteamWeb: Logging In...");
bool captcha = loginJson != null && loginJson.captcha_needed;
bool steamGuard = loginJson != null && loginJson.emailauth_needed;
string time = Uri.EscapeDataString(rsaJson.timestamp);
string capGid = string.Empty;
// Response does not need to send if captcha is needed or not.
// ReSharper disable once MergeSequentialChecks
if (loginJson != null && loginJson.captcha_gid != null)
{
capGid = Uri.EscapeDataString(loginJson.captcha_gid);
}
data = new NameValueCollection {{"password", encryptedBase64Password}, {"username", username}};
// Captcha Check.
string capText = "";
if (captcha)
{
Console.WriteLine("SteamWeb: Captcha is needed.");
System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid);
Console.WriteLine("SteamWeb: Type the captcha:");
string consoleText = Console.ReadLine();
if (!string.IsNullOrEmpty(consoleText))
{
capText = Uri.EscapeDataString(consoleText);
}
}
data.Add("captchagid", captcha ? capGid : "");
data.Add("captcha_text", captcha ? capText : "");
// Captcha end.
// Added Header for two factor code.
data.Add("twofactorcode", "");
// Added Header for remember login. It can also set to true.
data.Add("remember_login", "false");
// SteamGuard check. If SteamGuard is enabled you need to enter it. Care probably you need to wait 7 days to trade.
// For further information about SteamGuard see: https://support.steampowered.com/kb_article.php?ref=4020-ALZM-5519&l=english.
if (steamGuard)
{
Console.WriteLine("SteamWeb: SteamGuard is needed.");
Console.WriteLine("SteamWeb: Type the code:");
string consoleText = Console.ReadLine();
if (!string.IsNullOrEmpty(consoleText))
{
steamGuardText = Uri.EscapeDataString(consoleText);
}
steamGuardId = loginJson.emailsteamid;
// Adding the machine name to the NameValueCollection, because it is requested by steam.
Console.WriteLine("SteamWeb: Type your machine name:");
consoleText = Console.ReadLine();
var machineName = string.IsNullOrEmpty(consoleText) ? "" : Uri.EscapeDataString(consoleText);
data.Add("loginfriendlyname", machineName != "" ? machineName : "defaultSteamBotMachine");
}
data.Add("emailauth", steamGuardText);
data.Add("emailsteamid", steamGuardId);
// SteamGuard end.
// Added unixTimestamp. It is included in the request normally.
var unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
// Added three "0"'s because Steam has a weird unix timestamp interpretation.
data.Add("donotcache", unixTimestamp + "000");
data.Add("rsatimestamp", time);
// Sending the actual login.
using(HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false))
{
var stream = webResponse.GetResponseStream();
if (stream == null)
{
return false;
}
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
loginJson = JsonConvert.DeserializeObject<SteamResult>(json);
cookieCollection = webResponse.Cookies;
}
}
} while (loginJson.captcha_needed || loginJson.emailauth_needed);
// If the login was successful, we need to enter the cookies to steam.
if (loginJson.success)
{
_cookies = new CookieContainer();
foreach (Cookie cookie in cookieCollection)
{
_cookies.Add(cookie);
}
SubmitCookies(_cookies);
return true;
}
else
{
Console.WriteLine("SteamWeb Error: " + loginJson.message);
return false;
}
}
///<summary>
/// Authenticate using SteamKit2 and ISteamUserAuth.
/// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website.
/// </summary>
/// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks>
/// <param name="myUniqueId">Id what you get to login.</param>
/// <param name="client">An instance of a SteamClient.</param>
/// <param name="myLoginKey">Login Key of your account.</param>
/// <returns>A bool, which is true if the login was successful.</returns>
public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey)
{
Token = TokenSecure = "";
SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));
_cookies = new CookieContainer();
using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth"))
{
// Generate an AES session key.
var sessionKey = CryptoHelper.GenerateRandomBlock(32);
// rsa encrypt it with the public key for the universe we're on
byte[] cryptedSessionKey;
using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse)))
{
cryptedSessionKey = rsa.Encrypt(sessionKey);
}
byte[] loginKey = new byte[20];
Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length);
// AES encrypt the loginkey with our session key.
byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);
KeyValue authResult;
// Get the Authentification Result.
try
{
authResult = userAuth.AuthenticateUser(
steamid: client.SteamID.ConvertToUInt64(),
sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
method: "POST",
secure: true
);
}
catch (Exception)
{
Token = TokenSecure = null;
return false;
}
Token = authResult["token"].AsString();
TokenSecure = authResult["tokensecure"].AsString();
// Adding cookies to the cookie container.
_cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain));
_cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain));
_cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain));
return true;
}
}
/// <summary>
/// Authenticate using an array of cookies from a browser or whatever source, without contacting the server.
/// It is recommended that you call <see cref="VerifyCookies"/> after calling this method to ensure that the cookies are valid.
/// </summary>
/// <param name="cookies">An array of cookies from a browser or whatever source. Must contain sessionid, steamLogin, steamLoginSecure</param>
/// <exception cref="ArgumentException">One of the required cookies(steamLogin, steamLoginSecure, sessionid) is missing.</exception>
public void Authenticate(System.Collections.Generic.IEnumerable<Cookie> cookies)
{
var cookieContainer = new CookieContainer();
string token = null;
string tokenSecure = null;
string sessionId = null;
foreach (var cookie in cookies)
{
if (cookie.Name == "sessionid")
sessionId = cookie.Value;
else if (cookie.Name == "steamLogin")
token = cookie.Value;
else if (cookie.Name == "steamLoginSecure")
tokenSecure = cookie.Value;
cookieContainer.Add(cookie);
}
if (token == null)
throw new ArgumentException("Cookie with name \"steamLogin\" is not found.");
if (tokenSecure == null)
throw new ArgumentException("Cookie with name \"steamLoginSecure\" is not found.");
if (sessionId == null)
throw new ArgumentException("Cookie with name \"sessionid\" is not found.");
Token = token;
TokenSecure = tokenSecure;
SessionId = sessionId;
_cookies = cookieContainer;
}
/// <summary>
/// Helper method to verify our precious cookies.
/// </summary>
/// <returns>true if cookies are correct; false otherwise</returns>
public bool VerifyCookies()
{
using (HttpWebResponse response = Request("http://steamcommunity.com/", "HEAD"))
{
return response.Cookies["steamLogin"] == null || !response.Cookies["steamLogin"].Value.Equals("deleted");
}
}
/// <summary>
/// Method to submit cookies to Steam after Login.
/// </summary>
/// <param name="cookies">Cookiecontainer which contains cookies after the login to Steam.</param>
static void SubmitCookies (CookieContainer cookies)
{
HttpWebRequest w = WebRequest.Create("https://steamcommunity.com/") as HttpWebRequest;
// Check, if the request is null.
if (w == null)
{
return;
}
w.Method = "POST";
w.ContentType = "application/x-www-form-urlencoded";
w.CookieContainer = cookies;
// Added content-length because it is required.
w.ContentLength = 0;
w.GetResponse().Close();
}
/// <summary>
/// Method to convert a Hex to a byte.
/// </summary>
/// <param name="hex">Input parameter as string.</param>
/// <returns>The byte value.</returns>
private byte[] HexToByte(string hex)
{
if (hex.Length % 2 == 1)
{
throw new Exception("The binary key cannot have an odd number of digits");
}
byte[] arr = new byte[hex.Length >> 1];
int l = hex.Length;
for (int i = 0; i < (l >> 1); ++i)
{
arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
/// <summary>
/// Get the Hex value as int out of an char.
/// </summary>
/// <param name="hex">Input parameter.</param>
/// <returns>A Hex Value as int.</returns>
private int GetHexVal(char hex)
{
int val = hex;
return val - (val < 58 ? 48 : 55);
}
/// <summary>
/// Method to allow all certificates.
/// </summary>
/// <param name="sender">An object that contains state information for this validation.</param>
/// <param name="certificate">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
/// <param name="policyErrors">One or more errors associated with the remote certificate.</param>
/// <returns>Always true to accept all certificates.</returns>
public bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors)
{
return true;
}
}
// JSON Classes
// These classes are used to deserialize response strings from the login:
// Example of a return string: {"success":true,"publickey_mod":"XXXX87144BF5B2CABFEC24E35655FDC5E438D6064E47D33A3531F3AAB195813E316A5D8AAB1D8A71CB7F031F801200377E8399C475C99CBAFAEFF5B24AE3CF64BXXXXB2FDBA3BC3974D6DCF1E760F8030AB5AB40FA8B9D193A8BEB43AA7260482EAD5CE429F718ED06B0C1F7E063FE81D4234188657DB40EEA4FAF8615111CD3E14CAF536CXXXX3C104BE060A342BF0C9F53BAAA2A4747E43349FF0518F8920664F6E6F09FE41D8D79C884F8FD037276DED0D1D1D540A2C2B6639CF97FF5180E3E75224EXXXX56AAA864EEBF9E8B35B80E25B405597219BFD90F3AD9765D81D148B9500F12519F1F96828C12AEF77D948D0DC9FDAF8C7CC73527ADE7C7F0FF33","publickey_exp":"010001","timestamp":"241590850000","steamid":"7656119824534XXXX","token_gid":"c35434c0c07XXXX"}
/// <summary>
/// Class to Deserialize the json response strings of the getResKey request. See: <see cref="SteamWeb.DoLogin"/>
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class GetRsaKey
{
public bool success { get; set; }
public string publickey_mod { get; set; }
public string publickey_exp { get; set; }
public string timestamp { get; set; }
}
// Examples:
// For not accepted SteamResult:
// {"success":false,"requires_twofactor":false,"message":"","emailauth_needed":true,"emaildomain":"gmail.com","emailsteamid":"7656119824534XXXX"}
// For accepted SteamResult:
// {"success":true,"requires_twofactor":false,"login_complete":true,"transfer_url":"https:\/\/store.steampowered.com\/login\/transfer","transfer_parameters":{"steamid":"7656119824534XXXX","token":"XXXXC39589A9XXXXCB60D651EFXXXX85578AXXXX","auth":"XXXXf1d9683eXXXXc76bdc1888XXXX29","remember_login":false,"webcookie":"XXXX4C33779A4265EXXXXC039D3512DA6B889D2F","token_secure":"XXXX63F43AA2CXXXXC703441A312E1B14AC2XXXX"}}
/// <summary>
/// Class to Deserialize the json response strings after the login. See: <see cref="SteamWeb.DoLogin"/>
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class SteamResult
{
public bool success { get; set; }
public string message { get; set; }
public bool captcha_needed { get; set; }
public string captcha_gid { get; set; }
public bool emailauth_needed { get; set; }
public string emailsteamid { get; set; }
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/24/2009 9:10:23 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;
using System;
using System.Collections.Generic;
namespace DotSpatial.Projections
{
/// <summary>
/// Contains methods for reprojection.
/// </summary>
public static class Reproject
{
#region Private Variables
private const double EPS = 1E-12;
#endregion
#region Methods
/// <summary>
/// This method reprojects the affine transform coefficients. This is used for projection on the fly,
/// where image transforms can take advantage of an affine projection, but does not have the power of
/// a full projective transform and gets less and less accurate as the image covers larger and larger
/// areas. Since most image layers represent small rectangular areas, this should not be a problem in
/// most cases. the affine array should be ordered as follows:
/// X' = [0] + [1] * Column + [2] * Row
/// Y' = [3] + [4] * Column + [5] * Row
/// </summary>
/// <param name="affine">The array of double affine coefficients.</param>
/// <param name="numRows">The number of rows to use for the lower bounds. Value of 0 or less will be set to 1.</param>
/// <param name="numCols">The number of columns to use to get the right bounds. Values of 0 or less will be set to 1.</param>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <returns>The transformed coefficients</returns>
public static double[] ReprojectAffine(double[] affine, double numRows, double numCols, ProjectionInfo source, ProjectionInfo dest)
{
if (numRows <= 0) numRows = 1;
if (numCols <= 0) numCols = 1;
double[] vertices = new double[6];
// Top left
vertices[0] = affine[0];
vertices[1] = affine[3];
// Top right
vertices[2] = affine[0] + affine[1] * numCols;
vertices[3] = affine[3] + affine[4] * numCols;
// Bottom Left
vertices[4] = affine[0] + affine[2] * numRows;
vertices[5] = affine[3] + affine[5] * numRows;
double[] z = new double[3];
ReprojectPoints(vertices, z, source, dest, 0, 3);
double[] affineResult = new double[6];
affineResult[0] = vertices[0];
affineResult[1] = (vertices[2] - vertices[0]) / numCols;
affineResult[2] = (vertices[4] - vertices[0]) / numRows;
affineResult[3] = vertices[1];
affineResult[4] = (vertices[3] - vertices[1]) / numCols;
affineResult[5] = (vertices[5] - vertices[1]) / numRows;
return affineResult;
}
public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, ProjectionInfo dest, int startIndex, int numPoints)
{
ReprojectPoints(xy, z, source, 1.0, dest, 1.0, null, startIndex, numPoints);
}
public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, double srcZtoMeter, ProjectionInfo dest, double dstZtoMeter, IDatumTransform idt, int startIndex, int numPoints)
{
double toMeter = source.Unit.Meters;
if (source.Transform.Rotated && source.Transform.Angle != 0)
{
double cosAngle = Math.Cos(Math.PI * source.Transform.Angle / 180.0);
double sinAngle = Math.Sin(Math.PI * source.Transform.Angle / 180.0);
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int x = i * 2;
int y = i * 2 + 1;
double x1 = cosAngle * xy[x] - sinAngle * xy[y];
double y1 = sinAngle * xy[x] + cosAngle * xy[y];
xy[x] = x1;
xy[y] = y1;
}
}
// Geocentric coordinates are centered at the core of the earth. Z is up toward the north pole.
// The X axis goes from the center of the earth through Greenwich.
// The Y axis passes through 90E.
// This section converts from geocentric coordinates to geodetic ones if necessary.
if (source.IsGeocentric)
{
if (z == null)
{
throw new ProjectionException(45);
}
for (int i = startIndex; i < numPoints; i++)
{
if (toMeter != 1)
{
xy[i * 2] *= toMeter;
xy[i * 2 + 1] *= toMeter;
}
}
GeocentricGeodetic g = new GeocentricGeodetic(source.GeographicInfo.Datum.Spheroid);
g.GeocentricToGeodetic(xy, z, startIndex, numPoints);
}
// Transform source points to lam/phi if they are not already
ConvertToLatLon(source, xy, z, srcZtoMeter, startIndex, numPoints);
double fromGreenwich = source.GeographicInfo.Meridian.Longitude * source.GeographicInfo.Unit.Radians;
if (fromGreenwich != 0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[2 * i] != double.PositiveInfinity)
xy[2 * i] += fromGreenwich;
}
}
// DATUM TRANSFORM IF NEEDED
if (idt == null)
{
if (!source.GeographicInfo.Datum.Matches(dest.GeographicInfo.Datum))
{
DatumTransform(source, dest, xy, z, startIndex, numPoints);
}
}
else
{
idt.Transform(source, dest, xy, z, startIndex, numPoints);
}
// Adjust to new prime meridian if there is one in the destination cs
fromGreenwich = dest.GeographicInfo.Meridian.Longitude * dest.GeographicInfo.Unit.Radians;
if (fromGreenwich != 0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] != double.PositiveInfinity)
{
xy[i * 2] -= fromGreenwich;
}
}
}
if (dest.IsGeocentric)
{
if (z == null)
{
throw new ProjectionException(45);
}
GeocentricGeodetic g = new GeocentricGeodetic(dest.GeographicInfo.Datum.Spheroid);
g.GeodeticToGeocentric(xy, z, startIndex, numPoints);
double frmMeter = 1 / dest.Unit.Meters;
if (frmMeter != 1)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] != double.PositiveInfinity)
{
xy[i * 2] *= frmMeter;
xy[i * 2 + 1] *= frmMeter;
}
}
}
}
else
{
ConvertToProjected(dest, xy, z, dstZtoMeter, startIndex, numPoints);
if (dest.Transform.Rotated && dest.Transform.Angle != 0)
{
double cosAngle = Math.Cos(-Math.PI * dest.Transform.Angle / 180.0);
double sinAngle = Math.Sin(-Math.PI * dest.Transform.Angle / 180.0);
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int x = i * 2;
int y = i * 2 + 1;
double x1 = cosAngle * xy[x] - sinAngle * xy[y];
double y1 = sinAngle * xy[x] + cosAngle * xy[y];
xy[x] = x1;
xy[y] = y1;
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="geom"></param>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <returns></returns>
public static IGeometry ReprojectGeometry(IGeometry geom, ProjectionInfo source, ProjectionInfo dest)
{
if (geom is IGeometryCollection)
{
IGeometryCollection iGeomColl = geom as IGeometryCollection;
List<IGeometry> lGeom = new List<IGeometry>();
foreach (IGeometry iGeom in iGeomColl.Geometries)
lGeom.Add(ReprojectGeometry(iGeom, source, dest));
if (geom is IMultiLineString)
return geom.Factory.CreateMultiLineString(Array.ConvertAll(lGeom.ToArray(), item => (ILineString)item));
if (geom is IMultiPolygon)
return geom.Factory.CreateMultiPolygon(Array.ConvertAll(lGeom.ToArray(), item => (IPolygon)item));
if (geom is IMultiPoint)
return geom.Factory.CreateMultiPoint(Array.ConvertAll(lGeom.ToArray(), item => (IPoint)item));
return geom.Factory.CreateGeometryCollection(lGeom.ToArray());
}
Coordinate[] listCoord = geom.Coordinates;
int iSize = listCoord.Length;
double[] xy = new double[iSize * 2];
int iIndex = 0;
for (int i = 0; i < iSize; i++)
{
xy[iIndex++] = listCoord[i].X;
xy[iIndex++] = listCoord[i].Y;
}
ReprojectPoints(xy, null, source, dest, 0, geom.Coordinates.Length);
IGeometry newGeom = geom.Clone() as IGeometry;
listCoord = newGeom.Coordinates;
iIndex = 0;
for (int i = 0; i < iSize; i++)
{
listCoord[i].X = xy[iIndex++];
listCoord[i].Y = xy[iIndex++];
}
ICoordinateSequence iCoordSeq = geom.Factory.CoordinateSequenceFactory.Create(listCoord);
if (geom is IPoint)
return geom.Factory.CreatePoint(iCoordSeq);
if (geom is ILinearRing)
return geom.Factory.CreateLinearRing(iCoordSeq);
if (geom is ILineString)
return geom.Factory.CreateLineString(iCoordSeq);
if (geom is IPolygon)
return geom.Factory.CreatePolygon(iCoordSeq);
return null;
}
private static void ConvertToProjected(ProjectionInfo dest, double[] xy, double[] z, double dstZtoMeter, int startIndex, int numPoints)
{
double frmMeter = 1 / dest.Unit.Meters;
double frmZMeter = 1 / dstZtoMeter;
bool geoc = dest.Geoc;
double lam0 = dest.Lam0;
double roneEs = 1 / (1 - dest.GeographicInfo.Datum.Spheroid.EccentricitySquared());
bool over = dest.Over;
double x0 = 0;
double y0 = 0;
if (dest.FalseEasting.HasValue) x0 = dest.FalseEasting.Value;
if (dest.FalseNorthing.HasValue) y0 = dest.FalseNorthing.Value;
double a = dest.GeographicInfo.Datum.Spheroid.EquatorialRadius;
for (int i = startIndex; i < numPoints; i++)
{
double lam = xy[2 * i];
double phi = xy[2 * i + 1];
double t = Math.Abs(phi) - Math.PI / 2;
if (t > EPS || Math.Abs(lam) > 10)
{
xy[2 * i] = double.PositiveInfinity;
xy[2 * i + 1] = double.PositiveInfinity;
continue;
}
if (Math.Abs(t) <= EPS)
{
xy[2 * i + 1] = phi < 0 ? -Math.PI / 2 : Math.PI / 2;
}
else if (geoc)
{
xy[2 * i + 1] = Math.Atan(roneEs * Math.Tan(phi));
}
xy[2 * i] -= lam0;
if (!over)
{
xy[2 * i] = Adjlon(xy[2 * i]);
}
}
// break this out because we don't want a chatty call to extension transforms
// CGX
if (dest.Transform != null)
{
dest.Transform.Forward(xy, startIndex, numPoints);
if (dstZtoMeter == 1.0)
{
for (int i = startIndex; i < numPoints; i++)
{
xy[2 * i] = frmMeter * (a * xy[2 * i] + x0);
xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
xy[2 * i] = frmMeter * (a * xy[2 * i] + x0);
xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
z[i] *= frmZMeter;
}
}
}
}
private static void DatumTransform(ProjectionInfo source, ProjectionInfo dest, double[] xy, double[] z, int startIndex, int numPoints)
{
Spheroid wgs84 = new Spheroid(Proj4Ellipsoid.WGS_1984);
Datum sDatum = source.GeographicInfo.Datum;
Datum dDatum = dest.GeographicInfo.Datum;
/* -------------------------------------------------------------------- */
/* We cannot do any meaningful datum transformation if either */
/* the source or destination are of an unknown datum type */
/* (ie. only a +ellps declaration, no +datum). This is new */
/* behavior for PROJ 4.6.0. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.Unknown ||
dDatum.DatumType == DatumType.Unknown) return;
/* -------------------------------------------------------------------- */
/* Short cut if the datums are identical. */
/* -------------------------------------------------------------------- */
if (sDatum.Matches(dDatum)) return;
// proj4 actually allows some tollerance here
if (sDatum.DatumType == dDatum.DatumType)
{
if (sDatum.Spheroid.EquatorialRadius == dDatum.Spheroid.EquatorialRadius)
{
if (Math.Abs(sDatum.Spheroid.EccentricitySquared() - dDatum.Spheroid.EccentricitySquared()) < 0.000000000050)
{
// The tolerence is to allow GRS80 and WGS84 to escape without being transformed at all.
return;
}
}
}
double srcA = sDatum.Spheroid.EquatorialRadius;
double srcEs = sDatum.Spheroid.EccentricitySquared();
double dstA = dDatum.Spheroid.EquatorialRadius;
double dstEs = dDatum.Spheroid.EccentricitySquared();
/* -------------------------------------------------------------------- */
/* Create a temporary Z value if one is not provided. */
/* -------------------------------------------------------------------- */
if (z == null)
{
z = new double[xy.Length / 2];
}
/* -------------------------------------------------------------------- */
/* If this datum requires grid shifts, then apply it to geodetic */
/* coordinates. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.GridShift)
{
// pj_apply_gridshift(pj_param(srcdefn->params,"snadgrids").s, 0,
// point_count, point_offset, x, y, z );
GridShift.Apply(source.GeographicInfo.Datum.NadGrids, false, xy, startIndex, numPoints);
srcA = wgs84.EquatorialRadius;
srcEs = wgs84.EccentricitySquared();
}
if (dDatum.DatumType == DatumType.GridShift)
{
dstA = wgs84.EquatorialRadius;
dstEs = wgs84.EccentricitySquared();
}
/* ==================================================================== */
/* Do we need to go through geocentric coordinates? */
/* ==================================================================== */
if (srcEs != dstEs || srcA != dstA
|| sDatum.DatumType == DatumType.Param3
|| sDatum.DatumType == DatumType.Param7
|| dDatum.DatumType == DatumType.Param3
|| dDatum.DatumType == DatumType.Param7)
{
/* -------------------------------------------------------------------- */
/* Convert to geocentric coordinates. */
/* -------------------------------------------------------------------- */
GeocentricGeodetic gc = new GeocentricGeodetic(sDatum.Spheroid);
gc.GeodeticToGeocentric(xy, z, startIndex, numPoints);
/* -------------------------------------------------------------------- */
/* Convert between datums. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.Param3 || sDatum.DatumType == DatumType.Param7)
{
PjGeocentricToWgs84(source, xy, z, startIndex, numPoints);
}
if (dDatum.DatumType == DatumType.Param3 || dDatum.DatumType == DatumType.Param7)
{
PjGeocentricFromWgs84(dest, xy, z, startIndex, numPoints);
}
/* -------------------------------------------------------------------- */
/* Convert back to geodetic coordinates. */
/* -------------------------------------------------------------------- */
gc = new GeocentricGeodetic(dDatum.Spheroid);
gc.GeocentricToGeodetic(xy, z, startIndex, numPoints);
}
/* -------------------------------------------------------------------- */
/* Apply grid shift to destination if required. */
/* -------------------------------------------------------------------- */
if (dDatum.DatumType == DatumType.GridShift)
{
// pj_apply_gridshift(pj_param(dstdefn->params,"snadgrids").s, 1,
// point_count, point_offset, x, y, z );
GridShift.Apply(dest.GeographicInfo.Datum.NadGrids, true, xy, startIndex, numPoints);
}
}
private static void ConvertToLatLon(ProjectionInfo source, double[] xy, double[] z, double srcZtoMeter, int startIndex, int numPoints)
{
double toMeter = 1.0;
if (source.Unit != null) toMeter = source.Unit.Meters;
double oneEs = 1 - source.GeographicInfo.Datum.Spheroid.EccentricitySquared();
double ra = 1 / source.GeographicInfo.Datum.Spheroid.EquatorialRadius;
double x0 = 0;
if (source.FalseEasting != null) x0 = source.FalseEasting.Value;
double y0 = 0;
if (source.FalseNorthing != null) y0 = source.FalseNorthing.Value;
if (srcZtoMeter == 1.0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
{
// This might be error worthy, but not sure if we want to throw an exception here
continue;
}
// descale and de-offset
xy[i * 2] = (xy[i * 2] * toMeter - x0) * ra;
xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
{
// This might be error worthy, but not sure if we want to throw an exception here
continue;
}
// descale and de-offset
xy[i * 2] = (xy[i * 2] * toMeter - x0) * ra;
xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
z[i] *= srcZtoMeter;
}
}
if (source.Transform != null)
{
source.Transform.Inverse(xy, startIndex, numPoints);
}
for (int i = startIndex; i < numPoints; i++)
{
double lam0 = source.Lam0;
xy[i * 2] += lam0;
if (!source.Over)
{
xy[i*2] = Adjlon(xy[i*2]);
}
if (source.Geoc && Math.Abs(Math.Abs(xy[i * 2 + 1]) - Math.PI / 2) > EPS)
{
xy[i * 2 + 1] = Math.Atan(oneEs * Math.Tan(xy[i * 2 + 1]));
}
}
}
private static double Adjlon(double lon)
{
if (Math.Abs(lon) <= Math.PI + Math.PI / 72) return (lon);
lon += Math.PI; /* adjust to 0..2pi rad */
lon -= 2 * Math.PI * Math.Floor(lon / (2 * Math.PI)); /* remove integral # of 'revolutions'*/
lon -= Math.PI; /* adjust back to -pi..pi rad */
return (lon);
}
private static void PjGeocentricToWgs84(ProjectionInfo source, double[] xy, double[] zArr, int startIndex, int numPoints)
{
double[] shift = source.GeographicInfo.Datum.ToWGS84;
if (source.GeographicInfo.Datum.DatumType == DatumType.Param3)
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
xy[2 * i] = xy[2 * i] + shift[0]; // dx
xy[2 * i + 1] = xy[2 * i + 1] + shift[1]; // dy
zArr[i] = zArr[i] + shift[2];
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
double x = xy[2 * i];
double y = xy[2 * i + 1];
double z = zArr[i];
xy[2 * i] = shift[6] * (x - shift[5] * y + shift[4] * z) + shift[0];
xy[2 * i + 1] = shift[6] * (shift[5] * x + y - shift[3] * z) + shift[1];
zArr[i] = shift[6] * (-shift[4] * x + shift[3] * y + z) + shift[2];
}
}
}
private static void PjGeocentricFromWgs84(ProjectionInfo dest, double[] xy, double[] zArr, int startIndex, int numPoints)
{
double[] shift = dest.GeographicInfo.Datum.ToWGS84;
if (dest.GeographicInfo.Datum.DatumType == DatumType.Param3)
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
xy[2 * i] = xy[2 * i] - shift[0]; // dx
xy[2 * i + 1] = xy[2 * i + 1] - shift[1]; // dy
zArr[i] = zArr[i] - shift[2];
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
double x = (xy[2 * i] - shift[0]) / shift[6];
double y = (xy[2 * i + 1] - shift[1]) / shift[6];
double z = (zArr[i] - shift[2]) / shift[6];
xy[2 * i] = x + shift[5] * y - shift[4] * z;
xy[2 * i + 1] = -shift[5] * x + y + shift[3] * z;
zArr[i] = shift[4] * x - shift[3] * y + z;
}
}
}
#endregion
}
}
| |
/*
This file is licensed 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 System.Collections.Generic;
using System.Linq;
using System.Xml;
using NUnit.Framework.Constraints;
using Org.XmlUnit.Builder;
using Org.XmlUnit.Diff;
namespace Org.XmlUnit.Constraints {
/// <summary>
/// Constraint that compares two XML sources with each other.
/// </summary>
public class CompareConstraint : Constraint, IDifferenceEngineConfigurer<CompareConstraint> {
private readonly DiffBuilder diffBuilder;
private ComparisonResult checkFor;
private Org.XmlUnit.Diff.Diff diffResult;
private bool formatXml;
private IComparisonFormatter comparisonFormatter = new DefaultComparisonFormatter();
private CompareConstraint(object control) {
diffBuilder = DiffBuilder.Compare(control);
}
/// <summary>
/// Create a CompareConstraint which compares the
/// test-Object with the given control Object for identity.
/// </summary>
public static CompareConstraint IsIdenticalTo(object control) {
return new CompareConstraint(control).CheckForIdentical();
}
/// <summary>
/// Create a CompareConstraint which compares the
/// test-Object with the given control Object for similarity.
/// </summary>
/// <remarks>
/// <para>
/// Example for Similar: The XML node
/// "<a>Text</a>" and
/// "<a><![CDATA[Text]]></a>" are
/// similar and the Test will not fail.
/// </para>
/// </remarks>
public static CompareConstraint IsSimilarTo(object control) {
return new CompareConstraint(control).CheckForSimilar();
}
private CompareConstraint CheckForSimilar() {
diffBuilder.CheckForSimilar();
checkFor = ComparisonResult.SIMILAR;
return this;
}
private CompareConstraint CheckForIdentical() {
diffBuilder.CheckForIdentical();
checkFor = ComparisonResult.EQUAL;
return this;
}
/// <summary>
/// Ignore whitespace differences.
/// </summary>
public CompareConstraint IgnoreWhitespace() {
formatXml = true;
diffBuilder.IgnoreWhitespace();
return this;
}
/// <summary>
/// Ignore element content whitespace differences.
/// </summary>
/// <remarks>
/// <para>
/// since XMLUnit 2.6.0
/// </para>
/// </remarks>
public CompareConstraint IgnoreElementContentWhitespace() {
diffBuilder.IgnoreElementContentWhitespace();
return this;
}
/// <summary>
/// Normalize whitespace before comparing.
/// </summary>
public CompareConstraint NormalizeWhitespace() {
formatXml = true;
diffBuilder.NormalizeWhitespace();
return this;
}
/// <summary>
/// Ignore comments.
/// </summary>
public CompareConstraint IgnoreComments()
{
diffBuilder.IgnoreComments();
return this;
}
/// <summary>
/// Ignore comments.
/// </summary>
/// <remarks>
/// <para>
/// since XMLUnit 2.5.0
/// </para>
/// </remarks>
/// <param name="xsltVersion">use this version for the stylesheet</param>
public CompareConstraint IgnoreCommentsUsingXSLTVersion(string xsltVersion)
{
diffBuilder.IgnoreCommentsUsingXSLTVersion(xsltVersion);
return this;
}
/// <summary>
/// Use the given <see cref="INodeMatcher"/> when comparing.
/// </summary>
/// <param name="nodeMatcher">INodeMatcher to use</param>
public CompareConstraint WithNodeMatcher(INodeMatcher nodeMatcher) {
diffBuilder.WithNodeMatcher(nodeMatcher);
return this;
}
/// <summary>
/// Use the given <see cref="DifferenceEvaluator"/> when comparing.
/// </summary>
/// <param name="differenceEvaluator">DifferenceEvaluator to use</param>
public CompareConstraint WithDifferenceEvaluator(DifferenceEvaluator differenceEvaluator)
{
diffBuilder.WithDifferenceEvaluator(differenceEvaluator);
return this;
}
/// <summary>
/// Use the given <see cref="ComparisonListener"/>s when comparing.
/// </summary>
/// <param name="comparisonListeners">ComparisonListeners to use</param>
public CompareConstraint WithComparisonListeners(params ComparisonListener[] comparisonListeners)
{
diffBuilder.WithComparisonListeners(comparisonListeners);
return this;
}
/// <summary>
/// Use the given <see cref="ComparisonListener"/>s as difference listeners when comparing.
/// </summary>
/// <param name="comparisonListeners">ComparisonListeners to use</param>
public CompareConstraint WithDifferenceListeners(params ComparisonListener[] comparisonListeners)
{
diffBuilder.WithDifferenceListeners(comparisonListeners);
return this;
}
/// <summary>
/// Use a custom Formatter for the Error Messages. The defaultFormatter is DefaultComparisonFormatter.
/// </summary>
public CompareConstraint WithComparisonFormatter(IComparisonFormatter comparisonFormatter) {
this.comparisonFormatter = comparisonFormatter;
return this;
}
/// <summary>
/// Registers a filter for attributes.
/// </summary>
/// <remarks>
/// <para>
/// Only attributes for which the predicate returns true are
/// part of the comparison. By default all attributes are
/// considered.
/// </para>
/// <para>
/// The "special" namespace, namespace-location and
/// schema-instance-type attributes can not be ignored this way.
/// If you want to suppress comparison of them you'll need to
/// implement <see cref="DifferenceEvaluator"/>
/// </para>
/// </remarks>
public CompareConstraint WithAttributeFilter(Predicate<XmlAttribute> attributeFilter) {
diffBuilder.WithAttributeFilter(attributeFilter);
return this;
}
/// <summary>
/// Registers a filter for nodes.
/// </summary>
/// <remarks>
/// <para>
/// Only nodes for which the predicate returns true are part
/// of the comparison. By default nodes that are neither
/// document types nor XML declarations are considered.
/// </para>
/// </remarks>
public CompareConstraint WithNodeFilter(Predicate<XmlNode> nodeFilter) {
diffBuilder.WithNodeFilter(nodeFilter);
return this;
}
/// <summary>
/// Establish a namespace context mapping from prefix to URI
/// that will be used in Comparison.Detail.XPath.
/// </summary>
/// <remarks>
/// Without a namespace context (or with an empty context) the
/// XPath expressions will only use local names for elements and
/// attributes.
/// </remarks>
public CompareConstraint WithNamespaceContext(IDictionary<string, string> ctx) {
diffBuilder.WithNamespaceContext(ctx);
return this;
}
/// <summary>
/// Throws an exception as you the ComparisonController is
/// completely determined by the factory method used.
/// </summary>
/// <remarks>
/// <para>
/// since XMLUnit 2.5.1
/// </para>
/// </remarks>
public CompareConstraint WithComparisonController(ComparisonController cc)
{
throw new NotImplementedException("Can't set ComparisonController with CompareConstraint");
}
/// <inheritdoc/>
public override bool Matches(object o) {
actual = o;
if (checkFor == ComparisonResult.EQUAL) {
diffBuilder.WithComparisonController(ComparisonControllers.StopWhenSimilar);
} else if (checkFor == ComparisonResult.SIMILAR) {
diffBuilder.WithComparisonController(ComparisonControllers.StopWhenDifferent);
}
diffResult = diffBuilder.WithTest(o).Build();
return !diffResult.HasDifferences();
}
/// <inheritdoc/>
public override void WriteDescriptionTo(MessageWriter writer)
{
string identicalOrSimilar = checkFor == ComparisonResult.EQUAL ? "identical" : "similar";
if (diffResult == null || !diffResult.HasDifferences()) {
writer.Write("is {0} to the control document", identicalOrSimilar);
} else {
writer.Write("{0} is {1} to {2}", diffResult.TestSource.SystemId,
identicalOrSimilar,
diffResult.ControlSource.SystemId);
}
}
/// <inheritdoc/>
public override void WriteMessageTo(MessageWriter writer)
{
Comparison c = diffResult.Differences.First().Comparison;
writer.WriteMessageLine(comparisonFormatter.GetDescription(c));
if (diffResult.TestSource.SystemId != null
|| diffResult.ControlSource.SystemId != null) {
writer.WriteMessageLine(string.Format("comparing {0} to {1}",
diffResult.TestSource.SystemId,
diffResult.ControlSource.SystemId));
}
writer.DisplayDifferences(GetDetails(c.ControlDetails, c.Type),
GetDetails(c.TestDetails, c.Type));
}
private string GetDetails(Comparison.Detail detail, ComparisonType type) {
return comparisonFormatter.GetDetails(detail, type, formatXml);
}
}
}
| |
using System;
using Server.Items;
using Server.Targeting;
using Server.Events.Halloween;
using Server.Mobiles;
using System.Collections.Generic;
namespace Server.Engines.Events
{
public class TrickOrTreat
{
public static TimeSpan OneSecond = TimeSpan.FromSeconds( 1 );
public static void Initialize()
{
DateTime now = DateTime.Now;
if( DateTime.Now >= HolidaySettings.StartHalloween && DateTime.Now <= HolidaySettings.FinishHalloween )
{
EventSink.Speech += new SpeechEventHandler( EventSink_Speech );
}
}
private static void EventSink_Speech( SpeechEventArgs e )
{
if( Insensitive.Contains( e.Speech, "trick or treat" ) )
{
e.Mobile.Target = new TrickOrTreatTarget();
e.Mobile.SendLocalizedMessage( 1076764 ); /* Pick someone to Trick or Treat. */
}
}
private class TrickOrTreatTarget : Target
{
public TrickOrTreatTarget()
: base( 15, false, TargetFlags.None )
{
}
protected override void OnTarget( Mobile from, object targ )
{
if( targ != null && CheckMobile( from ) )
{
if( !( targ is Mobile ) )
{
from.SendLocalizedMessage( 1076781 ); /* There is little chance of getting candy from that! */
return;
}
if( !( targ is BaseVendor ) || ( ( BaseVendor )targ ).Deleted )
{
from.SendLocalizedMessage( 1076765 ); /* That doesn't look friendly. */
return;
}
DateTime now = DateTime.Now;
BaseVendor m_Begged = targ as BaseVendor;
if( CheckMobile( m_Begged ) )
{
if( m_Begged.NextTrickOrTreat > now )
{
from.SendLocalizedMessage( 1076767 ); /* That doesn't appear to have any more candy. */
return;
}
m_Begged.NextTrickOrTreat = now + TimeSpan.FromMinutes( Utility.RandomMinMax( 5, 10 ) );
if( from.Backpack != null && !from.Backpack.Deleted )
{
if( Utility.RandomDouble() > .10 )
{
switch( Utility.Random( 3 ) )
{
case 0: m_Begged.Say( 1076768 ); break; /* Oooooh, aren't you cute! */
case 1: m_Begged.Say( 1076779 ); break; /* All right...This better not spoil your dinner! */
case 2: m_Begged.Say( 1076778 ); break; /* Here you go! Enjoy! */
default: break;
}
if( Utility.RandomDouble() <= .01 && from.Skills.Begging.Value >= 100 )
{
from.AddToBackpack( HolidaySettings.RandomGMBeggerItem );
from.SendLocalizedMessage( 1076777 ); /* You receive a special treat! */
}
else
{
from.AddToBackpack( HolidaySettings.RandomTreat );
from.SendLocalizedMessage( 1076769 ); /* You receive some candy. */
}
}
else
{
m_Begged.Say( 1076770 ); /* TRICK! */
int m_Action = Utility.Random( 4 );
if( m_Action == 0 )
{
Timer.DelayCall<Mobile>( OneSecond, OneSecond, 10, new TimerStateCallback<Mobile>( Bleeding ), from );
}
else if( m_Action == 1 )
{
Timer.DelayCall<Mobile>( TimeSpan.FromSeconds( 2 ), new TimerStateCallback<Mobile>( SolidHueMobile ), from );
}
else
{
Timer.DelayCall<Mobile>( TimeSpan.FromSeconds( 2 ), new TimerStateCallback<Mobile>( MakeTwin ), from );
}
}
}
}
}
}
}
public static void Bleeding( Mobile m_From )
{
if( TrickOrTreat.CheckMobile( m_From ) )
{
if( m_From.Location != Point3D.Zero )
{
int amount = Utility.RandomMinMax( 3, 7 );
for( int i = 0; i < amount; i++ )
{
new Blood( Utility.RandomMinMax( 0x122C, 0x122F ) ).MoveToWorld( RandomPointOneAway( m_From.X, m_From.Y, m_From.Z, m_From.Map ), m_From.Map );
}
}
}
}
public static void RemoveHueMod( Mobile target )
{
if( target != null && !target.Deleted )
{
target.SolidHueOverride = -1;
}
}
public static void SolidHueMobile( Mobile target )
{
if( CheckMobile( target ) )
{
target.SolidHueOverride = Utility.RandomMinMax( 2501, 2644 );
Timer.DelayCall<Mobile>( TimeSpan.FromSeconds( 10 ), new TimerStateCallback<Mobile>( RemoveHueMod ), target );
}
}
public static void MakeTwin( Mobile m_From )
{
List<Item> m_Items = new List<Item>();
if( CheckMobile( m_From ) )
{
Mobile twin = new NaughtyTwin( m_From );
if( twin != null && !twin.Deleted )
{
foreach( Item item in m_From.Items )
{
if( item.Layer != Layer.Backpack && item.Layer != Layer.Mount && item.Layer != Layer.Bank )
{
m_Items.Add( item );
}
}
if( m_Items.Count > 0 )
{
for( int i = 0; i < m_Items.Count; i++ ) /* dupe exploits start out like this ... */
{
twin.AddItem( Mobile.LiftItemDupe( m_Items[ i ], 1 ) );
}
foreach( Item item in twin.Items ) /* ... and end like this */
{
if( item.Layer != Layer.Backpack && item.Layer != Layer.Mount && item.Layer != Layer.Bank )
{
item.Movable = false;
}
}
}
twin.Hue = m_From.Hue;
twin.BodyValue = m_From.BodyValue;
twin.Kills = m_From.Kills;
Point3D point = RandomPointOneAway( m_From.X, m_From.Y, m_From.Z, m_From.Map );
twin.MoveToWorld( m_From.Map.CanSpawnMobile( point ) ? point : m_From.Location, m_From.Map );
Timer.DelayCall( TimeSpan.FromSeconds( 5 ), new TimerStateCallback<Mobile>( DeleteTwin ), twin );
}
}
}
public static void DeleteTwin( Mobile m_Twin )
{
if( TrickOrTreat.CheckMobile( m_Twin ) )
{
m_Twin.Delete();
}
}
public static Point3D RandomPointOneAway( int x, int y, int z, Map map )
{
Point3D loc = new Point3D( x + Utility.Random( -1, 3 ), y + Utility.Random( -1, 3 ), 0 );
loc.Z = ( map.CanFit( loc, 0 )) ? map.GetAverageZ( loc.X, loc.Y ) : z;
return loc;
}
public static bool CheckMobile( Mobile mobile )
{
return ( mobile != null && mobile.Map != null && !mobile.Deleted && mobile.Alive && mobile.Map != Map.Internal );
}
}
public class NaughtyTwin : BaseCreature
{
private Mobile m_From;
private static Point3D[] Felucca_Locations =
{
new Point3D( 4467, 1283, 5 ), // Moonglow
new Point3D( 1336, 1997, 5 ), // Britain
new Point3D( 1499, 3771, 5 ), // Jhelom
new Point3D( 771, 752, 5 ), // Yew
new Point3D( 2701, 692, 5 ), // Minoc
new Point3D( 1828, 2948,-20), // Trinsic
new Point3D( 643, 2067, 5 ), // Skara Brae
new Point3D( 3563, 2139, Map.Trammel.GetAverageZ( 3563, 2139 ) ), // (New) Magincia
};
private static Point3D[] Malas_Locations =
{
new Point3D(1015, 527, -65), // Luna
new Point3D(1997, 1386, -85) // Umbra
};
private static Point3D[] Ilshenar_Locations =
{
new Point3D( 1215, 467, -13 ), // Compassion
new Point3D( 722, 1366, -60 ), // Honesty
new Point3D( 744, 724, -28 ), // Honor
new Point3D( 281, 1016, 0 ), // Humility
new Point3D( 987, 1011, -32 ), // Justice
new Point3D( 1174, 1286, -30 ), // Sacrifice
new Point3D( 1532, 1340, - 3 ), // Spirituality
new Point3D( 528, 216, -45 ), // Valor
new Point3D( 1721, 218, 96 ) // Chaos
};
private static Point3D[] Tokuno_Locations =
{
new Point3D( 1169, 998, 41 ), // Isamu-Jima
new Point3D( 802, 1204, 25 ), // Makoto-Jima
new Point3D( 270, 628, 15 ) // Homare-Jima
};
public NaughtyTwin( Mobile from )
: base( AIType.AI_Melee, FightMode.None, 10, 1, 0.2, 0.4 )
{
if( TrickOrTreat.CheckMobile( from ) )
{
Body = from.Body;
m_From = from;
Name = String.Format( "{0}\'s Naughty Twin", from.Name );
Timer.DelayCall<Mobile>( TrickOrTreat.OneSecond, Utility.RandomBool() ? new TimerStateCallback<Mobile>( StealCandy ) : new TimerStateCallback<Mobile>( ToGate ), m_From );
}
}
public override void OnThink()
{
if( m_From == null || m_From.Deleted )
{
Delete();
}
}
public static Item FindCandyTypes( Mobile target )
{
Type[] types = { typeof(WrappedCandy), typeof(RedLollipop), typeof(GreenLollipop), typeof(YellowLollipop), typeof(RedCandyCane), typeof(GreenCandyCane), typeof(Jellybeans), typeof(Nougat)};
if( TrickOrTreat.CheckMobile( target ) )
{
for( int i = 0; i < types.Length; i++ )
{
Item item = target.Backpack.FindItemByType( types[ i ] );
if( item != null )
{
return item;
}
}
}
return null;
}
public static void StealCandy( Mobile target )
{
if( TrickOrTreat.CheckMobile( target ) )
{
Item item = FindCandyTypes( target );
target.SendLocalizedMessage( 1113967 ); /* Your naughty twin steals some of your candy. */
if( item != null && !item.Deleted )
{
item.Delete();
}
}
}
public static void ToGate( Mobile target )
{
if( TrickOrTreat.CheckMobile( target ) )
{
target.SendLocalizedMessage( 1113972 ); /* Your naughty twin teleports you away with a naughty laugh! */
target.MoveToWorld( RandomMoongate( target ), target.Map );
}
}
public static Point3D RandomMoongate( Mobile target )
{
Map map = target.Map;
switch( target.Map.MapID )
{
case 2: return Ilshenar_Locations[ Utility.Random( Ilshenar_Locations.Length ) ];
case 3: return Malas_Locations[ Utility.Random( Malas_Locations.Length ) ];
case 4: return Tokuno_Locations[ Utility.Random( Tokuno_Locations.Length ) ];
default: return Felucca_Locations[ Utility.Random( Felucca_Locations.Length ) ];
}
}
public NaughtyTwin( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( ( int )0 );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Oyosoft.AgenceImmobiliere.Core.Commands;
using Oyosoft.AgenceImmobiliere.Core.DataAccess;
using Oyosoft.AgenceImmobiliere.Core.Service;
using Oyosoft.AgenceImmobiliere.Core.Tools;
namespace Oyosoft.AgenceImmobiliere.Core.ViewModels.BienImmobilier
{
public class List : BaseViewModel<Model.BienImmobilier, SearchCriteria>
{
public static long? itemsCountOnPage;
protected bool _isInitialized;
protected bool _isLoadingList;
protected bool _isLoadingDetails;
protected Enums.TypeTransaction? _transactionType;
protected SearchResult<Model.BienImmobilier> _biens;
protected Model.BienImmobilier _bienSelectionne;
private EventBindingCommand<EventArgs> _initializeCommand;
private Command<long?> _loadListCommand;
private Command<ICommand> _modifySearchCriteriaCommand;
private Command<ICommand> _addBienCommand;
private Command<ICommand> _modifyBienCommand;
private Command<Func<bool>> _deleteBienCommand;
public bool InitialisationTerminee
{
get { return _isInitialized; }
protected set { SetProperty(ref _isInitialized, value); }
}
public bool ChargementListeEnCours
{
get { return _isLoadingList; }
protected set { SetProperty(ref _isLoadingList, value); }
}
public Enums.TypeTransaction? TypeTransaction
{
get { return (_transactionType == null) ? Enums.TypeTransaction.Vente : _transactionType; }
protected set { if (SetProperty(ref _transactionType, value)) LoadList(null); }
}
public SearchCriteria CriteresRecherche
{
get { return _criteria; }
set { if (SetProperty(ref _criteria, value)) { OnPropertyChanged("CriteresRecherchesVides"); LoadList(null); } }
}
public bool CriteresRecherchesVides
{
get
{
return this._criteria.CriteresVides;
}
}
public SearchResult<Model.BienImmobilier> Biens
{
get { return _biens; }
protected set
{
if (SetProperty(ref _biens, value))
{
OnPropertyChanged("PageCourante");
OnPropertyChanged("PagePrecedente");
OnPropertyChanged("PageSuivante");
this.ModifyBienCommand.OnCanExecuteChanged();
this.DeleteBienCommand.OnCanExecuteChanged();
}
}
}
public long? PageCourante
{
get { return (_biens == null) ? null : _biens.CurrentPage; }
}
public long? PagePrecedente
{
get { return (_biens == null) ? null : (_biens.CurrentPage <= 1) ? null : _biens.CurrentPage - 1; }
}
public long? PageSuivante
{
get { return (_biens == null) ? null : (_biens.CurrentPage >= _biens.PagesCount) ? null : _biens.CurrentPage + 1; }
}
public Model.BienImmobilier BienSelectionne
{
get { return _bienSelectionne; }
protected set
{
if (SetProperty(ref _bienSelectionne, value))
{
OnPropertyChanged("BienEstSelectionne");
this.ModifyBienCommand.OnCanExecuteChanged();
this.DeleteBienCommand.OnCanExecuteChanged();
}
}
}
public bool BienEstSelectionne
{
get { return !_isLoadingDetails && _bienSelectionne != null; }
}
public EventBindingCommand<EventArgs> InitializeCommand
{
get
{
return _initializeCommand ?? (_initializeCommand = new EventBindingCommand<EventArgs>(async arg => { await LoadList(null); OnPropertyChanged("Biens"); }));
}
}
public Command<long?> LoadListCommand
{
get
{
return _loadListCommand ?? (_loadListCommand = new Command<long?>(async (currentPage) => await LoadList(currentPage)));
}
}
public Command<ICommand> ModifySearchCriteriaCommand
{
get
{
return _modifySearchCriteriaCommand ?? (_modifySearchCriteriaCommand = new Command<ICommand>(async (cmd) => await ExecuteCommand(cmd, this)));
}
}
public Command<ICommand> AddBienCommand
{
get
{
return _addBienCommand ?? (_addBienCommand = new Command<ICommand>(async (cmd) => await ExecuteCommand(cmd, null)));
}
}
public Command<ICommand> ModifyBienCommand
{
get
{
return _modifyBienCommand ?? (_modifyBienCommand = new Command<ICommand>(async (cmd) =>
{
if (this.BienEstSelectionne) await ExecuteCommand(cmd, this.BienSelectionne);
}, (cmd) => {
if (this.Biens == null ||
this.Biens.Items.Count == 0) return false;
return this.BienEstSelectionne;
}));
}
}
public Command<Func<bool>> DeleteBienCommand
{
get
{
return _deleteBienCommand ?? (_deleteBienCommand = new Command<Func<bool>>(async (cmd) =>
{
if (this.BienEstSelectionne) await Delete(cmd);
}, (cmd) => {
if (this.Biens == null ||
this.Biens.Items.Count == 0) return false;
return this.BienEstSelectionne;
}));
}
}
public List() : base()
{
_isLoadingDetails = false;
_isLoadingDetails = false;
_isLoadingList = false;
_biens = null;
_bienSelectionne = null;
}
public async Task LoadList(long? currentPage)
{
this.ChargementListeEnCours = true;
this.Erreurs.Clear();
this.BienSelectionne = null;
if (_criteria == null) _criteria = new SearchCriteria();
_criteria.TypeTransaction = _transactionType;
this.Biens = await base.GetList(currentPage, itemsCountOnPage);
this.ChargementListeEnCours = false;
}
public async Task ExecuteCommand(ICommand cmd, object parameter)
{
if (cmd != null)
{
if (cmd.GetType() == typeof(Command))
{
await ((Command)cmd).ExecuteAsync(parameter);
}
else
{
cmd.Execute(parameter);
}
}
}
public async Task Delete(Func<bool> validater)
{
if (!BienEstSelectionne) return;
this.Erreurs.Clear();
if (validater != null)
{
if (!validater()) return;
}
if (!await base.Delete(BienSelectionne.Id)) return;
await LoadList(this.PageCourante);
}
}
}
| |
/*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using SubSonic.Sugar;
using SubSonic.Utilities;
namespace SubSonic
{
/// <summary>
/// Summary for the Inflector class
/// </summary>
public static class Inflector
{
private static readonly List<InflectorRule> _plurals = new List<InflectorRule>();
private static readonly List<InflectorRule> _singulars = new List<InflectorRule>();
private static readonly List<string> _uncountables = new List<string>();
/// <summary>
/// Initializes the <see cref="Inflector"/> class.
/// </summary>
static Inflector()
{
AddPluralRule("$", "s");
AddPluralRule("s$", "s");
AddPluralRule("(ax|test)is$", "$1es");
AddPluralRule("(octop|vir)us$", "$1i");
AddPluralRule("(alias|status)$", "$1es");
AddPluralRule("(bu)s$", "$1ses");
AddPluralRule("(buffal|tomat)o$", "$1oes");
AddPluralRule("([ti])um$", "$1a");
AddPluralRule("sis$", "ses");
AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves");
AddPluralRule("(hive)$", "$1s");
AddPluralRule("([^aeiouy]|qu)y$", "$1ies");
AddPluralRule("(x|ch|ss|sh)$", "$1es");
AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices");
AddPluralRule("([m|l])ouse$", "$1ice");
AddPluralRule("^(ox)$", "$1en");
AddPluralRule("(quiz)$", "$1zes");
AddSingularRule("s$", String.Empty);
AddSingularRule("ss$", "ss");
AddSingularRule("(n)ews$", "$1ews");
AddSingularRule("([ti])a$", "$1um");
AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
AddSingularRule("(^analy)ses$", "$1sis");
AddSingularRule("([^f])ves$", "$1fe");
AddSingularRule("(hive)s$", "$1");
AddSingularRule("(tive)s$", "$1");
AddSingularRule("([lr])ves$", "$1f");
AddSingularRule("([^aeiouy]|qu)ies$", "$1y");
AddSingularRule("(s)eries$", "$1eries");
AddSingularRule("(m)ovies$", "$1ovie");
AddSingularRule("(x|ch|ss|sh)es$", "$1");
AddSingularRule("([m|l])ice$", "$1ouse");
AddSingularRule("(bus)es$", "$1");
AddSingularRule("(o)es$", "$1");
AddSingularRule("(shoe)s$", "$1");
AddSingularRule("(cris|ax|test)es$", "$1is");
AddSingularRule("(octop|vir)i$", "$1us");
AddSingularRule("(alias|status)$", "$1");
AddSingularRule("(alias|status)es$", "$1");
AddSingularRule("^(ox)en", "$1");
AddSingularRule("(vert|ind)ices$", "$1ex");
AddSingularRule("(matr)ices$", "$1ix");
AddSingularRule("(quiz)zes$", "$1");
AddIrregularRule("person", "people");
AddIrregularRule("man", "men");
AddIrregularRule("child", "children");
AddIrregularRule("sex", "sexes");
AddIrregularRule("tax", "taxes");
AddIrregularRule("move", "moves");
AddUnknownCountRule("equipment");
AddUnknownCountRule("information");
AddUnknownCountRule("rice");
AddUnknownCountRule("money");
AddUnknownCountRule("species");
AddUnknownCountRule("series");
AddUnknownCountRule("fish");
AddUnknownCountRule("sheep");
}
/// <summary>
/// Adds the irregular rule.
/// </summary>
/// <param name="singular">The singular.</param>
/// <param name="plural">The plural.</param>
private static void AddIrregularRule(string singular, string plural)
{
AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"), String.Concat("$1", plural.Substring(1)));
AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"), String.Concat("$1", singular.Substring(1)));
}
/// <summary>
/// Adds the unknown count rule.
/// </summary>
/// <param name="word">The word.</param>
private static void AddUnknownCountRule(string word)
{
_uncountables.Add(word.ToLower());
}
/// <summary>
/// Adds the plural rule.
/// </summary>
/// <param name="rule">The rule.</param>
/// <param name="replacement">The replacement.</param>
private static void AddPluralRule(string rule, string replacement)
{
_plurals.Add(new InflectorRule(rule, replacement));
}
/// <summary>
/// Adds the singular rule.
/// </summary>
/// <param name="rule">The rule.</param>
/// <param name="replacement">The replacement.</param>
private static void AddSingularRule(string rule, string replacement)
{
_singulars.Add(new InflectorRule(rule, replacement));
}
/// <summary>
/// Makes the plural.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakePlural(string word)
{
return ApplyRules(_plurals, word);
}
/// <summary>
/// Makes the singular.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakeSingular(string word)
{
return ApplyRules(_singulars, word);
}
/// <summary>
/// Applies the rules.
/// </summary>
/// <param name="rules">The rules.</param>
/// <param name="word">The word.</param>
/// <returns></returns>
private static string ApplyRules(IList<InflectorRule> rules, string word)
{
string result = word;
if(!_uncountables.Contains(word.ToLower()))
{
for(int i = rules.Count - 1; i >= 0; i--)
{
string currentPass = rules[i].Apply(word);
if(currentPass != null)
{
result = currentPass;
break;
}
}
}
return result;
}
/// <summary>
/// Converts the string to title case.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string ToTitleCase(string word)
{
return Regex.Replace(ToHumanCase(AddUnderscores(word)), @"\b([a-z])",
delegate(Match match) { return match.Captures[0].Value.ToUpper(); });
}
/// <summary>
/// Converts the string to human case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param>
/// <returns></returns>
public static string ToHumanCase(string lowercaseAndUnderscoredWord)
{
return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " "));
}
/// <summary>
/// Converts the string to pascal case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param>
/// <returns></returns>
public static string ToPascalCase(string lowercaseAndUnderscoredWord)
{
return ToPascalCase(lowercaseAndUnderscoredWord, true);
}
/// <summary>
/// Converts text to pascal case...
/// </summary>
/// <param name="text">The text.</param>
/// <param name="removeUnderscores">if set to <c>true</c> [remove underscores].</param>
/// <returns></returns>
public static string ToPascalCase(string text, bool removeUnderscores)
{
if(String.IsNullOrEmpty(text))
return text;
text = text.Replace("_", " ");
string joinString = removeUnderscores ? String.Empty : "_";
string[] words = text.Split(' ');
if(words.Length > 1 || Validation.IsUpperCase(words[0]))
{
for(int i = 0; i < words.Length; i++)
{
if(words[i].Length > 0)
{
string word = words[i];
string restOfWord = word.Substring(1);
if(Validation.IsUpperCase(restOfWord))
restOfWord = restOfWord.ToLower(CultureInfo.CurrentUICulture);
char firstChar = char.ToUpper(word[0], CultureInfo.CurrentUICulture);
words[i] = String.Concat(firstChar, restOfWord);
}
}
return String.Join(joinString, words);
}
return String.Concat(words[0].Substring(0, 1).ToUpper(CultureInfo.CurrentUICulture), words[0].Substring(1));
}
/// <summary>
/// Converts the string to camel case.
/// </summary>
/// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param>
/// <returns></returns>
public static string ToCamelCase(string lowercaseAndUnderscoredWord)
{
return MakeInitialLowerCase(ToPascalCase(lowercaseAndUnderscoredWord));
}
/// <summary>
/// Adds the underscores.
/// </summary>
/// <param name="pascalCasedWord">The pascal cased word.</param>
/// <returns></returns>
public static string AddUnderscores(string pascalCasedWord)
{
return Regex.Replace(Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower();
}
/// <summary>
/// Makes the initial caps.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakeInitialCaps(string word)
{
return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower());
}
/// <summary>
/// Makes the initial lower case.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public static string MakeInitialLowerCase(string word)
{
return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1));
}
/// <summary>
/// Adds the ordinal suffix.
/// </summary>
/// <param name="number">The number.</param>
/// <returns></returns>
public static string AddOrdinalSuffix(string number)
{
if(Utility.IsStringNumeric(number))
{
int n = int.Parse(number);
int nMod100 = n % 100;
if(nMod100 >= 11 && nMod100 <= 13)
return String.Concat(number, "th");
switch(n % 10)
{
case 1:
return String.Concat(number, "st");
case 2:
return String.Concat(number, "nd");
case 3:
return String.Concat(number, "rd");
default:
return String.Concat(number, "th");
}
}
return number;
}
/// <summary>
/// Converts the underscores to dashes.
/// </summary>
/// <param name="underscoredWord">The underscored word.</param>
/// <returns></returns>
public static string ConvertUnderscoresToDashes(string underscoredWord)
{
return underscoredWord.Replace('_', '-');
}
#region Nested type: InflectorRule
/// <summary>
/// Summary for the InflectorRule class
/// </summary>
private class InflectorRule
{
/// <summary>
///
/// </summary>
public readonly Regex regex;
/// <summary>
///
/// </summary>
public readonly string replacement;
/// <summary>
/// Initializes a new instance of the <see cref="InflectorRule"/> class.
/// </summary>
/// <param name="regexPattern">The regex pattern.</param>
/// <param name="replacementText">The replacement text.</param>
public InflectorRule(string regexPattern, string replacementText)
{
regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
replacement = replacementText;
}
/// <summary>
/// Applies the specified word.
/// </summary>
/// <param name="word">The word.</param>
/// <returns></returns>
public string Apply(string word)
{
if(!regex.IsMatch(word))
return null;
string replace = regex.Replace(word, replacement);
if(word == word.ToUpper())
replace = replace.ToUpper();
return replace;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Numerics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Vulkan;
namespace VulkanTest
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Vertex
{
public Vector2 pos;
public Vector3 color;
public Vertex(float px, float py, float cr, float cg, float cb)
{
pos.X = px;
pos.Y = py;
color.X = cr;
color.Y = cg;
color.Z = cb;
}
public static VK.VertexInputBindingDescription getBindingDescription()
{
VK.VertexInputBindingDescription bindingDescription = new VK.VertexInputBindingDescription();
bindingDescription.binding = 0;
bindingDescription.stride = (UInt32)Marshal.SizeOf(default(Vertex));
bindingDescription.inputRate = VK.VertexInputRate.Vertex;
return bindingDescription;
}
public static VK.VertexInputAttributeDescription[] getAttributeDescriptions()
{
VK.VertexInputAttributeDescription[] attributeDescriptions = new VK.VertexInputAttributeDescription[2];
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK.Format.R32g32Sfloat;
attributeDescriptions[0].offset = 0;
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK.Format.R32g32b32Sfloat;
attributeDescriptions[1].offset = 8;
return attributeDescriptions;
}
};
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct UniformBufferObject
{
public Matrix4x4 model;
public Matrix4x4 view;
public Matrix4x4 proj;
};
class QueueFamilyIndices
{
public Int32 graphicsFamily = -1;
public Int32 presentFamily = -1;
public bool isComplete()
{
return (graphicsFamily != -1) && (presentFamily != -1);
}
};
class SwapChainSupportDetails
{
public VK.SurfaceCapabilitiesKHR capabilities;
public VK.SurfaceFormatKHR[] formats;
public VK.PresentModeKHR[] presentModes;
};
class VulkanApp
{
const int WIDTH = 800;
const int HEIGHT = 600;
const int MAX_FRAMES_IN_FLIGHT = 2;
List<string> validationLayers = new List<string>() { InstanceLayers.VK_LAYER_LUNARG_standard_validation };
List<string> instanceExtensions = new List<string>() { InstanceExtensions.VK_KHR_surface,
InstanceExtensions.VK_KHR_win32_surface,
InstanceExtensions.VK_EXT_debug_utils};
List<string> deviceExtensions = new List<string>() { DeviceExtensions.VK_KHR_swapchain };
#if DEBUG
const bool enableValidationLayers = true;
#else
const bool enableValidationLayers = false;
#endif
IntPtr HInstance;
IntPtr Hwnd;
VK.Instance instance;
VK.DebugUtilsMessengerEXT debugMessenger;
VK.SurfaceKHR surface;
VK.PhysicalDevice physicalDevice;
VK.Device device;
VK.Queue graphicsQueue;
VK.Queue presentQueue;
VK.SwapchainKHR swapChain;
VK.Image[] swapChainImages;
VK.Format swapChainImageFormat;
VK.Extent2D swapChainExtent;
VK.ImageView[] swapChainImageViews;
VK.Framebuffer[] swapChainFramebuffers;
VK.RenderPass renderPass;
VK.DescriptorSetLayout descriptorSetLayout;
VK.PipelineLayout pipelineLayout;
VK.Pipeline graphicsPipeline;
VK.CommandPool commandPool;
VK.Buffer vertexBuffer;
VK.DeviceMemory vertexBufferMemory;
VK.Buffer indexBuffer;
VK.DeviceMemory indexBufferMemory;
VK.Buffer[] uniformBuffers;
VK.DeviceMemory[] uniformBuffersMemory;
VK.DescriptorPool descriptorPool;
VK.DescriptorSet[] descriptorSets;
VK.CommandBuffer[] commandBuffers;
VK.Semaphore[] imageAvailableSemaphores;
VK.Semaphore[] renderFinishedSemaphores;
VK.Fence[] inFlightFences;
UInt64 currentFrame = 0;
bool framebufferResized = false;
Vertex[] verts = new Vertex[]
{
new Vertex(-0.5f, -0.5f, 1.0f, 0.0f, 0.0f),
new Vertex(0.5f, -0.5f, 0.0f, 1.0f, 0.0f),
new Vertex(0.5f, 0.5f, 0.0f, 0.0f, 1.0f),
new Vertex(-0.5f, 0.5f, 1.0f, 1.0f, 1.0f)
};
UInt16[] indices = new ushort[] { 0, 1, 2, 2, 3, 0 };
public void init(IntPtr appHandle, IntPtr windowHandle)
{
initWindow(appHandle, windowHandle);
initVulkan();
}
void initWindow(IntPtr appHandle, IntPtr windowHandle)
{
HInstance = appHandle;
Hwnd = windowHandle;
}
void initVulkan()
{
createInstance();
setupDebugCallback();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
createRenderPass();
createDescriptorSetLayout();
createGraphicsPipeline();
createFramebuffers();
createCommandPool();
createVertexBuffer();
createIndexBuffer();
createUniformBuffers();
createDescriptorPool();
createDescriptorSets();
createCommandBuffers();
createSyncObjects();
}
public void cleanup()
{
cleanupSwapChain();
VK.DestroyDescriptorSetLayout(device, descriptorSetLayout);
VK.DestroyBuffer(device, indexBuffer);
VK.FreeMemory(device, indexBufferMemory);
VK.DestroyBuffer(device, vertexBuffer);
VK.FreeMemory(device, vertexBufferMemory);
for(int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
VK.DestroySemaphore(device, renderFinishedSemaphores[i]);
VK.DestroySemaphore(device, imageAvailableSemaphores[i]);
VK.DestroyFence(device, inFlightFences[i]);
}
VK.DestroyCommandPool(device, commandPool);
VK.DestroyDevice(device);
if(enableValidationLayers)
{
VK.DestroyDebugUtilsMessengerEXT(instance, debugMessenger);
}
VK.DestroySurfaceKHR(instance, surface);
VK.DestroyInstance(instance);
}
void cleanupSwapChain()
{
foreach(VK.Framebuffer framebuffer in swapChainFramebuffers)
{
VK.DestroyFramebuffer(device, framebuffer);
}
VK.FreeCommandBuffers(device, commandPool, (UInt32)commandBuffers.Length, commandBuffers);
VK.DestroyPipeline(device, graphicsPipeline);
VK.DestroyPipelineLayout(device, pipelineLayout);
VK.DestroyRenderPass(device, renderPass);
foreach(VK.ImageView imageView in swapChainImageViews)
{
VK.DestroyImageView(device, imageView);
}
for(int i = 0; i < uniformBuffers.Length; i++)
{
VK.DestroyBuffer(device, uniformBuffers[i]);
VK.FreeMemory(device, uniformBuffersMemory[i]);
}
VK.DestroySwapchainKHR(device, swapChain);
}
void recreateSwapChain()
{
int width = 0, height = 0;
while(width == 0 || height == 0)
{
// glfwGetFramebufferSize(window, &width, &height);
// glfwWaitEvents();
}
VK.DeviceWaitIdle(device);
cleanupSwapChain();
createSwapChain();
createImageViews();
createRenderPass();
createGraphicsPipeline();
createFramebuffers();
createCommandBuffers();
}
void createInstance()
{
if(enableValidationLayers && !checkValidationLayerSupport())
{
throw new Exception("validation layers requested, but not available!");
}
if(enableValidationLayers)
{
instanceExtensions.Add(InstanceExtensions.VK_EXT_debug_utils);
}
VK.InstanceCreateInfo info = new VK.InstanceCreateInfo()
{
type = VK.StructureType.InstanceCreateInfo,
next = IntPtr.Zero,
flags = 0,
applicationInfo = new VK.ApplicationInfo()
{
type = VK.StructureType.ApplicationInfo,
next = IntPtr.Zero,
applicationName = "Hello Triangle",
applicationVersion = Vulkan.Version.Make(1, 0, 0),
engineName = "Bobatron",
engineVersion = 1,
apiVersion = Vulkan.Version.Make(1, 1, 0)
},
enabledLayerNames = validationLayers,
enabledExtensionNames = instanceExtensions
};
VK.Result result = VK.CreateInstance(info, out instance);
if(result != VK.Result.Success)
{
throw new Exception("Failed to create Vulkan instance");
}
initInstanceExtensions();
}
void initInstanceExtensions()
{
VK.KHR_surface.init(instance);
VK.KHR_win32_surface.init(instance);
if(enableValidationLayers)
{
VK.EXT_debug_utils.init(instance);
}
}
void initDeviceExtensions()
{
VK.KHR_swapchain.init(device);
}
void setupDebugCallback()
{
Console.WriteLine("Initializing debug utils callback");
VK.DebugUtilsMessengerCreateInfoEXT info = new VK.DebugUtilsMessengerCreateInfoEXT()
{
type = VK.StructureType.DebugUtilsMessengerCreateInfoExt,
next = IntPtr.Zero,
flags = 0,
messageSeverity = VK.DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt |
VK.DebugUtilsMessageSeverityFlagsEXT.WarningBitExt,
messageType = VK.DebugUtilsMessageTypeFlagsEXT.GeneralBitExt | VK.DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt | VK.DebugUtilsMessageTypeFlagsEXT.ValidationBitExt,
pfnUserCallback = debugCallback,
pUserData = IntPtr.Zero
};
VK.Result res = VK.CreateDebugUtilsMessengerEXT(instance, ref info, null, out debugMessenger);
if(res != VK.Result.Success)
{
Console.WriteLine("Failed to install debug utils callback");
}
}
Bool32 debugCallback(VK.DebugUtilsMessageSeverityFlagsEXT messageSeverity, VK.DebugUtilsMessageTypeFlagsEXT messageTypes, ref VK.DebugUtilsMessengerCallbackDataEXT pCallbackData, IntPtr pUserData)
{
if(messageSeverity.HasFlag(VK.DebugUtilsMessageSeverityFlagsEXT.VerboseBitExt)) Console.Write("VERBOSE: ");
if(messageSeverity.HasFlag(VK.DebugUtilsMessageSeverityFlagsEXT.InfoBitExt)) Console.Write("INFO: ");
if(messageSeverity.HasFlag(VK.DebugUtilsMessageSeverityFlagsEXT.WarningBitExt)) Console.Write("WARNING: ");
if(messageSeverity.HasFlag(VK.DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)) Console.Write("ERROR: ");
if(messageTypes.HasFlag(VK.DebugUtilsMessageTypeFlagsEXT.GeneralBitExt)) Console.Write("GENERAL ");
if(messageTypes.HasFlag(VK.DebugUtilsMessageTypeFlagsEXT.ValidationBitExt)) Console.Write("VALIDATION ");
if(messageTypes.HasFlag(VK.DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt)) Console.Write("PERFORMANCE ");
Console.WriteLine(": ID: {0} Name: {1} \n\t {2}", pCallbackData.messageIdNumber, pCallbackData.pMessageIdName, pCallbackData.pMessage);
// Don't bail out, but keep going.
return false;
}
void createSurface()
{
Console.WriteLine("Creating surface");
VK.Win32SurfaceCreateInfoKHR info = new VK.Win32SurfaceCreateInfoKHR()
{
type = VK.StructureType.Win32SurfaceCreateInfoKhr,
next = IntPtr.Zero,
flags = 0,
hinstance = HInstance,
hwnd = Hwnd
};
VK.Result res = VK.CreateWin32SurfaceKHR(instance, ref info, null, ref surface);
if(res != VK.Result.Success)
{
Console.WriteLine("Failed to create surface");
}
}
void pickPhysicalDevice()
{
UInt32 deviceCount = 0;
VK.EnumeratePhysicalDevices(instance, ref deviceCount, null);
if(deviceCount == 0)
{
throw new Exception("failed to find GPUs with Vulkan support!");
}
VK.PhysicalDevice[] devices = new VK.PhysicalDevice[deviceCount];
VK.EnumeratePhysicalDevices(instance, ref deviceCount, devices);
foreach(VK.PhysicalDevice device in devices)
{
if(isDeviceSuitable(device))
{
physicalDevice = device;
break;
}
}
if(physicalDevice.native == IntPtr.Zero)
{
throw new Exception("failed to find a suitable GPU!");
}
}
void createLogicalDevice()
{
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
List<VK.DeviceQueueCreateInfo> queueCreateInfos = new List<VK.DeviceQueueCreateInfo>();
List<UInt32> queueFamilies = new List<UInt32>();
queueFamilies.Add((UInt32)indices.graphicsFamily);
queueFamilies.Add((UInt32)indices.presentFamily);
foreach(UInt32 familyIndex in queueFamilies)
{
queueCreateInfos.Add(
new VK.DeviceQueueCreateInfo()
{
type = VK.StructureType.DeviceQueueCreateInfo,
next = IntPtr.Zero,
flags = 0,
queueFamilyIndex = familyIndex,
queueCount = 1,
queuePriorities = new float[1] { 1.0f }
}
);
}
VK.PhysicalDeviceFeatures deviceFeatures = new VK.PhysicalDeviceFeatures();
VK.DeviceCreateInfo info = new VK.DeviceCreateInfo()
{
type = VK.StructureType.DeviceCreateInfo,
next = IntPtr.Zero,
flags = 0,
queueCreateInfos = queueCreateInfos,
enabledFeatures = deviceFeatures,
enabledExtensionNames = deviceExtensions,
enabledLayerNames = new List<string>() { }
};
if(VK.CreateDevice(physicalDevice, info, out device) != VK.Result.Success)
{
throw new Exception("failed to create logical device!");
}
VK.GetDeviceQueue(device, (UInt32)indices.graphicsFamily, 0, out graphicsQueue);
VK.GetDeviceQueue(device, (UInt32)indices.presentFamily, 0, out presentQueue);
initDeviceExtensions();
}
void createSwapChain()
{
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
VK.SurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
VK.PresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
VK.Extent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
UInt32 imageCount = swapChainSupport.capabilities.minImageCount + 1;
if(swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
{
imageCount = swapChainSupport.capabilities.maxImageCount;
}
VK.SwapchainCreateInfoKHR createInfo = new VK.SwapchainCreateInfoKHR();
createInfo.type = VK.StructureType.SwapchainCreateInfoKhr;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK.ImageUsageFlags.ColorAttachmentBit;
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
List<UInt32> queueFamilyIndices = new List<UInt32> { (UInt32)indices.graphicsFamily, (UInt32)indices.presentFamily };
if(indices.graphicsFamily != indices.presentFamily)
{
createInfo.imageSharingMode = VK.SharingMode.Concurrent;
createInfo.queueFamilyIndices = queueFamilyIndices;
}
else
{
createInfo.imageSharingMode = VK.SharingMode.Exclusive;
createInfo.queueFamilyIndices = null;
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK.CompositeAlphaFlagsKHR.OpaqueBit;
createInfo.presentMode = presentMode;
createInfo.clipped = true;
if(VK.CreateSwapchainKHR(device, ref createInfo, ref swapChain) != VK.Result.Success)
{
throw new Exception("failed to create swap chain!");
}
VK.GetSwapchainImagesKHR(device, swapChain, ref imageCount, null);
swapChainImages = new VK.Image[imageCount];
VK.GetSwapchainImagesKHR(device, swapChain, ref imageCount, swapChainImages);
swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent;
}
void createImageViews()
{
swapChainImageViews = new VK.ImageView[swapChainImages.Length];
for(int i = 0; i < swapChainImages.Length; i++)
{
VK.ImageViewCreateInfo createInfo = new VK.ImageViewCreateInfo();
createInfo.type = VK.StructureType.ImageViewCreateInfo;
createInfo.image = swapChainImages[i];
createInfo.viewType = VK.ImageViewType._2d;
createInfo.format = swapChainImageFormat;
createInfo.components.r = VK.ComponentSwizzle.Identity;
createInfo.components.g = VK.ComponentSwizzle.Identity;
createInfo.components.b = VK.ComponentSwizzle.Identity;
createInfo.components.a = VK.ComponentSwizzle.Identity; ;
createInfo.subresourceRange.aspectMask = VK.ImageAspectFlags.ColorBit;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
if(VK.CreateImageView(device, ref createInfo, out swapChainImageViews[i]) != VK.Result.Success)
{
throw new Exception("failed to create image views!");
}
}
}
void createRenderPass()
{
VK.AttachmentDescription colorAttachment = new VK.AttachmentDescription();
colorAttachment.format = swapChainImageFormat;
colorAttachment.samples = VK.SampleCountFlags._1Bit;
colorAttachment.loadOp = VK.AttachmentLoadOp.Clear;
colorAttachment.storeOp = VK.AttachmentStoreOp.Store;
colorAttachment.stencilLoadOp = VK.AttachmentLoadOp.DontCare;
colorAttachment.stencilStoreOp = VK.AttachmentStoreOp.DontCare;
colorAttachment.initialLayout = VK.ImageLayout.Undefined;
colorAttachment.finalLayout = VK.ImageLayout.PresentSrcKhr;
VK.AttachmentReference colorAttachmentRef = new VK.AttachmentReference();
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK.ImageLayout.ColorAttachmentOptimal;
VK.SubpassDescription subpass = new VK.SubpassDescription();
subpass.pipelineBindPoint = VK.PipelineBindPoint.Graphics;
subpass.colorAttachments = new List<VK.AttachmentReference> { colorAttachmentRef };
VK.SubpassDependency dependency = new VK.SubpassDependency();
dependency.srcSubpass = VK.SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK.PipelineStageFlags.ColorAttachmentOutputBit;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK.PipelineStageFlags.ColorAttachmentOutputBit;
dependency.dstAccessMask = VK.AccessFlags.ColorAttachmentReadBit | VK.AccessFlags.ColorAttachmentWriteBit;
VK.RenderPassCreateInfo renderPassInfo = new VK.RenderPassCreateInfo();
renderPassInfo.type = VK.StructureType.RenderPassCreateInfo;
renderPassInfo.attachments = new List<VK.AttachmentDescription> { colorAttachment };
renderPassInfo.subpasses = new List<VK.SubpassDescription> { subpass };
renderPassInfo.dependencies = new List<VK.SubpassDependency> { dependency };
if(VK.CreateRenderPass(device, ref renderPassInfo, out renderPass) != VK.Result.Success)
{
throw new Exception("failed to create render pass!");
}
}
void createDescriptorSetLayout()
{
VK.DescriptorSetLayoutBinding uboLayoutBinding = new VK.DescriptorSetLayoutBinding();
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.descriptorType = VK.DescriptorType.UniformBuffer;
uboLayoutBinding.immutableSamplers = null;
uboLayoutBinding.stageFlags = VK.ShaderStageFlags.VertexBit;
VK.DescriptorSetLayoutCreateInfo layoutInfo = new VK.DescriptorSetLayoutCreateInfo();
layoutInfo.type = VK.StructureType.DescriptorSetLayoutCreateInfo;
layoutInfo.bindings = new List<VK.DescriptorSetLayoutBinding> { uboLayoutBinding };
if(VK.CreateDescriptorSetLayout(device, ref layoutInfo, out descriptorSetLayout) != VK.Result.Success)
{
throw new Exception("failed to create descriptor set layout!");
}
}
void createGraphicsPipeline()
{
byte[] vertShaderCode = getEmbeddedResource("VulkanTest.libsrc.testVK.shaders.simpleTri.vert.glsl.spv");
byte[] fragShaderCode = getEmbeddedResource("VulkanTest.libsrc.testVK.shaders.simpleTri.frag.glsl.spv");
VK.ShaderModule vertShaderModule = createShaderModule(vertShaderCode);
VK.ShaderModule fragShaderModule = createShaderModule(fragShaderCode);
VK.PipelineShaderStageCreateInfo vertShaderStageInfo = new VK.PipelineShaderStageCreateInfo();
vertShaderStageInfo.type = VK.StructureType.PipelineShaderStageCreateInfo;
vertShaderStageInfo.stage = VK.ShaderStageFlags.VertexBit;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.name = "main";
VK.PipelineShaderStageCreateInfo fragShaderStageInfo = new VK.PipelineShaderStageCreateInfo();
fragShaderStageInfo.type = VK.StructureType.PipelineShaderStageCreateInfo;
fragShaderStageInfo.stage = VK.ShaderStageFlags.FragmentBit;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.name = "main";
List<VK.PipelineShaderStageCreateInfo> shaderStages = new List<VK.PipelineShaderStageCreateInfo> { vertShaderStageInfo, fragShaderStageInfo };
VK.PipelineVertexInputStateCreateInfo vertexInputInfo = new VK.PipelineVertexInputStateCreateInfo();
vertexInputInfo.type = VK.StructureType.PipelineVertexInputStateCreateInfo;
vertexInputInfo.vertexBindingDescriptions = new VK.VertexInputBindingDescription[] { Vertex.getBindingDescription() };
vertexInputInfo.vertexAttributeDescriptions = Vertex.getAttributeDescriptions();
VK.PipelineInputAssemblyStateCreateInfo inputAssembly = new VK.PipelineInputAssemblyStateCreateInfo();
inputAssembly.type = VK.StructureType.PipelineInputAssemblyStateCreateInfo;
inputAssembly.topology = VK.PrimitiveTopology.TriangleList;
inputAssembly.primitiveRestartEnable = false;
VK.Viewport viewport = new VK.Viewport();
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)swapChainExtent.width;
viewport.height = (float)swapChainExtent.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VK.Rect2D scissor = new VK.Rect2D();
scissor.offset = new VK.Offset2D { x = 0, y = 0 };
scissor.extent = swapChainExtent;
VK.PipelineViewportStateCreateInfo viewportState = new VK.PipelineViewportStateCreateInfo();
viewportState.type = VK.StructureType.PipelineViewportStateCreateInfo;
viewportState.viewports = new List<VK.Viewport> { viewport };
viewportState.scissors = new List<VK.Rect2D> { scissor };
VK.PipelineRasterizationStateCreateInfo rasterizer = new VK.PipelineRasterizationStateCreateInfo();
rasterizer.type = VK.StructureType.PipelineRasterizationStateCreateInfo;
rasterizer.depthClampEnable = false;
rasterizer.rasterizerDiscardEnable = false;
rasterizer.polygonMode = VK.PolygonMode.Fill;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK.CullModeFlags.BackBit;
rasterizer.frontFace = VK.FrontFace.Clockwise;
rasterizer.depthBiasEnable = false;
VK.PipelineMultisampleStateCreateInfo multisampling = new VK.PipelineMultisampleStateCreateInfo();
multisampling.type = VK.StructureType.PipelineMultisampleStateCreateInfo;
multisampling.sampleShadingEnable = false;
multisampling.rasterizationSamples = VK.SampleCountFlags._1Bit;
VK.PipelineColorBlendAttachmentState colorBlendAttachment = new VK.PipelineColorBlendAttachmentState();
colorBlendAttachment.colorWriteMask = VK.ColorComponentFlags.RBit | VK.ColorComponentFlags.GBit | VK.ColorComponentFlags.BBit | VK.ColorComponentFlags.ABit;
colorBlendAttachment.blendEnable = false;
VK.PipelineColorBlendStateCreateInfo colorBlending = new VK.PipelineColorBlendStateCreateInfo();
colorBlending.type = VK.StructureType.PipelineColorBlendStateCreateInfo;
colorBlending.logicOpEnable = false;
colorBlending.logicOp = VK.LogicOp.Copy;
colorBlending.attachments = new List<VK.PipelineColorBlendAttachmentState> { colorBlendAttachment };
colorBlending.blendConstants = new List<float> { 0.0f, 0.0f, 0.0f, 0.0f };
VK.PipelineLayoutCreateInfo pipelineLayoutInfo = new VK.PipelineLayoutCreateInfo();
pipelineLayoutInfo.type = VK.StructureType.PipelineLayoutCreateInfo;
pipelineLayoutInfo.setLayouts = new List<VK.DescriptorSetLayout> { descriptorSetLayout };
pipelineLayoutInfo.pushConstantRanges = null;
if(VK.CreatePipelineLayout(device, ref pipelineLayoutInfo, out pipelineLayout) != VK.Result.Success)
{
throw new Exception("failed to create pipeline layout!");
}
VK.GraphicsPipelineCreateInfo pipelineInfo = new VK.GraphicsPipelineCreateInfo();
pipelineInfo.type = VK.StructureType.GraphicsPipelineCreateInfo;
pipelineInfo.stages = shaderStages;
pipelineInfo.vertexInputState = vertexInputInfo;
pipelineInfo.inputAssemblyState = inputAssembly;
pipelineInfo.viewportState = viewportState;
pipelineInfo.rasterizationState = rasterizer;
pipelineInfo.multisampleState = multisampling;
pipelineInfo.colorBlendState = colorBlending;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK.NullPipeline;
VK.Pipeline[] pipelines = new VK.Pipeline[1];
if(VK.CreateGraphicsPipelines(device, VK.NullPipelineCache, 1, new VK.GraphicsPipelineCreateInfo[] { pipelineInfo }, pipelines) != VK.Result.Success)
{
throw new Exception("failed to create graphics pipeline!");
}
graphicsPipeline = pipelines[0];
VK.DestroyShaderModule(device, fragShaderModule);
VK.DestroyShaderModule(device, vertShaderModule);
}
void createFramebuffers()
{
swapChainFramebuffers = new VK.Framebuffer[swapChainImageViews.Length];
for(int i = 0; i < swapChainImageViews.Length; i++)
{
List<VK.ImageView> attachments = new List<VK.ImageView> { swapChainImageViews[i] };
VK.FramebufferCreateInfo framebufferInfo = new VK.FramebufferCreateInfo();
framebufferInfo.type = VK.StructureType.FramebufferCreateInfo;
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachments = attachments;
framebufferInfo.width = swapChainExtent.width;
framebufferInfo.height = swapChainExtent.height;
framebufferInfo.layers = 1;
if(VK.CreateFramebuffer(device, framebufferInfo, out swapChainFramebuffers[i]) != VK.Result.Success)
{
throw new Exception("failed to create framebuffer!");
}
}
}
void createCommandPool()
{
QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
VK.CommandPoolCreateInfo poolInfo = new VK.CommandPoolCreateInfo();
poolInfo.type = VK.StructureType.CommandPoolCreateInfo;
poolInfo.queueFamilyIndex = (UInt32)queueFamilyIndices.graphicsFamily;
if(VK.CreateCommandPool(device, ref poolInfo, out commandPool) != VK.Result.Success)
{
throw new Exception("failed to create command pool!");
}
}
unsafe void createVertexBuffer()
{
Vulkan.DeviceSize bufferSize = Marshal.SizeOf(typeof(Vertex)) * verts.Length;
VK.Buffer stagingBuffer = new VK.Buffer();
VK.DeviceMemory stagingBufferMemory = new VK.DeviceMemory();
createBuffer(bufferSize, VK.BufferUsageFlags.TransferSrcBit, VK.MemoryPropertyFlags.HostVisibleBit | VK.MemoryPropertyFlags.HostCoherentBit, ref stagingBuffer, ref stagingBufferMemory);
IntPtr data = IntPtr.Zero;
VK.MapMemory(device, stagingBufferMemory, 0, bufferSize, 0, ref data);
fixed (Vertex* v = &verts[0])
{
Util.memcpy(data, (IntPtr)v, (int)((UInt64)bufferSize));
}
VK.UnmapMemory(device, stagingBufferMemory);
createBuffer(bufferSize, VK.BufferUsageFlags.TransferDstBit | VK.BufferUsageFlags.VertexBufferBit, VK.MemoryPropertyFlags.DeviceLocalBit, ref vertexBuffer, ref vertexBufferMemory);
copyBuffer(stagingBuffer, vertexBuffer, bufferSize);
VK.DestroyBuffer(device, stagingBuffer);
VK.FreeMemory(device, stagingBufferMemory);
}
unsafe void createIndexBuffer()
{
Vulkan.DeviceSize bufferSize = Marshal.SizeOf(typeof(UInt32)) * indices.Length;
VK.Buffer stagingBuffer = new VK.Buffer();
VK.DeviceMemory stagingBufferMemory = new VK.DeviceMemory();
createBuffer(bufferSize, VK.BufferUsageFlags.TransferSrcBit, VK.MemoryPropertyFlags.HostVisibleBit | VK.MemoryPropertyFlags.HostCoherentBit, ref stagingBuffer, ref stagingBufferMemory);
IntPtr data = IntPtr.Zero;
VK.MapMemory(device, stagingBufferMemory, 0, bufferSize, 0, ref data);
fixed (UInt16* v = &indices[0])
{
Util.memcpy(data, (IntPtr)v, (int)((UInt64)bufferSize));
}
VK.UnmapMemory(device, stagingBufferMemory);
createBuffer(bufferSize, VK.BufferUsageFlags.TransferDstBit | VK.BufferUsageFlags.IndexBufferBit, VK.MemoryPropertyFlags.DeviceLocalBit, ref indexBuffer, ref indexBufferMemory);
copyBuffer(stagingBuffer, indexBuffer, bufferSize);
VK.DestroyBuffer(device, stagingBuffer);
VK.FreeMemory(device, stagingBufferMemory);
}
void createUniformBuffers()
{
Vulkan.DeviceSize bufferSize = Marshal.SizeOf(typeof(UniformBufferObject));
uniformBuffers = new VK.Buffer[swapChainImages.Length];
uniformBuffersMemory = new VK.DeviceMemory[swapChainImages.Length];
for(int i = 0; i < swapChainImages.Length; i++)
{
createBuffer(bufferSize, VK.BufferUsageFlags.UniformBufferBit, VK.MemoryPropertyFlags.HostVisibleBit | VK.MemoryPropertyFlags.HostCoherentBit, ref uniformBuffers[i], ref uniformBuffersMemory[i]);
}
}
void createDescriptorPool()
{
VK.DescriptorPoolSize poolSize = new VK.DescriptorPoolSize();
poolSize.type = VK.DescriptorType.UniformBuffer;
poolSize.descriptorCount = (UInt32)swapChainImages.Length;
VK.DescriptorPoolCreateInfo poolInfo = new VK.DescriptorPoolCreateInfo();
poolInfo.type = VK.StructureType.DescriptorPoolCreateInfo;
poolInfo.poolSizes = new List<VK.DescriptorPoolSize>() { poolSize };
poolInfo.maxSets = (UInt32)swapChainImages.Length;
if(VK.CreateDescriptorPool(device, ref poolInfo, out descriptorPool) != VK.Result.Success)
{
throw new Exception("failed to create descriptor pool!");
}
}
void createDescriptorSets()
{
List<VK.DescriptorSetLayout> layouts = new List<VK.DescriptorSetLayout>() { descriptorSetLayout, descriptorSetLayout, descriptorSetLayout };
VK.DescriptorSetAllocateInfo allocInfo = new VK.DescriptorSetAllocateInfo();
allocInfo.type = VK.StructureType.DescriptorSetAllocateInfo;
allocInfo.descriptorPool = descriptorPool;
allocInfo.setLayouts = layouts;
descriptorSets = new VK.DescriptorSet[swapChainImages.Length];
if(VK.AllocateDescriptorSets(device, ref allocInfo, descriptorSets) != VK.Result.Success)
{
throw new Exception("failed to allocate descriptor sets!");
}
for(int i = 0; i < swapChainImages.Length; i++)
{
VK.DescriptorBufferInfo bufferInfo = new VK.DescriptorBufferInfo();
bufferInfo.buffer = uniformBuffers[i];
bufferInfo.offset = 0;
bufferInfo.range = Marshal.SizeOf(typeof(UniformBufferObject));
VK.WriteDescriptorSet descriptorWrite = new VK.WriteDescriptorSet();
descriptorWrite.type = VK.StructureType.WriteDescriptorSet;
descriptorWrite.dstSet = descriptorSets[i];
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK.DescriptorType.UniformBuffer;
descriptorWrite.descriptorCount = 1;
descriptorWrite.bufferInfo = bufferInfo;
VK.UpdateDescriptorSets(device, 1, new VK.WriteDescriptorSet[] { descriptorWrite }, 0, null);
}
}
void createBuffer(Vulkan.DeviceSize size, VK.BufferUsageFlags usage, VK.MemoryPropertyFlags properties, ref VK.Buffer buffer, ref VK.DeviceMemory bufferMemory)
{
VK.BufferCreateInfo bufferInfo = new VK.BufferCreateInfo();
bufferInfo.type = VK.StructureType.BufferCreateInfo;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK.SharingMode.Exclusive;
if(VK.CreateBuffer(device, ref bufferInfo, out buffer) != VK.Result.Success)
{
throw new Exception("failed to create buffer!");
}
VK.MemoryRequirements memRequirements = new VK.MemoryRequirements();
VK.GetBufferMemoryRequirements(device, buffer, ref memRequirements);
VK.MemoryAllocateInfo allocInfo = new VK.MemoryAllocateInfo();
allocInfo.type = VK.StructureType.MemoryAllocateInfo;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits, properties);
if(VK.AllocateMemory(device, ref allocInfo, out bufferMemory) != VK.Result.Success)
{
throw new Exception("failed to allocate buffer memory!");
}
VK.BindBufferMemory(device, buffer, bufferMemory, 0);
}
void copyBuffer(VK.Buffer srcBuffer, VK.Buffer dstBuffer, Vulkan.DeviceSize size)
{
VK.CommandBufferAllocateInfo allocInfo = new VK.CommandBufferAllocateInfo();
allocInfo.type = VK.StructureType.CommandBufferAllocateInfo;
allocInfo.level = VK.CommandBufferLevel.Primary;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VK.CommandBuffer commandBuffer = new VK.CommandBuffer();
VK.CommandBuffer[] buffers = new VK.CommandBuffer[1];
VK.AllocateCommandBuffers(device, ref allocInfo, buffers);
commandBuffer = buffers[0];
VK.CommandBufferBeginInfo beginInfo = new VK.CommandBufferBeginInfo();
beginInfo.type = VK.StructureType.CommandBufferBeginInfo;
beginInfo.flags = VK.CommandBufferUsageFlags.OneTimeSubmitBit;
VK.BeginCommandBuffer(commandBuffer, ref beginInfo);
VK.BufferCopy copyRegion = new VK.BufferCopy();
copyRegion.size = size;
VK.CmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, new VK.BufferCopy[] { copyRegion });
VK.EndCommandBuffer(commandBuffer);
VK.SubmitInfo submitInfo = new VK.SubmitInfo();
submitInfo.type = VK.StructureType.SubmitInfo;
submitInfo.commandBuffers = new List<VK.CommandBuffer>() { commandBuffer };
VK.QueueSubmit(graphicsQueue, 1, new VK.SubmitInfo[] { submitInfo }, VK.NULL_FENCE);
VK.QueueWaitIdle(graphicsQueue);
VK.FreeCommandBuffers(device, commandPool, 1, buffers);
}
UInt32 findMemoryType(UInt32 typeFilter, VK.MemoryPropertyFlags properties)
{
VK.PhysicalDeviceMemoryProperties memProperties;
VK.GetPhysicalDeviceMemoryProperties(physicalDevice, out memProperties);
for(int i = 0; i < memProperties.memoryTypeCount; i++)
{
if(((typeFilter & (1 << i)) != 0) && ((memProperties.memoryTypes[i].propertyFlags & properties) == properties))
{
return (UInt32)i;
}
}
throw new Exception("failed to find suitable memory type!");
}
void createCommandBuffers()
{
commandBuffers = new VK.CommandBuffer[swapChainFramebuffers.Length];
VK.CommandBufferAllocateInfo allocInfo = new VK.CommandBufferAllocateInfo();
allocInfo.type = VK.StructureType.CommandBufferAllocateInfo;
allocInfo.commandPool = commandPool;
allocInfo.level = VK.CommandBufferLevel.Primary;
allocInfo.commandBufferCount = (UInt32)commandBuffers.Length;
if(VK.AllocateCommandBuffers(device, ref allocInfo, commandBuffers) != VK.Result.Success)
{
throw new Exception("failed to allocate command buffers!");
}
for(int i = 0; i < commandBuffers.Length; i++)
{
VK.CommandBufferBeginInfo beginInfo = new VK.CommandBufferBeginInfo();
beginInfo.type = VK.StructureType.CommandBufferBeginInfo;
if(VK.BeginCommandBuffer(commandBuffers[i], ref beginInfo) != VK.Result.Success)
{
throw new Exception("failed to begin recording command buffer!");
}
VK.RenderPassBeginInfo renderPassInfo = new VK.RenderPassBeginInfo();
renderPassInfo.type = VK.StructureType.RenderPassBeginInfo;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = swapChainFramebuffers[i];
renderPassInfo.renderArea.offset = new VK.Offset2D() { x = 0, y = 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
VK.ClearValue clearColor = new VK.ClearValue();
clearColor.color.r = 0.0f;
clearColor.color.g = 0.0f;
clearColor.color.b = 0.0f;
clearColor.color.a = 1.0f;
renderPassInfo.clearValues = new List<VK.ClearValue> { clearColor };
VK.CmdBeginRenderPass(commandBuffers[i], ref renderPassInfo, VK.SubpassContents.Inline);
VK.CmdBindPipeline(commandBuffers[i], VK.PipelineBindPoint.Graphics, graphicsPipeline);
VK.Buffer[] vertexBuffers = new VK.Buffer[] { vertexBuffer };
Vulkan.DeviceSize[] offsets = new DeviceSize[] { 0 };
VK.CmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets);
VK.CmdBindIndexBuffer(commandBuffers[i], indexBuffer, 0, VK.IndexType.Uint16);
UInt32 dynamicOffsets = 0;
VK.CmdBindDescriptorSets(commandBuffers[i], VK.PipelineBindPoint.Graphics, pipelineLayout, 0, 1, ref descriptorSets[i], 0, ref dynamicOffsets);
VK.CmdDrawIndexed(commandBuffers[i], (UInt32)indices.Length, 1, 0, 0, 0);
VK.CmdEndRenderPass(commandBuffers[i]);
if(VK.EndCommandBuffer(commandBuffers[i]) != VK.Result.Success)
{
throw new Exception("failed to record command buffer!");
}
}
}
void createSyncObjects()
{
imageAvailableSemaphores = new VK.Semaphore[MAX_FRAMES_IN_FLIGHT];
renderFinishedSemaphores = new VK.Semaphore[MAX_FRAMES_IN_FLIGHT];
inFlightFences = new VK.Fence[MAX_FRAMES_IN_FLIGHT];
VK.SemaphoreCreateInfo semaphoreInfo = new VK.SemaphoreCreateInfo();
semaphoreInfo.type = VK.StructureType.SemaphoreCreateInfo;
VK.FenceCreateInfo fenceInfo = new VK.FenceCreateInfo();
fenceInfo.type = VK.StructureType.FenceCreateInfo;
fenceInfo.flags = VK.FenceCreateFlags.SignaledBit;
for(int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
if(VK.CreateSemaphore(device, ref semaphoreInfo, out imageAvailableSemaphores[i]) != VK.Result.Success ||
VK.CreateSemaphore(device, ref semaphoreInfo, out renderFinishedSemaphores[i]) != VK.Result.Success ||
VK.CreateFence(device, ref fenceInfo, out inFlightFences[i]) != VK.Result.Success)
{
throw new Exception("failed to create synchronization objects for a frame!");
}
}
}
Stopwatch timesrc = new Stopwatch();
unsafe void updateUniformBuffer(UInt32 currentImage)
{
if(timesrc.IsRunning == false)
{
timesrc.Start();
}
float time = (float)timesrc.Elapsed.TotalSeconds;
UniformBufferObject ubo = new UniformBufferObject();
ubo.model = Matrix4x4.CreateRotationY(time * (float)(90.0 * Math.PI / 180.0));
ubo.view = Matrix4x4.CreateLookAt(new Vector3(2.0f, 2.0f, 2.0f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f));
ubo.proj = Matrix4x4.CreatePerspectiveFieldOfView((float)(45.0 * Math.PI / 180.0), swapChainExtent.width / (float)swapChainExtent.height, 0.1f, 10.0f);
//ubo.proj[1][1] *= -1;
IntPtr data = IntPtr.Zero;
Vulkan.DeviceSize bufferSize = Marshal.SizeOf(typeof(UniformBufferObject));
VK.MapMemory(device, uniformBuffersMemory[currentImage], 0, bufferSize, 0, ref data);
UniformBufferObject* u = &ubo;
Util.memcpy(data, (IntPtr)u, (int)((UInt64)bufferSize));
VK.UnmapMemory(device, uniformBuffersMemory[currentImage]);
}
public void drawFrame()
{
VK.WaitForFences(device, 1, new VK.Fence[] { inFlightFences[currentFrame] }, true, UInt64.MaxValue);
UInt32 imageIndex = 0;
VK.Result result = VK.AcquireNextImageKHR(device, swapChain, UInt64.MaxValue, imageAvailableSemaphores[currentFrame], VK.NULL_FENCE, ref imageIndex);
if(result == VK.Result.ErrorOutOfDateKhr)
{
recreateSwapChain();
return;
}
else if(result != VK.Result.Success && result != VK.Result.SuboptimalKhr)
{
throw new Exception("failed to acquire swap chain image!");
}
updateUniformBuffer(imageIndex);
List<VK.Semaphore> signalSemaphores = new List<VK.Semaphore> { renderFinishedSemaphores[currentFrame] };
VK.SubmitInfo submitInfo = new VK.SubmitInfo();
submitInfo.type = VK.StructureType.SubmitInfo;
submitInfo.waitSemaphores = new List<VK.Semaphore> { imageAvailableSemaphores[currentFrame] };
submitInfo.waitDstStageMask = new List<VK.PipelineStageFlags> { VK.PipelineStageFlags.ColorAttachmentOutputBit };
submitInfo.commandBuffers = new List<VK.CommandBuffer> { commandBuffers[imageIndex] };
submitInfo.signalSemaphores = signalSemaphores;
VK.ResetFences(device, 1, new VK.Fence[] { inFlightFences[currentFrame] });
if(VK.QueueSubmit(graphicsQueue, 1, new VK.SubmitInfo[] { submitInfo }, inFlightFences[currentFrame]) != VK.Result.Success)
{
throw new Exception("failed to submit draw command buffer!");
}
VK.PresentInfoKHR presentInfo = new VK.PresentInfoKHR();
presentInfo.type = VK.StructureType.PresentInfoKhr;
presentInfo.waitSemaphores = signalSemaphores;
presentInfo.swapchains = new List<VK.SwapchainKHR> { swapChain };
presentInfo.indices = new List<UInt32>() { imageIndex };
result = VK.QueuePresentKHR(presentQueue, ref presentInfo);
if(result == VK.Result.ErrorOutOfDateKhr || result == VK.Result.SuboptimalKhr || framebufferResized)
{
framebufferResized = false;
recreateSwapChain();
}
else if(result != VK.Result.Success)
{
throw new Exception("failed to present swap chain image!");
}
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
VK.ShaderModule createShaderModule(byte[] code)
{
VK.ShaderModuleCreateInfo createInfo = new VK.ShaderModuleCreateInfo();
createInfo.type = VK.StructureType.ShaderModuleCreateInfo;
createInfo.code = code;
VK.ShaderModule shaderModule;
if(VK.CreateShaderModule(device, ref createInfo, out shaderModule) != VK.Result.Success)
{
throw new Exception("failed to create shader module!");
}
return shaderModule;
}
VK.SurfaceFormatKHR chooseSwapSurfaceFormat(VK.SurfaceFormatKHR[] availableFormats)
{
foreach(VK.SurfaceFormatKHR availableFormat in availableFormats)
{
if(availableFormat.format == VK.Format.B8g8r8a8Unorm && availableFormat.colorSpace == VK.ColorSpaceKHR.SrgbNonlinear)
{
return availableFormat;
}
}
return availableFormats[0];
}
VK.PresentModeKHR chooseSwapPresentMode(VK.PresentModeKHR[] availablePresentModes)
{
foreach(VK.PresentModeKHR availablePresentMode in availablePresentModes)
{
if(availablePresentMode == VK.PresentModeKHR.Mailbox)
{
return availablePresentMode;
}
}
return VK.PresentModeKHR.Fifo;
}
VK.Extent2D chooseSwapExtent(VK.SurfaceCapabilitiesKHR capabilities)
{
if(capabilities.currentExtent.width != UInt32.MaxValue)
{
return capabilities.currentExtent;
}
else
{
int width = WIDTH;
int height = HEIGHT;
//glfwGetFramebufferSize(window, &width, &height);
VK.Extent2D actualExtent = new VK.Extent2D();
actualExtent.width = (UInt32)width;
actualExtent.height = (UInt32)height;
actualExtent.width = Math.Max(capabilities.minImageExtent.width, Math.Min(capabilities.maxImageExtent.width, actualExtent.width));
actualExtent.height = Math.Max(capabilities.minImageExtent.height, Math.Min(capabilities.maxImageExtent.height, actualExtent.height));
return actualExtent;
}
}
SwapChainSupportDetails querySwapChainSupport(VK.PhysicalDevice device)
{
SwapChainSupportDetails details = new SwapChainSupportDetails();
VK.GetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, out details.capabilities);
UInt32 formatCount = 0;
VK.GetPhysicalDeviceSurfaceFormatsKHR(device, surface, ref formatCount, null);
if(formatCount != 0)
{
details.formats = new VK.SurfaceFormatKHR[formatCount];
VK.GetPhysicalDeviceSurfaceFormatsKHR(device, surface, ref formatCount, details.formats);
}
UInt32 presentModeCount = 0;
VK.GetPhysicalDeviceSurfacePresentModesKHR(device, surface, ref presentModeCount, null);
if(presentModeCount != 0)
{
details.presentModes = new VK.PresentModeKHR[presentModeCount];
VK.GetPhysicalDeviceSurfacePresentModesKHR(device, surface, ref presentModeCount, details.presentModes);
}
return details;
}
bool isDeviceSuitable(VK.PhysicalDevice device)
{
QueueFamilyIndices indices = findQueueFamilies(device);
bool extensionsSupported = checkDeviceExtensionSupport(device);
bool swapChainAdequate = false;
if(extensionsSupported)
{
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device);
swapChainAdequate = (swapChainSupport.formats.Length > 0) && (swapChainSupport.presentModes.Length > 0);
}
VK.PhysicalDeviceProperties props;
VK.GetPhysicalDeviceProperties(device, out props);
VK.PhysicalDeviceFeatures supportedFeatures;
VK.GetPhysicalDeviceFeatures(device, out supportedFeatures);
if(props.deviceType != VK.PhysicalDeviceType.DiscreteGpu)
{
return false;
}
return indices.isComplete() && extensionsSupported && swapChainAdequate;
}
bool checkDeviceExtensionSupport(VK.PhysicalDevice device)
{
UInt32 extensionCount = 0;
VK.EnumerateDeviceExtensionProperties(device, null, ref extensionCount, null);
VK.ExtensionProperties[] availableExtensions = new VK.ExtensionProperties[extensionCount];
VK.EnumerateDeviceExtensionProperties(device, null, ref extensionCount, availableExtensions);
bool allFound = true;
foreach(string extension in deviceExtensions)
{
bool found = false;
foreach(VK.ExtensionProperties ext in availableExtensions)
{
if(ext.extensionName == extension)
{
found = true;
break;
}
}
allFound = allFound && found;
}
return allFound;
}
QueueFamilyIndices findQueueFamilies(VK.PhysicalDevice device)
{
QueueFamilyIndices indices = new QueueFamilyIndices();
UInt32 queueFamilyCount = 0;
VK.GetPhysicalDeviceQueueFamilyProperties(device, ref queueFamilyCount, null);
VK.QueueFamilyProperties[] queueFamilies = new VK.QueueFamilyProperties[queueFamilyCount];
VK.GetPhysicalDeviceQueueFamilyProperties(device, ref queueFamilyCount, queueFamilies);
Int32 i = 0;
foreach(VK.QueueFamilyProperties queueFamily in queueFamilies)
{
if((queueFamily.queueCount > 0) && queueFamily.queueFlags.HasFlag(VK.QueueFlags.GraphicsBit))
{
indices.graphicsFamily = i;
}
Bool32 presentSupport = false;
VK.GetPhysicalDeviceSurfaceSupportKHR(device, (UInt32)i, surface, out presentSupport);
if(queueFamily.queueCount > 0 && presentSupport)
{
indices.presentFamily = i;
}
if(indices.isComplete())
{
break;
}
i++;
}
return indices;
}
bool checkValidationLayerSupport()
{
UInt32 layerCount = 0;
VK.EnumerateInstanceLayerProperties(ref layerCount, null);
VK.LayerProperties[] availableLayers = new VK.LayerProperties[layerCount];
VK.EnumerateInstanceLayerProperties(ref layerCount, availableLayers);
foreach(String layerName in validationLayers)
{
bool layerFound = false;
foreach(VK.LayerProperties layerProperties in availableLayers)
{
if(layerName == layerProperties.layerName)
{
layerFound = true;
break;
}
}
if(!layerFound)
{
return false;
}
}
return true;
}
void enumerateInstanceLayers()
{
Console.WriteLine("Enumerating Instance Layer Properties");
UInt32 count = 0;
VK.EnumerateInstanceLayerProperties(ref count, null);
VK.LayerProperties[] props = new VK.LayerProperties[count];
VK.EnumerateInstanceLayerProperties(ref count, props);
for(int i = 0; i < props.Length; i++)
{
Console.WriteLine("\tLayer Name: {0}", props[i].layerName);
Console.WriteLine("\t\tDescription: {0}", props[i].description);
}
}
void enumerateInstanceExtensions()
{
Console.WriteLine("Enumerating Instance Extensions");
UInt32 count = 0;
VK.EnumerateInstanceExtensionProperties(null, out count, null);
VK.ExtensionProperties[] props = new VK.ExtensionProperties[count];
VK.EnumerateInstanceExtensionProperties(null, out count, props);
for(int i = 0; i < props.Length; i++)
{
Console.WriteLine("\tExtensions Name: {0}", props[i].extensionName);
}
}
void enumerateDeviceLayers()
{
Console.WriteLine("Enumerating Device Layer Properties");
UInt32 count = 0;
VK.EnumerateDeviceLayerProperties(physicalDevice, out count, null);
VK.LayerProperties[] props = new VK.LayerProperties[count];
VK.EnumerateDeviceLayerProperties(physicalDevice, out count, props);
for(int i = 0; i < props.Length; i++)
{
Console.WriteLine("\tLayer Name: {0}", props[i].layerName);
Console.WriteLine("\t\tDescription: {0}", props[i].description);
}
}
void enumerateDeviceExtensions()
{
Console.WriteLine("Enumerating Device Extensions");
UInt32 count = 0;
VK.EnumerateDeviceExtensionProperties(physicalDevice, null, ref count, null);
VK.ExtensionProperties[] props = new VK.ExtensionProperties[count];
VK.EnumerateDeviceExtensionProperties(physicalDevice, null, ref count, props);
for(int i = 0; i < props.Length; i++)
{
Console.WriteLine("\tExtensions Name: {0}", props[i].extensionName);
}
}
byte[] getEmbeddedResource(string resourceName)
{
Assembly[] asses = AppDomain.CurrentDomain.GetAssemblies();
foreach(Assembly ass in asses)
{
string[] resources = ass.GetManifestResourceNames();
foreach(string s in resources)
{
if(s == resourceName)
{
Stream stream = ass.GetManifestResourceStream(resourceName);
if(stream == null)
{
Console.WriteLine("Cannot find embedded resource {0}", resourceName);
return null;
}
using(var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
}
return null;
}
};
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// 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;
#if NET_2_0
using System.Collections.Generic;
#endif
namespace NUnit.Framework.Constraints
{
#region ConstraintOperator Base Class
/// <summary>
/// The ConstraintOperator class is used internally by a
/// ConstraintBuilder to represent an operator that
/// modifies or combines constraints.
///
/// Constraint operators use left and right precedence
/// values to determine whether the top operator on the
/// stack should be reduced before pushing a new operator.
/// </summary>
public abstract class ConstraintOperator
{
private object leftContext;
private object rightContext;
/// <summary>
/// The precedence value used when the operator
/// is about to be pushed to the stack.
/// </summary>
protected int left_precedence;
/// <summary>
/// The precedence value used when the operator
/// is on the top of the stack.
/// </summary>
protected int right_precedence;
/// <summary>
/// The syntax element preceding this operator
/// </summary>
public object LeftContext
{
get { return leftContext; }
set { leftContext = value; }
}
/// <summary>
/// The syntax element folowing this operator
/// </summary>
public object RightContext
{
get { return rightContext; }
set { rightContext = value; }
}
/// <summary>
/// The precedence value used when the operator
/// is about to be pushed to the stack.
/// </summary>
public virtual int LeftPrecedence
{
get { return left_precedence; }
}
/// <summary>
/// The precedence value used when the operator
/// is on the top of the stack.
/// </summary>
public virtual int RightPrecedence
{
get { return right_precedence; }
}
/// <summary>
/// Reduce produces a constraint from the operator and
/// any arguments. It takes the arguments from the constraint
/// stack and pushes the resulting constraint on it.
/// </summary>
/// <param name="stack"></param>
public abstract void Reduce(ConstraintBuilder.ConstraintStack stack);
}
#endregion
#region Prefix Operators
#region PrefixOperator
/// <summary>
/// PrefixOperator takes a single constraint and modifies
/// it's action in some way.
/// </summary>
public abstract class PrefixOperator : ConstraintOperator
{
/// <summary>
/// Reduce produces a constraint from the operator and
/// any arguments. It takes the arguments from the constraint
/// stack and pushes the resulting constraint on it.
/// </summary>
/// <param name="stack"></param>
public override void Reduce(ConstraintBuilder.ConstraintStack stack)
{
stack.Push(ApplyPrefix(stack.Pop()));
}
/// <summary>
/// Returns the constraint created by applying this
/// prefix to another constraint.
/// </summary>
/// <param name="constraint"></param>
/// <returns></returns>
public abstract Constraint ApplyPrefix(Constraint constraint);
}
#endregion
#region NotOperator
/// <summary>
/// Negates the test of the constraint it wraps.
/// </summary>
public class NotOperator : PrefixOperator
{
/// <summary>
/// Constructs a new NotOperator
/// </summary>
public NotOperator()
{
// Not stacks on anything and only allows other
// prefix ops to stack on top of it.
this.left_precedence = this.right_precedence = 1;
}
/// <summary>
/// Returns a NotConstraint applied to its argument.
/// </summary>
public override Constraint ApplyPrefix(Constraint constraint)
{
return new NotConstraint(constraint);
}
}
#endregion
#region Collection Operators
/// <summary>
/// Abstract base for operators that indicate how to
/// apply a constraint to items in a collection.
/// </summary>
public abstract class CollectionOperator : PrefixOperator
{
/// <summary>
/// Constructs a CollectionOperator
/// </summary>
public CollectionOperator()
{
// Collection Operators stack on everything
// and allow all other ops to stack on them
this.left_precedence = 1;
this.right_precedence = 10;
}
}
/// <summary>
/// Represents a constraint that succeeds if all the
/// members of a collection match a base constraint.
/// </summary>
public class AllOperator : CollectionOperator
{
/// <summary>
/// Returns a constraint that will apply the argument
/// to the members of a collection, succeeding if
/// they all succeed.
/// </summary>
public override Constraint ApplyPrefix(Constraint constraint)
{
return new AllItemsConstraint(constraint);
}
}
/// <summary>
/// Represents a constraint that succeeds if any of the
/// members of a collection match a base constraint.
/// </summary>
public class SomeOperator : CollectionOperator
{
/// <summary>
/// Returns a constraint that will apply the argument
/// to the members of a collection, succeeding if
/// any of them succeed.
/// </summary>
public override Constraint ApplyPrefix(Constraint constraint)
{
return new SomeItemsConstraint(constraint);
}
}
/// <summary>
/// Represents a constraint that succeeds if none of the
/// members of a collection match a base constraint.
/// </summary>
public class NoneOperator : CollectionOperator
{
/// <summary>
/// Returns a constraint that will apply the argument
/// to the members of a collection, succeeding if
/// none of them succeed.
/// </summary>
public override Constraint ApplyPrefix(Constraint constraint)
{
return new NoItemConstraint(constraint);
}
}
#endregion
#region WithOperator
/// <summary>
/// Represents a constraint that simply wraps the
/// constraint provided as an argument, without any
/// further functionality, but which modifes the
/// order of evaluation because of its precedence.
/// </summary>
public class WithOperator : PrefixOperator
{
/// <summary>
/// Constructor for the WithOperator
/// </summary>
public WithOperator()
{
this.left_precedence = 1;
this.right_precedence = 4;
}
/// <summary>
/// Returns a constraint that wraps its argument
/// </summary>
public override Constraint ApplyPrefix(Constraint constraint)
{
return constraint;
}
}
#endregion
#region SelfResolving Operators
#region SelfResolvingOperator
/// <summary>
/// Abstract base class for operators that are able to reduce to a
/// constraint whether or not another syntactic element follows.
/// </summary>
public abstract class SelfResolvingOperator : ConstraintOperator
{
}
#endregion
#region PropOperator
/// <summary>
/// Operator used to test for the presence of a named Property
/// on an object and optionally apply further tests to the
/// value of that property.
/// </summary>
public class PropOperator : SelfResolvingOperator
{
private string name;
/// <summary>
/// Gets the name of the property to which the operator applies
/// </summary>
public string Name
{
get { return name; }
}
/// <summary>
/// Constructs a PropOperator for a particular named property
/// </summary>
public PropOperator(string name)
{
this.name = name;
// Prop stacks on anything and allows only
// prefix operators to stack on it.
this.left_precedence = this.right_precedence = 1;
}
/// <summary>
/// Reduce produces a constraint from the operator and
/// any arguments. It takes the arguments from the constraint
/// stack and pushes the resulting constraint on it.
/// </summary>
/// <param name="stack"></param>
public override void Reduce(ConstraintBuilder.ConstraintStack stack)
{
if (RightContext == null || RightContext is BinaryOperator)
stack.Push(new PropertyExistsConstraint(name));
else
stack.Push(new PropertyConstraint(name, stack.Pop()));
}
}
#endregion
#region AttributeOperator
/// <summary>
/// Operator that tests for the presence of a particular attribute
/// on a type and optionally applies further tests to the attribute.
/// </summary>
public class AttributeOperator : SelfResolvingOperator
{
private Type type;
/// <summary>
/// Construct an AttributeOperator for a particular Type
/// </summary>
/// <param name="type">The Type of attribute tested</param>
public AttributeOperator(Type type)
{
this.type = type;
// Attribute stacks on anything and allows only
// prefix operators to stack on it.
this.left_precedence = this.right_precedence = 1;
}
/// <summary>
/// Reduce produces a constraint from the operator and
/// any arguments. It takes the arguments from the constraint
/// stack and pushes the resulting constraint on it.
/// </summary>
public override void Reduce(ConstraintBuilder.ConstraintStack stack)
{
if (RightContext == null || RightContext is BinaryOperator)
stack.Push(new AttributeExistsConstraint(type));
else
stack.Push(new AttributeConstraint(type, stack.Pop()));
}
}
#endregion
#region ThrowsOperator
/// <summary>
/// Operator that tests that an exception is thrown and
/// optionally applies further tests to the exception.
/// </summary>
public class ThrowsOperator : SelfResolvingOperator
{
/// <summary>
/// Construct a ThrowsOperator
/// </summary>
public ThrowsOperator()
{
// ThrowsOperator stacks on everything but
// it's always the first item on the stack
// anyway. It is evaluated last of all ops.
this.left_precedence = 1;
this.right_precedence = 100;
}
/// <summary>
/// Reduce produces a constraint from the operator and
/// any arguments. It takes the arguments from the constraint
/// stack and pushes the resulting constraint on it.
/// </summary>
public override void Reduce(ConstraintBuilder.ConstraintStack stack)
{
if (RightContext == null || RightContext is BinaryOperator)
stack.Push(new ThrowsConstraint(null));
else
stack.Push(new ThrowsConstraint(stack.Pop()));
}
}
#endregion
#endregion
#endregion
#region Binary Operators
#region BinaryOperator
/// <summary>
/// Abstract base class for all binary operators
/// </summary>
public abstract class BinaryOperator : ConstraintOperator
{
/// <summary>
/// Reduce produces a constraint from the operator and
/// any arguments. It takes the arguments from the constraint
/// stack and pushes the resulting constraint on it.
/// </summary>
/// <param name="stack"></param>
public override void Reduce(ConstraintBuilder.ConstraintStack stack)
{
Constraint right = stack.Pop();
Constraint left = stack.Pop();
stack.Push(ApplyOperator(left, right));
}
/// <summary>
/// Gets the left precedence of the operator
/// </summary>
public override int LeftPrecedence
{
get
{
return RightContext is CollectionOperator
? base.LeftPrecedence + 10
: base.LeftPrecedence;
}
}
/// <summary>
/// Gets the right precedence of the operator
/// </summary>
public override int RightPrecedence
{
get
{
return RightContext is CollectionOperator
? base.RightPrecedence + 10
: base.RightPrecedence;
}
}
/// <summary>
/// Abstract method that produces a constraint by applying
/// the operator to its left and right constraint arguments.
/// </summary>
public abstract Constraint ApplyOperator(Constraint left, Constraint right);
}
#endregion
#region AndOperator
/// <summary>
/// Operator that requires both it's arguments to succeed
/// </summary>
public class AndOperator : BinaryOperator
{
/// <summary>
/// Construct an AndOperator
/// </summary>
public AndOperator()
{
this.left_precedence = this.right_precedence = 2;
}
/// <summary>
/// Apply the operator to produce an AndConstraint
/// </summary>
public override Constraint ApplyOperator(Constraint left, Constraint right)
{
return new AndConstraint(left, right);
}
}
#endregion
#region OrOperator
/// <summary>
/// Operator that requires at least one of it's arguments to succeed
/// </summary>
public class OrOperator : BinaryOperator
{
/// <summary>
/// Construct an OrOperator
/// </summary>
public OrOperator()
{
this.left_precedence = this.right_precedence = 3;
}
/// <summary>
/// Apply the operator to produce an OrConstraint
/// </summary>
public override Constraint ApplyOperator(Constraint left, Constraint right)
{
return new OrConstraint(left, right);
}
}
#endregion
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Debug = System.Diagnostics.Debug;
namespace System.Xml.Linq
{
internal class XNodeReader : XmlReader, IXmlLineInfo
{
private static readonly char[] s_WhitespaceChars = new char[] { ' ', '\t', '\n', '\r' };
// The reader position is encoded by the tuple (source, parent).
// Lazy text uses (instance, parent element). Attribute value
// uses (instance, parent attribute). End element uses (instance,
// instance). Common XObject uses (instance, null).
private object _source;
private object _parent;
private ReadState _state;
private XNode _root;
private readonly XmlNameTable _nameTable;
private readonly bool _omitDuplicateNamespaces;
internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options)
{
_source = node;
_root = node;
_nameTable = nameTable != null ? nameTable : CreateNameTable();
_omitDuplicateNamespaces = (options & ReaderOptions.OmitDuplicateNamespaces) != 0 ? true : false;
}
internal XNodeReader(XNode node, XmlNameTable nameTable)
: this(node, nameTable,
(node.GetSaveOptionsFromAnnotations() & SaveOptions.OmitDuplicateNamespaces) != 0 ?
ReaderOptions.OmitDuplicateNamespaces : ReaderOptions.None)
{
}
public override int AttributeCount
{
get
{
if (!IsInteractive)
{
return 0;
}
int count = 0;
XElement e = GetElementInAttributeScope();
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a))
{
count++;
}
} while (a != e.lastAttr);
}
}
return count;
}
}
public override string BaseURI
{
get
{
XObject o = _source as XObject;
if (o != null)
{
return o.BaseUri;
}
o = _parent as XObject;
if (o != null)
{
return o.BaseUri;
}
return string.Empty;
}
}
public override int Depth
{
get
{
if (!IsInteractive)
{
return 0;
}
XObject o = _source as XObject;
if (o != null)
{
return GetDepth(o);
}
o = _parent as XObject;
if (o != null)
{
return GetDepth(o) + 1;
}
return 0;
}
}
private static int GetDepth(XObject o)
{
int depth = 0;
while (o.parent != null)
{
depth++;
o = o.parent;
}
if (o is XDocument)
{
depth--;
}
return depth;
}
public override bool EOF
{
get { return _state == ReadState.EndOfFile; }
}
public override bool HasAttributes
{
get
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null && e.lastAttr != null)
{
if (_omitDuplicateNamespaces)
{
return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next) != null;
}
else
{
return true;
}
}
else
{
return false;
}
}
}
public override bool HasValue
{
get
{
if (!IsInteractive)
{
return false;
}
XObject o = _source as XObject;
if (o != null)
{
switch (o.NodeType)
{
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.DocumentType:
return true;
default:
return false;
}
}
return true;
}
}
public override bool IsEmptyElement
{
get
{
if (!IsInteractive)
{
return false;
}
XElement e = _source as XElement;
return e != null && e.IsEmpty;
}
}
public override string LocalName
{
get { return _nameTable.Add(GetLocalName()); }
}
private string GetLocalName()
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = _source as XElement;
if (e != null)
{
return e.Name.LocalName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
return a.Name.LocalName;
}
XProcessingInstruction p = _source as XProcessingInstruction;
if (p != null)
{
return p.Target;
}
XDocumentType n = _source as XDocumentType;
if (n != null)
{
return n.Name;
}
return string.Empty;
}
public override string Name
{
get
{
string prefix = GetPrefix();
if (prefix.Length == 0)
{
return _nameTable.Add(GetLocalName());
}
return _nameTable.Add(string.Concat(prefix, ":", GetLocalName()));
}
}
public override string NamespaceURI
{
get { return _nameTable.Add(GetNamespaceURI()); }
}
private string GetNamespaceURI()
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = _source as XElement;
if (e != null)
{
return e.Name.NamespaceName;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
string namespaceName = a.Name.NamespaceName;
if (namespaceName.Length == 0 && a.Name.LocalName == "xmlns")
{
return XNamespace.xmlnsPrefixNamespace;
}
return namespaceName;
}
return string.Empty;
}
public override XmlNameTable NameTable
{
get { return _nameTable; }
}
public override XmlNodeType NodeType
{
get
{
if (!IsInteractive)
{
return XmlNodeType.None;
}
XObject o = _source as XObject;
if (o != null)
{
if (IsEndElement)
{
return XmlNodeType.EndElement;
}
XmlNodeType nt = o.NodeType;
if (nt != XmlNodeType.Text)
{
return nt;
}
if (o.parent != null && o.parent.parent == null && o.parent is XDocument)
{
return XmlNodeType.Whitespace;
}
return XmlNodeType.Text;
}
if (_parent is XDocument)
{
return XmlNodeType.Whitespace;
}
return XmlNodeType.Text;
}
}
public override string Prefix
{
get { return _nameTable.Add(GetPrefix()); }
}
private string GetPrefix()
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = _source as XElement;
if (e != null)
{
string prefix = e.GetPrefixOfNamespace(e.Name.Namespace);
if (prefix != null)
{
return prefix;
}
return string.Empty;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
string prefix = a.GetPrefixOfNamespace(a.Name.Namespace);
if (prefix != null)
{
return prefix;
}
}
return string.Empty;
}
public override ReadState ReadState
{
get { return _state; }
}
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = false;
return settings;
}
}
public override string Value
{
get
{
if (!IsInteractive)
{
return string.Empty;
}
XObject o = _source as XObject;
if (o != null)
{
switch (o.NodeType)
{
case XmlNodeType.Attribute:
return ((XAttribute)o).Value;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
return ((XText)o).Value;
case XmlNodeType.Comment:
return ((XComment)o).Value;
case XmlNodeType.ProcessingInstruction:
return ((XProcessingInstruction)o).Data;
case XmlNodeType.DocumentType:
return ((XDocumentType)o).InternalSubset;
default:
return string.Empty;
}
}
return (string)_source;
}
}
public override string XmlLang
{
get
{
if (!IsInteractive)
{
return string.Empty;
}
XElement e = GetElementInScope();
if (e != null)
{
XName name = XNamespace.Xml.GetName("lang");
do
{
XAttribute a = e.Attribute(name);
if (a != null)
{
return a.Value;
}
e = e.parent as XElement;
} while (e != null);
}
return string.Empty;
}
}
public override XmlSpace XmlSpace
{
get
{
if (!IsInteractive)
{
return XmlSpace.None;
}
XElement e = GetElementInScope();
if (e != null)
{
XName name = XNamespace.Xml.GetName("space");
do
{
XAttribute a = e.Attribute(name);
if (a != null)
{
switch (a.Value.Trim(s_WhitespaceChars))
{
case "preserve":
return XmlSpace.Preserve;
case "default":
return XmlSpace.Default;
default:
break;
}
}
e = e.parent as XElement;
} while (e != null);
}
return XmlSpace.None;
}
}
protected override void Dispose(bool disposing)
{
if (disposing && ReadState != ReadState.Closed)
{
Close();
}
}
public override void Close()
{
_source = null;
_parent = null;
_root = null;
_state = ReadState.Closed;
}
public override string GetAttribute(string name)
{
if (!IsInteractive)
{
return null;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
string localName, namespaceName;
GetNameInAttributeScope(name, e, out localName, out namespaceName);
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName)
{
if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
return null;
}
else
{
return a.Value;
}
}
} while (a != e.lastAttr);
}
return null;
}
XDocumentType n = _source as XDocumentType;
if (n != null)
{
switch (name)
{
case "PUBLIC":
return n.PublicId;
case "SYSTEM":
return n.SystemId;
}
}
return null;
}
public override string GetAttribute(string localName, string namespaceName)
{
if (!IsInteractive)
{
return null;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
if (localName == "xmlns")
{
if (namespaceName != null && namespaceName.Length == 0)
{
return null;
}
if (namespaceName == XNamespace.xmlnsPrefixNamespace)
{
namespaceName = string.Empty;
}
}
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName)
{
if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
return null;
}
else
{
return a.Value;
}
}
} while (a != e.lastAttr);
}
}
return null;
}
public override string GetAttribute(int index)
{
if (!IsInteractive)
{
return null;
}
if (index < 0)
{
return null;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a))
{
if (index-- == 0)
{
return a.Value;
}
}
} while (a != e.lastAttr);
}
}
return null;
}
public override string LookupNamespace(string prefix)
{
if (!IsInteractive)
{
return null;
}
if (prefix == null)
{
return null;
}
XElement e = GetElementInScope();
if (e != null)
{
XNamespace ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix);
if (ns != null)
{
return _nameTable.Add(ns.NamespaceName);
}
}
return null;
}
public override bool MoveToAttribute(string name)
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
string localName, namespaceName;
GetNameInAttributeScope(name, e, out localName, out namespaceName);
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName &&
a.Name.NamespaceName == namespaceName)
{
if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
// If it's a duplicate namespace attribute just act as if it doesn't exist
return false;
}
else
{
_source = a;
_parent = null;
return true;
}
}
} while (a != e.lastAttr);
}
}
return false;
}
public override bool MoveToAttribute(string localName, string namespaceName)
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
if (localName == "xmlns")
{
if (namespaceName != null && namespaceName.Length == 0)
{
return false;
}
if (namespaceName == XNamespace.xmlnsPrefixNamespace)
{
namespaceName = string.Empty;
}
}
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (a.Name.LocalName == localName &&
a.Name.NamespaceName == namespaceName)
{
if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a))
{
// If it's a duplicate namespace attribute just act as if it doesn't exist
return false;
}
else
{
_source = a;
_parent = null;
return true;
}
}
} while (a != e.lastAttr);
}
}
return false;
}
public override void MoveToAttribute(int index)
{
if (!IsInteractive)
{
return;
}
if (index < 0) throw new ArgumentOutOfRangeException(nameof(index));
XElement e = GetElementInAttributeScope();
if (e != null)
{
XAttribute a = e.lastAttr;
if (a != null)
{
do
{
a = a.next;
if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a))
{
// Only count those which are non-duplicates if we're asked to
if (index-- == 0)
{
_source = a;
_parent = null;
return;
}
}
} while (a != e.lastAttr);
}
}
throw new ArgumentOutOfRangeException(nameof(index));
}
public override bool MoveToElement()
{
if (!IsInteractive)
{
return false;
}
XAttribute a = _source as XAttribute;
if (a == null)
{
a = _parent as XAttribute;
}
if (a != null)
{
if (a.parent != null)
{
_source = a.parent;
_parent = null;
return true;
}
}
return false;
}
public override bool MoveToFirstAttribute()
{
if (!IsInteractive)
{
return false;
}
XElement e = GetElementInAttributeScope();
if (e != null)
{
if (e.lastAttr != null)
{
if (_omitDuplicateNamespaces)
{
object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next);
if (na == null)
{
return false;
}
_source = na;
}
else
{
_source = e.lastAttr.next;
}
return true;
}
}
return false;
}
public override bool MoveToNextAttribute()
{
if (!IsInteractive)
{
return false;
}
XElement e = _source as XElement;
if (e != null)
{
if (IsEndElement)
{
return false;
}
if (e.lastAttr != null)
{
if (_omitDuplicateNamespaces)
{
// Skip duplicate namespace attributes
// We must NOT modify the this.source until we find the one we're looking for
// because if we don't find anything, we need to stay positioned where we're now
object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next);
if (na == null)
{
return false;
}
_source = na;
}
else
{
_source = e.lastAttr.next;
}
return true;
}
return false;
}
XAttribute a = _source as XAttribute;
if (a == null)
{
a = _parent as XAttribute;
}
if (a != null)
{
if (a.parent != null && ((XElement)a.parent).lastAttr != a)
{
if (_omitDuplicateNamespaces)
{
// Skip duplicate namespace attributes
// We must NOT modify the this.source until we find the one we're looking for
// because if we don't find anything, we need to stay positioned where we're now
object na = GetFirstNonDuplicateNamespaceAttribute(a.next);
if (na == null)
{
return false;
}
_source = na;
}
else
{
_source = a.next;
}
_parent = null;
return true;
}
}
return false;
}
public override bool Read()
{
switch (_state)
{
case ReadState.Initial:
_state = ReadState.Interactive;
XDocument d = _source as XDocument;
if (d != null)
{
return ReadIntoDocument(d);
}
return true;
case ReadState.Interactive:
return Read(false);
default:
return false;
}
}
public override bool ReadAttributeValue()
{
if (!IsInteractive)
{
return false;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
return ReadIntoAttribute(a);
}
return false;
}
public override bool ReadToDescendant(string localName, string namespaceName)
{
if (!IsInteractive)
{
return false;
}
MoveToElement();
XElement c = _source as XElement;
if (c != null && !c.IsEmpty)
{
if (IsEndElement)
{
return false;
}
foreach (XElement e in c.Descendants())
{
if (e.Name.LocalName == localName &&
e.Name.NamespaceName == namespaceName)
{
_source = e;
return true;
}
}
IsEndElement = true;
}
return false;
}
public override bool ReadToFollowing(string localName, string namespaceName)
{
while (Read())
{
XElement e = _source as XElement;
if (e != null)
{
if (IsEndElement) continue;
if (e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName)
{
return true;
}
}
}
return false;
}
public override bool ReadToNextSibling(string localName, string namespaceName)
{
if (!IsInteractive)
{
return false;
}
MoveToElement();
if (_source != _root)
{
XNode n = _source as XNode;
if (n != null)
{
foreach (XElement e in n.ElementsAfterSelf())
{
if (e.Name.LocalName == localName &&
e.Name.NamespaceName == namespaceName)
{
_source = e;
IsEndElement = false;
return true;
}
}
if (n.parent is XElement)
{
_source = n.parent;
IsEndElement = true;
return false;
}
}
else
{
if (_parent is XElement)
{
_source = _parent;
_parent = null;
IsEndElement = true;
return false;
}
}
}
return ReadToEnd();
}
public override void ResolveEntity()
{
}
public override void Skip()
{
if (!IsInteractive)
{
return;
}
Read(true);
}
bool IXmlLineInfo.HasLineInfo()
{
if (IsEndElement)
{
// Special case for EndElement - we store the line info differently in this case
// we also know that the current node (source) is XElement
XElement e = _source as XElement;
if (e != null)
{
return e.Annotation<LineInfoEndElementAnnotation>() != null;
}
}
else
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.HasLineInfo();
}
}
return false;
}
int IXmlLineInfo.LineNumber
{
get
{
if (IsEndElement)
{
// Special case for EndElement - we store the line info differently in this case
// we also know that the current node (source) is XElement
XElement e = _source as XElement;
if (e != null)
{
LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>();
if (a != null)
{
return a.lineNumber;
}
}
}
else
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LineNumber;
}
}
return 0;
}
}
int IXmlLineInfo.LinePosition
{
get
{
if (IsEndElement)
{
// Special case for EndElement - we store the line info differently in this case
// we also know that the current node (source) is XElement
XElement e = _source as XElement;
if (e != null)
{
LineInfoEndElementAnnotation a = e.Annotation<LineInfoEndElementAnnotation>();
if (a != null)
{
return a.linePosition;
}
}
}
else
{
IXmlLineInfo li = _source as IXmlLineInfo;
if (li != null)
{
return li.LinePosition;
}
}
return 0;
}
}
private bool IsEndElement
{
get { return _parent == _source; }
set { _parent = value ? _source : null; }
}
private bool IsInteractive
{
get { return _state == ReadState.Interactive; }
}
private static XmlNameTable CreateNameTable()
{
XmlNameTable nameTable = new NameTable();
nameTable.Add(string.Empty);
nameTable.Add(XNamespace.xmlnsPrefixNamespace);
nameTable.Add(XNamespace.xmlPrefixNamespace);
return nameTable;
}
private XElement GetElementInAttributeScope()
{
XElement e = _source as XElement;
if (e != null)
{
if (IsEndElement)
{
return null;
}
return e;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
a = _parent as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
return null;
}
private XElement GetElementInScope()
{
XElement e = _source as XElement;
if (e != null)
{
return e;
}
XNode n = _source as XNode;
if (n != null)
{
return n.parent as XElement;
}
XAttribute a = _source as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
e = _parent as XElement;
if (e != null)
{
return e;
}
a = _parent as XAttribute;
if (a != null)
{
return (XElement)a.parent;
}
return null;
}
private static void GetNameInAttributeScope(string qualifiedName, XElement e, out string localName, out string namespaceName)
{
if (!string.IsNullOrEmpty(qualifiedName))
{
int i = qualifiedName.IndexOf(':');
if (i != 0 && i != qualifiedName.Length - 1)
{
if (i == -1)
{
localName = qualifiedName;
namespaceName = string.Empty;
return;
}
XNamespace ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i));
if (ns != null)
{
localName = qualifiedName.Substring(i + 1, qualifiedName.Length - i - 1);
namespaceName = ns.NamespaceName;
return;
}
}
}
localName = null;
namespaceName = null;
}
private bool Read(bool skipContent)
{
XElement e = _source as XElement;
if (e != null)
{
if (e.IsEmpty || IsEndElement || skipContent)
{
return ReadOverNode(e);
}
return ReadIntoElement(e);
}
XNode n = _source as XNode;
if (n != null)
{
return ReadOverNode(n);
}
XAttribute a = _source as XAttribute;
if (a != null)
{
return ReadOverAttribute(a, skipContent);
}
return ReadOverText(skipContent);
}
private bool ReadIntoDocument(XDocument d)
{
XNode n = d.content as XNode;
if (n != null)
{
_source = n.next;
return true;
}
string s = d.content as string;
if (s != null)
{
if (s.Length > 0)
{
_source = s;
_parent = d;
return true;
}
}
return ReadToEnd();
}
private bool ReadIntoElement(XElement e)
{
XNode n = e.content as XNode;
if (n != null)
{
_source = n.next;
return true;
}
string s = e.content as string;
if (s != null)
{
if (s.Length > 0)
{
_source = s;
_parent = e;
}
else
{
_source = e;
IsEndElement = true;
}
return true;
}
return ReadToEnd();
}
private bool ReadIntoAttribute(XAttribute a)
{
_source = a.value;
_parent = a;
return true;
}
private bool ReadOverAttribute(XAttribute a, bool skipContent)
{
XElement e = (XElement)a.parent;
if (e != null)
{
if (e.IsEmpty || skipContent)
{
return ReadOverNode(e);
}
return ReadIntoElement(e);
}
return ReadToEnd();
}
private bool ReadOverNode(XNode n)
{
if (n == _root)
{
return ReadToEnd();
}
XNode next = n.next;
if (null == next || next == n || n == n.parent.content)
{
if (n.parent == null || (n.parent.parent == null && n.parent is XDocument))
{
return ReadToEnd();
}
_source = n.parent;
IsEndElement = true;
}
else
{
_source = next;
IsEndElement = false;
}
return true;
}
private bool ReadOverText(bool skipContent)
{
if (_parent is XElement)
{
_source = _parent;
_parent = null;
IsEndElement = true;
return true;
}
XAttribute parent = _parent as XAttribute;
if (parent != null)
{
_parent = null;
return ReadOverAttribute(parent, skipContent);
}
return ReadToEnd();
}
private bool ReadToEnd()
{
_state = ReadState.EndOfFile;
return false;
}
/// <summary>
/// Determines if the specified attribute would be a duplicate namespace declaration
/// - one which we already reported on some ancestor, so it's not necessary to report it here
/// </summary>
/// <param name="candidateAttribute">The attribute to test.</param>
/// <returns>true if the attribute is a duplicate namespace declaration attribute</returns>
private bool IsDuplicateNamespaceAttribute(XAttribute candidateAttribute)
{
if (!candidateAttribute.IsNamespaceDeclaration)
{
return false;
}
else
{
// Split the method in two to enable inlining of this piece (Which will work for 95% of cases)
return IsDuplicateNamespaceAttributeInner(candidateAttribute);
}
}
private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute)
{
// First of all - if this is an xmlns:xml declaration then it's a duplicate
// since xml prefix can't be redeclared and it's declared by default always.
if (candidateAttribute.Name.LocalName == "xml")
{
return true;
}
// The algorithm we use is:
// Go up the tree (but don't go higher than the root of this reader)
// and find the closest namespace declaration attribute which declares the same prefix
// If it declares that prefix to the exact same URI as ours does then ours is a duplicate
// Note that if we find a namespace declaration for the same prefix but with a different URI, then we don't have a dupe!
XElement element = candidateAttribute.parent as XElement;
if (element == _root || element == null)
{
// If there's only the parent element of our attribute, there can be no duplicates
return false;
}
element = element.parent as XElement;
while (element != null)
{
// Search all attributes of this element for the same prefix declaration
// Trick - a declaration for the same prefix will have the exact same XName - so we can do a quick ref comparison of names
// (The default ns decl is represented by an XName "xmlns{}", even if you try to create
// an attribute with XName "xmlns{http://www.w3.org/2000/xmlns/}" it will fail,
// because it's treated as a declaration of prefix "xmlns" which is invalid)
XAttribute a = element.lastAttr;
if (a != null)
{
do
{
if (a.name == candidateAttribute.name)
{
// Found the same prefix decl
if (a.Value == candidateAttribute.Value)
{
// And it's for the same namespace URI as well - so ours is a duplicate
return true;
}
else
{
// It's not for the same namespace URI - which means we have to keep ours
// (no need to continue the search as this one overrides anything above it)
return false;
}
}
a = a.next;
} while (a != element.lastAttr);
}
if (element == _root)
{
return false;
}
element = element.parent as XElement;
}
return false;
}
/// <summary>
/// Finds a first attribute (starting with the parameter) which is not a duplicate namespace attribute
/// </summary>
/// <param name="candidate">The attribute to start with</param>
/// <returns>The first attribute which is not a namespace attribute or null if the end of attributes has bean reached</returns>
private XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate)
{
Debug.Assert(_omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute." +
"For perf reason it's better to test this flag in the caller method.");
if (!IsDuplicateNamespaceAttribute(candidate))
{
return candidate;
}
XElement e = candidate.parent as XElement;
if (e != null && candidate != e.lastAttr)
{
do
{
candidate = candidate.next;
if (!IsDuplicateNamespaceAttribute(candidate))
{
return candidate;
}
} while (candidate != e.lastAttr);
}
return null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MigAz.Azure.Generator.AsmToArm;
using MigAz.Tests.Fakes;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Threading.Tasks;
using MigAz.Azure;
using MigAz.Azure.UserControls;
using MigAz.Azure.MigrationTarget;
using MigAz.Azure.Core;
namespace MigAz.Tests
{
[TestClass]
public class StorageTests
{
[TestMethod]
public async Task LoadASMObjectsFromSampleOfflineFile()
{
string restResponseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestDocs\\NewTest1\\AsmObjectsOffline.json");
TargetSettings targetSettings = new FakeSettingsProvider().GetTargetSettings();
AzureEnvironment azureEnvironment = AzureEnvironment.GetAzureEnvironments()[0];
AzureContext azureContextUSCommercial = await TestHelper.SetupAzureContext(azureEnvironment, restResponseFile);
await azureContextUSCommercial.AzureSubscription.InitializeChildrenAsync(true);
await azureContextUSCommercial.AzureSubscription.BindAsmResources(targetSettings);
AzureGenerator templateGenerator = await TestHelper.SetupTemplateGenerator(azureContextUSCommercial);
var artifacts = new ExportArtifacts(azureContextUSCommercial.AzureSubscription);
artifacts.ResourceGroup = await TestHelper.GetTargetResourceGroup(azureContextUSCommercial);
//foreach (Azure.MigrationTarget.StorageAccount s in azureContextUSCommercial.AzureRetriever.AsmTargetStorageAccounts)
//{
// artifacts.StorageAccounts.Add(s);
//}
await artifacts.ValidateAzureResources();
Assert.IsFalse(artifacts.HasErrors, "Template Generation cannot occur as the are error(s).");
templateGenerator.ExportArtifacts = artifacts;
await templateGenerator.GenerateStreams();
JObject templateJson = JObject.Parse(await templateGenerator.GetTemplateString());
Assert.AreEqual(0, templateJson["resources"].Children().Count());
//var resource = templateJson["resources"].Single();
//Assert.AreEqual("Microsoft.Storage/storageAccounts", resource["type"].Value<string>());
//Assert.AreEqual("asmtest8155v2", resource["name"].Value<string>());
//Assert.AreEqual("[resourceGroup().location]", resource["location"].Value<string>());
//Assert.AreEqual("Standard_LRS", resource["properties"]["accountType"].Value<string>());
}
[TestMethod]
public async Task LoadARMObjectsFromSampleOfflineFile()
{
string restResponseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestDocs\\NewTest1\\ArmObjectsOffline.json");
TargetSettings targetSettings = new FakeSettingsProvider().GetTargetSettings();
AzureEnvironment azureEnvironment = AzureEnvironment.GetAzureEnvironments()[0];
AzureContext azureContextUSCommercial = await TestHelper.SetupAzureContext(azureEnvironment, restResponseFile);
await azureContextUSCommercial.AzureSubscription.InitializeChildrenAsync(true);
await azureContextUSCommercial.AzureSubscription.BindArmResources(targetSettings);
AzureGenerator templateGenerator = await TestHelper.SetupTemplateGenerator(azureContextUSCommercial);
var artifacts = new ExportArtifacts(azureContextUSCommercial.AzureSubscription);
artifacts.ResourceGroup = await TestHelper.GetTargetResourceGroup(azureContextUSCommercial);
//foreach (Azure.MigrationTarget.StorageAccount s in azureContextUSCommercial.AzureRetriever.ArmTargetStorageAccounts)
//{
// artifacts.StorageAccounts.Add(s);
//}
await artifacts.ValidateAzureResources();
Assert.IsFalse(artifacts.HasErrors, "Template Generation cannot occur as the are error(s).");
templateGenerator.ExportArtifacts = artifacts;
await templateGenerator.GenerateStreams();
JObject templateJson = JObject.Parse(await templateGenerator.GetTemplateString());
Assert.AreEqual(0, templateJson["resources"].Children().Count());
//var resource = templateJson["resources"].First();
//Assert.AreEqual("Microsoft.Storage/storageAccounts", resource["type"].Value<string>());
//Assert.AreEqual("manageddiskdiag857v2", resource["name"].Value<string>());
//Assert.AreEqual("[resourceGroup().location]", resource["location"].Value<string>());
//Assert.AreEqual("Standard_LRS", resource["properties"]["accountType"].Value<string>());
}
[TestMethod]
public async Task LoadARMObjectsFromSampleOfflineFile2()
{
string restResponseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestDocs\\NewTest1\\temp.json");
TargetSettings targetSettings = new FakeSettingsProvider().GetTargetSettings();
AzureEnvironment azureEnvironment = AzureEnvironment.GetAzureEnvironments()[0];
AzureContext azureContextUSCommercial = await TestHelper.SetupAzureContext(azureEnvironment, restResponseFile);
await azureContextUSCommercial.AzureSubscription.InitializeChildrenAsync(true);
await azureContextUSCommercial.AzureSubscription.BindArmResources(targetSettings);
AzureGenerator templateGenerator = await TestHelper.SetupTemplateGenerator(azureContextUSCommercial);
var artifacts = new ExportArtifacts(azureContextUSCommercial.AzureSubscription);
artifacts.ResourceGroup = await TestHelper.GetTargetResourceGroup(azureContextUSCommercial);
artifacts.VirtualMachines.Add(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualMachines[0]);
artifacts.VirtualMachines[0].OSVirtualHardDisk.DiskSizeInGB = 128;
await artifacts.ValidateAzureResources();
Assert.IsNotNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' utilizes Network Security Group (NSG) 'ManagedDisk01-nsg-nsg', but the NSG resource is not added into the migration template."));
artifacts.NetworkSecurityGroups.Add(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0]);
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' utilizes Network Security Group (NSG) 'ManagedDisk01-nsg-nsg', but the NSG resource is not added into the migration template."));
Assert.IsNotNull(artifacts.SeekAlert("Target Virtual Network 'ManagedDiskvnet-vnet' for Virtual Machine 'ManagedDisk01-vm' Network Interface 'manageddisk01549-nic' is invalid, as it is not included in the migration / template."));
artifacts.VirtualNetworks.Add(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0]);
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Target Virtual Network 'ManagedDiskvnet-vnet' for Virtual Machine 'ManagedDisk01-vm' Network Interface 'manageddisk01549-nic' is invalid, as it is not included in the migration / template."));
Assert.IsNotNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' IP Configuration 'ipconfig1' utilizes Public IP 'ManagedDisk01-ip', but the Public IP resource is not added into the migration template."));
artifacts.PublicIPs.Add(azureContextUSCommercial.AzureSubscription.ArmTargetPublicIPs[0]);
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' IP Configuration 'ipconfig1' utilizes Public IP 'ManagedDisk01-ip', but the Public IP resource is not added into the migration template."));
Assert.IsNotNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDisk01_OsDisk_1_e901d155e5404b6a912afb22e7a804a6' which has not been added as an export resource."));
artifacts.Disks.Add(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[1]);
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDisk01_OsDisk_1_e901d155e5404b6a912afb22e7a804a6' which has not been added as an export resource."));
Assert.IsNotNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDataDisk01' which has not been added as an export resource."));
artifacts.Disks.Add(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0]);
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Virtual Machine 'ManagedDisk01' references Managed Disk 'ManagedDataDisk01' which has not been added as an export resource."));
Assert.IsNotNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' is used by Virtual Machine 'ManagedDisk01-vm', but is not included in the exported resources."));
artifacts.NetworkInterfaces.Add(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0]);
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Network Interface Card (NIC) 'manageddisk01549-nic' is used by Virtual Machine 'ManagedDisk01-vm', but is not included in the exported resources."));
Assert.IsTrue(artifacts.VirtualMachines[0].TargetSize.ToString() == "Standard_A1");
await artifacts.ValidateAzureResources();
Assert.IsFalse(artifacts.HasErrors, "Template Generation cannot occur as the are error(s).");
ManagedDiskStorage managedDiskStorage = new ManagedDiskStorage(artifacts.VirtualMachines[0].OSVirtualHardDisk.SourceDisk);
managedDiskStorage.StorageAccountType = Azure.Core.Interface.StorageAccountType.Premium_LRS;
artifacts.VirtualMachines[0].OSVirtualHardDisk.TargetStorage = managedDiskStorage;
await artifacts.ValidateAzureResources();
Assert.IsNotNull(artifacts.SeekAlert("Premium Disk based Virtual Machines must be of VM Series 'B', 'DS', 'DS v2', 'DS v3', 'GS', 'GS v2', 'Ls' or 'Fs'."));
artifacts.VirtualMachines[0].TargetSize = artifacts.ResourceGroup.TargetLocation.SeekVmSize("Standard_DS2_v2");
await artifacts.ValidateAzureResources();
Assert.IsNull(artifacts.SeekAlert("Premium Disk based Virtual Machines must be of VM Series 'B', 'DS', 'DS v2', 'DS v3', 'GS', 'GS v2', 'Ls' or 'Fs'."));
Assert.IsFalse(artifacts.HasErrors, "Template Generation cannot occur as the are error(s).");
templateGenerator.ExportArtifacts = artifacts;
await templateGenerator.GenerateStreams();
JObject templateJson = JObject.Parse(await templateGenerator.GetTemplateString());
Assert.AreEqual(7, templateJson["resources"].Children().Count());
var resource = templateJson["resources"].First();
Assert.AreEqual("Microsoft.Network/networkSecurityGroups", resource["type"].Value<string>());
Assert.AreEqual("ManagedDisk01-nsg-nsg", resource["name"].Value<string>());
Assert.AreEqual("[resourceGroup().location]", resource["location"].Value<string>());
}
[TestMethod]
public async Task OfflineUITargetTreeViewTest()
{
string restResponseFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestDocs\\NewTest1\\temp.json");
TargetSettings targetSettings = new FakeSettingsProvider().GetTargetSettings();
AzureEnvironment azureEnvironment = AzureEnvironment.GetAzureEnvironments()[0];
AzureContext azureContextUSCommercial = await TestHelper.SetupAzureContext(azureEnvironment, restResponseFile);
await azureContextUSCommercial.AzureSubscription.InitializeChildrenAsync(true);
await azureContextUSCommercial.AzureSubscription.BindArmResources(targetSettings);
AzureGenerator templateGenerator = await TestHelper.SetupTemplateGenerator(azureContextUSCommercial);
var artifacts = new ExportArtifacts(azureContextUSCommercial.AzureSubscription);
artifacts.ResourceGroup = await TestHelper.GetTargetResourceGroup(azureContextUSCommercial);
TargetTreeView targetTreeView = new TargetTreeView();
targetTreeView.TargetSettings = targetSettings;
await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0]);
targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0]);
Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0].GetType(), "Object type mismatch");
Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetRouteTables[0], "Not the correct object");
await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0]);
targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0]);
Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0].GetType(), "Object type mismatch");
Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetVirtualNetworks[0], "Not the correct object");
await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0]);
targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0]);
Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0].GetType(), "Object type mismatch");
Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkInterfaces[0], "Not the correct object");
await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0]);
targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0]);
Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0].GetType(), "Object type mismatch");
Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetManagedDisks[0], "Not the correct object");
await targetTreeView.AddMigrationTarget(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0]);
targetTreeView.SeekAlertSource(azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0]);
Assert.IsTrue(targetTreeView.SelectedNode != null, "Selected Node is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag != null, "Selected Node Tag is null");
Assert.IsTrue(targetTreeView.SelectedNode.Tag.GetType() == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0].GetType(), "Object type mismatch");
Assert.IsTrue(targetTreeView.SelectedNode.Tag == azureContextUSCommercial.AzureSubscription.ArmTargetNetworkSecurityGroups[0], "Not the correct object");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
namespace System.Drawing
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
#if netcoreapp
[TypeConverter("System.Drawing.IconConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")]
#endif
public sealed partial class Icon : MarshalByRefObject, ICloneable, IDisposable, ISerializable
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
private static int s_bitDepth;
// The PNG signature is specified at http://www.w3.org/TR/PNG/#5PNG-file-signature
private const int PNGSignature1 = 137 + ('P' << 8) + ('N' << 16) + ('G' << 24);
private const int PNGSignature2 = 13 + (10 << 8) + (26 << 16) + (10 << 24);
// Icon data
private readonly byte[] _iconData;
private int _bestImageOffset;
private int _bestBitDepth;
private int _bestBytesInRes;
private bool? _isBestImagePng = null;
private Size _iconSize = Size.Empty;
private IntPtr _handle = IntPtr.Zero;
private bool _ownHandle = true;
private Icon() { }
internal Icon(IntPtr handle) : this(handle, false)
{
}
internal Icon(IntPtr handle, bool takeOwnership)
{
if (handle == IntPtr.Zero)
{
throw new ArgumentException(SR.Format(SR.InvalidGDIHandle, nameof(Icon)));
}
_handle = handle;
_ownHandle = takeOwnership;
}
public Icon(string fileName) : this(fileName, 0, 0)
{
}
public Icon(string fileName, Size size) : this(fileName, size.Width, size.Height)
{
}
public Icon(string fileName, int width, int height) : this()
{
using (FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Debug.Assert(f != null, "File.OpenRead returned null instead of throwing an exception");
_iconData = new byte[(int)f.Length];
f.Read(_iconData, 0, _iconData.Length);
}
Initialize(width, height);
}
public Icon(Icon original, Size size) : this(original, size.Width, size.Height)
{
}
public Icon(Icon original, int width, int height) : this()
{
if (original == null)
{
throw new ArgumentNullException(nameof(original));
}
_iconData = original._iconData;
if (_iconData == null)
{
_iconSize = original.Size;
_handle = SafeNativeMethods.CopyImage(new HandleRef(original, original.Handle), SafeNativeMethods.IMAGE_ICON, _iconSize.Width, _iconSize.Height, 0);
}
else
{
Initialize(width, height);
}
}
public Icon(Type type, string resource) : this()
{
Stream stream = type.Module.Assembly.GetManifestResourceStream(type, resource);
if (stream == null)
{
throw new ArgumentException(SR.Format(SR.ResourceNotFound, type, resource));
}
_iconData = new byte[(int)stream.Length];
stream.Read(_iconData, 0, _iconData.Length);
Initialize(0, 0);
}
public Icon(Stream stream) : this(stream, 0, 0)
{
}
public Icon(Stream stream, Size size) : this(stream, size.Width, size.Height)
{
}
public Icon(Stream stream, int width, int height) : this()
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
_iconData = new byte[(int)stream.Length];
stream.Read(_iconData, 0, _iconData.Length);
Initialize(width, height);
}
private Icon(SerializationInfo info, StreamingContext context)
{
_iconData = (byte[])info.GetValue("IconData", typeof(byte[])); // Do not rename (binary serialization)
_iconSize = (Size)info.GetValue("IconSize", typeof(Size)); // Do not rename (binary serialization)
Initialize(_iconSize.Width, _iconSize.Height);
}
void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
{
if (_iconData != null)
{
si.AddValue("IconData", _iconData, typeof(byte[])); // Do not rename (binary serialization)
}
else
{
MemoryStream stream = new MemoryStream();
Save(stream);
si.AddValue("IconData", stream.ToArray(), typeof(byte[])); // Do not rename (binary serialization)
}
si.AddValue("IconSize", _iconSize, typeof(Size)); // Do not rename (binary serialization)
}
public static Icon ExtractAssociatedIcon(string filePath) => ExtractAssociatedIcon(filePath, 0);
private static Icon ExtractAssociatedIcon(string filePath, int index)
{
if (filePath == null)
{
throw new ArgumentNullException(nameof(filePath));
}
Uri uri;
try
{
uri = new Uri(filePath);
}
catch (UriFormatException)
{
// It's a relative pathname, get its full path as a file.
filePath = Path.GetFullPath(filePath);
uri = new Uri(filePath);
}
if (!uri.IsFile)
{
return null;
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
var sb = new StringBuilder(NativeMethods.MAX_PATH);
sb.Append(filePath);
IntPtr hIcon = SafeNativeMethods.ExtractAssociatedIcon(NativeMethods.NullHandleRef, sb, ref index);
if (hIcon != IntPtr.Zero)
{
return new Icon(hIcon, true);
}
return null;
}
[Browsable(false)]
public IntPtr Handle
{
get
{
if (_handle == IntPtr.Zero)
{
throw new ObjectDisposedException(GetType().Name);
}
return _handle;
}
}
[Browsable(false)]
public int Height => Size.Height;
public Size Size
{
get
{
if (_iconSize.IsEmpty)
{
var info = new SafeNativeMethods.ICONINFO();
SafeNativeMethods.GetIconInfo(new HandleRef(this, Handle), info);
var bmp = new SafeNativeMethods.BITMAP();
if (info.hbmColor != IntPtr.Zero)
{
SafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor));
_iconSize = new Size(bmp.bmWidth, bmp.bmHeight);
}
else if (info.hbmMask != IntPtr.Zero)
{
SafeNativeMethods.GetObject(new HandleRef(null, info.hbmMask), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
_iconSize = new Size(bmp.bmWidth, bmp.bmHeight / 2);
}
if (info.hbmMask != IntPtr.Zero)
{
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask));
}
}
return _iconSize;
}
}
[Browsable(false)]
public int Width => Size.Width;
public object Clone() => new Icon(this, Size.Width, Size.Height);
// Called when this object is going to destroy it's Win32 handle. You
// may override this if there is something special you need to do to
// destroy the handle. This will be called even if the handle is not
// owned by this object, which is handy if you want to create a
// derived class that has it's own create/destroy semantics.
//
// The default implementation will call the appropriate Win32
// call to destroy the handle if this object currently owns the
// handle. It will do nothing if the object does not currently
// own the handle.
internal void DestroyHandle()
{
if (_ownHandle)
{
SafeNativeMethods.DestroyIcon(new HandleRef(this, _handle));
_handle = IntPtr.Zero;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_handle != IntPtr.Zero)
{
#if FINALIZATION_WATCH
if (!disposing)
{
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
}
#endif
DestroyHandle();
}
}
// Draws this image to a graphics object. The drawing command originates on the graphics
// object, but a graphics object generally has no idea how to render a given image. So,
// it passes the call to the actual image. This version crops the image to the given
// dimensions and allows the user to specify a rectangle within the image to draw.
private void DrawIcon(IntPtr dc, Rectangle imageRect, Rectangle targetRect, bool stretch)
{
int imageX = 0;
int imageY = 0;
int imageWidth;
int imageHeight;
int targetX = 0;
int targetY = 0;
int targetWidth = 0;
int targetHeight = 0;
Size cursorSize = Size;
// Compute the dimensions of the icon if needed.
if (!imageRect.IsEmpty)
{
imageX = imageRect.X;
imageY = imageRect.Y;
imageWidth = imageRect.Width;
imageHeight = imageRect.Height;
}
else
{
imageWidth = cursorSize.Width;
imageHeight = cursorSize.Height;
}
if (!targetRect.IsEmpty)
{
targetX = targetRect.X;
targetY = targetRect.Y;
targetWidth = targetRect.Width;
targetHeight = targetRect.Height;
}
else
{
targetWidth = cursorSize.Width;
targetHeight = cursorSize.Height;
}
int drawWidth, drawHeight;
int clipWidth, clipHeight;
if (stretch)
{
drawWidth = cursorSize.Width * targetWidth / imageWidth;
drawHeight = cursorSize.Height * targetHeight / imageHeight;
clipWidth = targetWidth;
clipHeight = targetHeight;
}
else
{
drawWidth = cursorSize.Width;
drawHeight = cursorSize.Height;
clipWidth = targetWidth < imageWidth ? targetWidth : imageWidth;
clipHeight = targetHeight < imageHeight ? targetHeight : imageHeight;
}
// The ROP is SRCCOPY, so we can be simple here and take
// advantage of clipping regions. Drawing the cursor
// is merely a matter of offsetting and clipping.
IntPtr hSaveRgn = SafeNativeMethods.SaveClipRgn(dc);
try
{
SafeNativeMethods.IntersectClipRect(new HandleRef(this, dc), targetX, targetY, targetX + clipWidth, targetY + clipHeight);
SafeNativeMethods.DrawIconEx(new HandleRef(null, dc),
targetX - imageX,
targetY - imageY,
new HandleRef(this, _handle),
drawWidth,
drawHeight,
0,
NativeMethods.NullHandleRef,
SafeNativeMethods.DI_NORMAL);
}
finally
{
SafeNativeMethods.RestoreClipRgn(dc, hSaveRgn);
}
}
internal void Draw(Graphics graphics, int x, int y)
{
Size size = Size;
Draw(graphics, new Rectangle(x, y, size.Width, size.Height));
}
// Draws this image to a graphics object. The drawing command originates on the graphics
// object, but a graphics object generally has no idea how to render a given image. So,
// it passes the call to the actual image. This version stretches the image to the given
// dimensions and allows the user to specify a rectangle within the image to draw.
internal void Draw(Graphics graphics, Rectangle targetRect)
{
Rectangle copy = targetRect;
copy.X += (int)graphics.Transform.OffsetX;
copy.Y += (int)graphics.Transform.OffsetY;
using (WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics, ApplyGraphicsProperties.Clipping))
{
IntPtr dc = wg.GetHdc();
DrawIcon(dc, Rectangle.Empty, copy, true);
}
}
// Draws this image to a graphics object. The drawing command originates on the graphics
// object, but a graphics object generally has no idea how to render a given image. So,
// it passes the call to the actual image. This version crops the image to the given
// dimensions and allows the user to specify a rectangle within the image to draw.
internal void DrawUnstretched(Graphics graphics, Rectangle targetRect)
{
Rectangle copy = targetRect;
copy.X += (int)graphics.Transform.OffsetX;
copy.Y += (int)graphics.Transform.OffsetY;
using (WindowsGraphics wg = WindowsGraphics.FromGraphics(graphics, ApplyGraphicsProperties.Clipping))
{
IntPtr dc = wg.GetHdc();
DrawIcon(dc, Rectangle.Empty, copy, false);
}
}
~Icon() => Dispose(false);
public static Icon FromHandle(IntPtr handle) => new Icon(handle);
private unsafe short GetShort(byte* pb)
{
int retval = 0;
if (0 != (unchecked((byte)pb) & 1))
{
retval = *pb;
pb++;
retval = unchecked(retval | (*pb << 8));
}
else
{
retval = unchecked(*(short*)pb);
}
return unchecked((short)retval);
}
private unsafe int GetInt(byte* pb)
{
int retval = 0;
if (0 != (unchecked((byte)pb) & 3))
{
retval = *pb; pb++;
retval = retval | (*pb << 8); pb++;
retval = retval | (*pb << 16); pb++;
retval = unchecked(retval | (*pb << 24));
}
else
{
retval = *(int*)pb;
}
return retval;
}
// Initializes this Image object. This is identical to calling the image's
// constructor with picture, but this allows non-constructor initialization,
// which may be necessary in some instances.
private unsafe void Initialize(int width, int height)
{
if (_iconData == null || _handle != IntPtr.Zero)
{
throw new InvalidOperationException(SR.Format(SR.IllegalState, GetType().Name));
}
int icondirSize = Marshal.SizeOf(typeof(SafeNativeMethods.ICONDIR));
if (_iconData.Length < icondirSize)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
// Get the correct width and height.
if (width == 0)
{
width = UnsafeNativeMethods.GetSystemMetrics(SafeNativeMethods.SM_CXICON);
}
if (height == 0)
{
height = UnsafeNativeMethods.GetSystemMetrics(SafeNativeMethods.SM_CYICON);
}
if (s_bitDepth == 0)
{
IntPtr dc = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
s_bitDepth = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, dc), SafeNativeMethods.BITSPIXEL);
s_bitDepth *= UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, dc), SafeNativeMethods.PLANES);
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, dc));
// If the bitdepth is 8, make it 4 because windows does not
// choose a 256 color icon if the display is running in 256 color mode
// due to palette flicker.
if (s_bitDepth == 8)
{
s_bitDepth = 4;
}
}
fixed (byte* pbIconData = _iconData)
{
short idReserved = GetShort(pbIconData);
short idType = GetShort(pbIconData + 2);
short idCount = GetShort(pbIconData + 4);
if (idReserved != 0 || idType != 1 || idCount == 0)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
SafeNativeMethods.ICONDIRENTRY EntryTemp;
byte bestWidth = 0;
byte bestHeight = 0;
byte* pbIconDirEntry = unchecked(pbIconData + 6);
int icondirEntrySize = Marshal.SizeOf(typeof(SafeNativeMethods.ICONDIRENTRY));
if ((icondirEntrySize * (idCount - 1) + icondirSize) > _iconData.Length)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
for (int i = 0; i < idCount; i++)
{
// Fill in EntryTemp
EntryTemp.bWidth = pbIconDirEntry[0];
EntryTemp.bHeight = pbIconDirEntry[1];
EntryTemp.bColorCount = pbIconDirEntry[2];
EntryTemp.bReserved = pbIconDirEntry[3];
EntryTemp.wPlanes = GetShort(pbIconDirEntry + 4);
EntryTemp.wBitCount = GetShort(pbIconDirEntry + 6);
EntryTemp.dwBytesInRes = GetInt(pbIconDirEntry + 8);
EntryTemp.dwImageOffset = GetInt(pbIconDirEntry + 12);
bool fUpdateBestFit = false;
int iconBitDepth = 0;
if (EntryTemp.bColorCount != 0)
{
iconBitDepth = 4;
if (EntryTemp.bColorCount < 0x10)
{
iconBitDepth = 1;
}
}
else
{
iconBitDepth = EntryTemp.wBitCount;
}
// If it looks like if nothing is specified at this point then set the bits per pixel to 8.
if (iconBitDepth == 0)
{
iconBitDepth = 8;
}
// Windows rules for specifing an icon:
//
// 1. The icon with the closest size match.
// 2. For matching sizes, the image with the closest bit depth.
// 3. If there is no color depth match, the icon with the closest color depth that does not exceed the display.
// 4. If all icon color depth > display, lowest color depth is chosen.
// 5. color depth of > 8bpp are all equal.
// 6. Never choose an 8bpp icon on an 8bpp system.
//
if (_bestBytesInRes == 0)
{
fUpdateBestFit = true;
}
else
{
int bestDelta = Math.Abs(bestWidth - width) + Math.Abs(bestHeight - height);
int thisDelta = Math.Abs(EntryTemp.bWidth - width) + Math.Abs(EntryTemp.bHeight - height);
if ((thisDelta < bestDelta) ||
(thisDelta == bestDelta && (iconBitDepth <= s_bitDepth && iconBitDepth > _bestBitDepth || _bestBitDepth > s_bitDepth && iconBitDepth < _bestBitDepth)))
{
fUpdateBestFit = true;
}
}
if (fUpdateBestFit)
{
bestWidth = EntryTemp.bWidth;
bestHeight = EntryTemp.bHeight;
_bestImageOffset = EntryTemp.dwImageOffset;
_bestBytesInRes = EntryTemp.dwBytesInRes;
_bestBitDepth = iconBitDepth;
}
pbIconDirEntry += icondirEntrySize;
}
if (_bestImageOffset < 0)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
if (_bestBytesInRes < 0)
{
throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER);
}
int endOffset;
try
{
endOffset = checked(_bestImageOffset + _bestBytesInRes);
}
catch (OverflowException)
{
throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER);
}
if (endOffset > _iconData.Length)
{
throw new ArgumentException(SR.Format(SR.InvalidPictureType, "picture", nameof(Icon)));
}
// Copy the bytes into an aligned buffer if needed.
if ((_bestImageOffset % IntPtr.Size) != 0)
{
// Beginning of icon's content is misaligned.
byte[] alignedBuffer = new byte[_bestBytesInRes];
Array.Copy(_iconData, _bestImageOffset, alignedBuffer, 0, _bestBytesInRes);
fixed (byte* pbAlignedBuffer = alignedBuffer)
{
_handle = SafeNativeMethods.CreateIconFromResourceEx(pbAlignedBuffer, _bestBytesInRes, true, 0x00030000, 0, 0, 0);
}
}
else
{
try
{
_handle = SafeNativeMethods.CreateIconFromResourceEx(checked(pbIconData + _bestImageOffset), _bestBytesInRes, true, 0x00030000, 0, 0, 0);
}
catch (OverflowException)
{
throw new Win32Exception(SafeNativeMethods.ERROR_INVALID_PARAMETER);
}
}
if (_handle == IntPtr.Zero)
{
throw new Win32Exception();
}
}
}
public void Save(Stream outputStream)
{
if (_iconData != null)
{
outputStream.Write(_iconData, 0, _iconData.Length);
}
else
{
// Ideally, we would pick apart the icon using
// GetIconInfo, and then pull the individual bitmaps out,
// converting them to DIBS and saving them into the file.
// But, in the interest of simplicity, we just call to
// OLE to do it for us.
PICTDESC pictdesc = PICTDESC.CreateIconPICTDESC(Handle);
Guid g = typeof(IPicture).GUID;
IPicture picture = OleCreatePictureIndirect(pictdesc, ref g, false);
if (picture != null)
{
try
{
// We threw this way on NetFX
if (outputStream == null)
throw new ArgumentNullException("dataStream");
picture.SaveAsFile(new GPStream(outputStream, makeSeekable: false), -1, out int temp);
}
finally
{
Marshal.ReleaseComObject(picture);
}
}
}
}
private void CopyBitmapData(BitmapData sourceData, BitmapData targetData)
{
int offsetSrc = 0;
int offsetDest = 0;
Debug.Assert(sourceData.Height == targetData.Height, "Unexpected height. How did this happen?");
for (int i = 0; i < Math.Min(sourceData.Height, targetData.Height); i++)
{
IntPtr srcPtr, destPtr;
if (IntPtr.Size == 4)
{
srcPtr = new IntPtr(sourceData.Scan0.ToInt32() + offsetSrc);
destPtr = new IntPtr(targetData.Scan0.ToInt32() + offsetDest);
}
else
{
srcPtr = new IntPtr(sourceData.Scan0.ToInt64() + offsetSrc);
destPtr = new IntPtr(targetData.Scan0.ToInt64() + offsetDest);
}
UnsafeNativeMethods.CopyMemory(new HandleRef(this, destPtr), new HandleRef(this, srcPtr), Math.Abs(targetData.Stride));
offsetSrc += sourceData.Stride;
offsetDest += targetData.Stride;
}
}
private static bool BitmapHasAlpha(BitmapData bmpData)
{
bool hasAlpha = false;
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 3; j < Math.Abs(bmpData.Stride); j += 4)
{
// Stride here is fine since we know we're doing this on the whole image.
unsafe
{
byte* candidate = unchecked(((byte*)bmpData.Scan0.ToPointer()) + (i * bmpData.Stride) + j);
if (*candidate != 0)
{
hasAlpha = true;
return hasAlpha;
}
}
}
}
return false;
}
public Bitmap ToBitmap()
{
// DontSupportPngFramesInIcons is true when the application is targeting framework version below 4.6
// and false when the application is targeting 4.6 and above. Downlevel application can also set the following switch
// to false in the .config file's runtime section in order to opt-in into the new behavior:
// <AppContextSwitchOverrides value="Switch.System.Drawing.DontSupportPngFramesInIcons=false" />
if (HasPngSignature() && !LocalAppContextSwitches.DontSupportPngFramesInIcons)
{
return PngFrame();
}
return BmpFrame();
}
private Bitmap BmpFrame()
{
Bitmap bitmap = null;
if (_iconData != null && _bestBitDepth == 32)
{
// GDI+ doesnt handle 32 bpp icons with alpha properly
// we load the icon ourself from the byte table
bitmap = new Bitmap(Size.Width, Size.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Debug.Assert(_bestImageOffset >= 0 && (_bestImageOffset + _bestBytesInRes) <= _iconData.Length, "Illegal offset/length for the Icon data");
unsafe
{
BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, Size.Width, Size.Height),
ImageLockMode.WriteOnly,
PixelFormat.Format32bppArgb);
try
{
uint* pixelPtr = (uint*)bmpdata.Scan0.ToPointer();
// jumping the image header
int newOffset = _bestImageOffset + Marshal.SizeOf(typeof(SafeNativeMethods.BITMAPINFOHEADER));
// there is no color table that we need to skip since we're 32bpp
int lineLength = Size.Width * 4;
int width = Size.Width;
for (int j = (Size.Height - 1) * 4; j >= 0; j -= 4)
{
Marshal.Copy(_iconData, newOffset + j * width, (IntPtr)pixelPtr, lineLength);
pixelPtr += width;
}
// note: we ignore the mask that's available after the pixel table
}
finally
{
bitmap.UnlockBits(bmpdata);
}
}
}
else if (_bestBitDepth == 0 || _bestBitDepth == 32)
{
// This may be a 32bpp icon or an icon without any data.
var info = new SafeNativeMethods.ICONINFO();
SafeNativeMethods.GetIconInfo(new HandleRef(this, _handle), info);
var bmp = new SafeNativeMethods.BITMAP();
try
{
if (info.hbmColor != IntPtr.Zero)
{
SafeNativeMethods.GetObject(new HandleRef(null, info.hbmColor), Marshal.SizeOf(typeof(SafeNativeMethods.BITMAP)), bmp);
if (bmp.bmBitsPixel == 32)
{
Bitmap tmpBitmap = null;
BitmapData bmpData = null;
BitmapData targetData = null;
try
{
tmpBitmap = Image.FromHbitmap(info.hbmColor);
// In GDI+ the bits are there but the bitmap was created with no alpha channel
// so copy the bits by hand to a new bitmap
// we also need to go around a limitation in the way the ICON is stored (ie if it's another bpp
// but stored in 32bpp all pixels are transparent and not opaque)
// (Here you mostly need to remain calm....)
bmpData = tmpBitmap.LockBits(new Rectangle(0, 0, tmpBitmap.Width, tmpBitmap.Height), ImageLockMode.ReadOnly, tmpBitmap.PixelFormat);
// we need do the following if the image has alpha because otherwise the image is fully transparent even though it has data
if (BitmapHasAlpha(bmpData))
{
bitmap = new Bitmap(bmpData.Width, bmpData.Height, PixelFormat.Format32bppArgb);
targetData = bitmap.LockBits(new Rectangle(0, 0, bmpData.Width, bmpData.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
CopyBitmapData(bmpData, targetData);
}
}
finally
{
if (tmpBitmap != null && bmpData != null)
{
tmpBitmap.UnlockBits(bmpData);
}
if (bitmap != null && targetData != null)
{
bitmap.UnlockBits(targetData);
}
}
tmpBitmap.Dispose();
}
}
}
finally
{
if (info.hbmColor != IntPtr.Zero)
{
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmColor));
}
if (info.hbmMask != IntPtr.Zero)
{
SafeNativeMethods.IntDeleteObject(new HandleRef(null, info.hbmMask));
}
}
}
if (bitmap == null)
{
// last chance... all the other cases (ie non 32 bpp icons coming from a handle or from the bitmapData)
// we have to do this rather than just return Bitmap.FromHIcon because
// the bitmap returned from that, even though it's 32bpp, just paints where the mask allows it
// seems like another GDI+ weirdness. might be interesting to investigate further. In the meantime
// this looks like the right thing to do and is not more expansive that what was present before.
Size size = Size;
bitmap = new Bitmap(size.Width, size.Height); // initialized to transparent
Graphics graphics = null;
using (graphics = Graphics.FromImage(bitmap))
{
try
{
using (Bitmap tmpBitmap = Bitmap.FromHicon(Handle))
{
graphics.DrawImage(tmpBitmap, new Rectangle(0, 0, size.Width, size.Height));
}
}
catch (ArgumentException)
{
// Sometimes FromHicon will crash with no real reason.
// The backup plan is to just draw the image like we used to.
// NOTE: FromHIcon is also where we have the buffer overrun
// if width and height are mismatched.
Draw(graphics, new Rectangle(0, 0, size.Width, size.Height));
}
}
// GDI+ fills the surface with a sentinel color for GetDC, but does
// not correctly clean it up again, so we have to do it.
Color fakeTransparencyColor = Color.FromArgb(0x0d, 0x0b, 0x0c);
bitmap.MakeTransparent(fakeTransparencyColor);
}
Debug.Assert(bitmap != null, "Bitmap cannot be null");
return bitmap;
}
private Bitmap PngFrame()
{
Debug.Assert(_iconData != null);
using (var stream = new MemoryStream())
{
stream.Write(_iconData, _bestImageOffset, _bestBytesInRes);
return new Bitmap(stream);
}
}
private bool HasPngSignature()
{
if (!_isBestImagePng.HasValue)
{
if (_iconData != null && _iconData.Length >= _bestImageOffset + 8)
{
int iconSignature1 = BitConverter.ToInt32(_iconData, _bestImageOffset);
int iconSignature2 = BitConverter.ToInt32(_iconData, _bestImageOffset + 4);
_isBestImagePng = (iconSignature1 == PNGSignature1) && (iconSignature2 == PNGSignature2);
}
else
{
_isBestImagePng = false;
}
}
return _isBestImagePng.Value;
}
public override string ToString() => SR.toStringIcon;
[DllImport(ExternDll.Oleaut32, PreserveSig = false)]
internal static extern IPicture OleCreatePictureIndirect(PICTDESC pictdesc, [In]ref Guid refiid, bool fOwn);
[ComImport()]
[Guid("7BF80980-BF32-101A-8BBB-00AA00300CAB")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IPicture
{
IntPtr GetHandle();
IntPtr GetHPal();
[return: MarshalAs(UnmanagedType.I2)]
short GetPictureType();
int GetWidth();
int GetHeight();
void Render();
void SetHPal([In] IntPtr phpal);
IntPtr GetCurDC();
void SelectPicture([In] IntPtr hdcIn,
[Out, MarshalAs(UnmanagedType.LPArray)] int[] phdcOut,
[Out, MarshalAs(UnmanagedType.LPArray)] int[] phbmpOut);
[return: MarshalAs(UnmanagedType.Bool)]
bool GetKeepOriginalFormat();
void SetKeepOriginalFormat([In, MarshalAs(UnmanagedType.Bool)] bool pfkeep);
void PictureChanged();
[PreserveSig]
int SaveAsFile([In, MarshalAs(UnmanagedType.Interface)] Interop.Ole32.IStream pstm,
[In] int fSaveMemCopy,
[Out] out int pcbSize);
int GetAttributes();
void SetHdc([In] IntPtr hdc);
}
internal class Ole
{
public const int PICTYPE_ICON = 3;
}
[StructLayout(LayoutKind.Sequential)]
internal class PICTDESC
{
internal int cbSizeOfStruct;
public int picType;
internal IntPtr union1;
internal int union2;
internal int union3;
public static PICTDESC CreateIconPICTDESC(IntPtr hicon)
{
return new PICTDESC()
{
cbSizeOfStruct = 12,
picType = Ole.PICTYPE_ICON,
union1 = hicon
};
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
*
* Class: IsolatedStorageFileStream
//
// <OWNER>[....]</OWNER>
*
*
* Purpose: Provides access to files using the same interface as FileStream
*
* Date: Feb 18, 2000
*
===========================================================*/
namespace System.IO.IsolatedStorage {
using System;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public class IsolatedStorageFileStream : FileStream
{
private const int s_BlockSize = 1024; // Should be a power of 2!
// see usage before
// changing this constant
#if !FEATURE_PAL
private const String s_BackSlash = "\\";
#else
// s_BackSlash is initialized in the contructor with Path.DirectorySeparatorChar
private readonly String s_BackSlash;
#endif // !FEATURE_PAL
private FileStream m_fs;
private IsolatedStorageFile m_isf;
private String m_GivenPath;
private String m_FullPath;
private bool m_OwnedStore;
private IsolatedStorageFileStream() {}
#if !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.AppDomain | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.AppDomain | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode)
: this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, null) {
}
#endif // !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
IsolatedStorageFile isf)
: this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, isf)
{
}
#if !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.AppDomain | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.AppDomain | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access)
: this(path, mode, access, access == FileAccess.Read?
FileShare.Read: FileShare.None, DefaultBufferSize, null) {
}
#endif // !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, IsolatedStorageFile isf)
: this(path, mode, access, access == FileAccess.Read?
FileShare.Read: FileShare.None, DefaultBufferSize, isf) {
}
#if !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.AppDomain | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.AppDomain | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share)
: this(path, mode, access, share, DefaultBufferSize, null) {
}
#endif // !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share, IsolatedStorageFile isf)
: this(path, mode, access, share, DefaultBufferSize, isf) {
}
#if !FEATURE_ISOSTORE_LIGHT
[ResourceExposure(ResourceScope.AppDomain | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.AppDomain | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share, int bufferSize)
: this(path, mode, access, share, bufferSize, null) {
}
#endif // !FEATURE_ISOSTORE_LIGHT
// If the isolated storage file is null, then we default to using a file
// that is scoped by user, appdomain, and assembly.
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine | ResourceScope.Assembly)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly)]
public IsolatedStorageFileStream(String path, FileMode mode,
FileAccess access, FileShare share, int bufferSize,
IsolatedStorageFile isf)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_PAL
if (s_BackSlash == null)
s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar,1);
#endif // FEATURE_PAL
if ((path.Length == 0) || path.Equals(s_BackSlash))
throw new ArgumentException(
Environment.GetResourceString(
"IsolatedStorage_Path"));
if (isf == null)
{
#if FEATURE_ISOSTORE_LIGHT
throw new ArgumentNullException("isf");
#else // !FEATURE_ISOSTORE_LIGHT
m_OwnedStore = true;
isf = IsolatedStorageFile.GetUserStoreForDomain();
#endif // !FEATURE_ISOSTORE_LIGHT
}
if (isf.Disposed)
throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen"));
switch (mode) {
case FileMode.CreateNew: // Assume new file
case FileMode.Create: // Check for New file & Unreserve
case FileMode.OpenOrCreate: // Check for new file
case FileMode.Truncate: // Unreserve old file size
case FileMode.Append: // Check for new file
case FileMode.Open: // Open existing, else exception
break;
default:
throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode"));
}
m_isf = isf;
#if !FEATURE_CORECLR
FileIOPermission fiop =
new FileIOPermission(FileIOPermissionAccess.AllAccess,
m_isf.RootDirectory);
fiop.Assert();
fiop.PermitOnly();
#endif
m_GivenPath = path;
m_FullPath = m_isf.GetFullPath(m_GivenPath);
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
ulong oldFileSize=0, newFileSize;
bool fNewFile = false, fLock=false;
RuntimeHelpers.PrepareConstrainedRegions();
try { // for finally Unlocking locked store
// Cache the old file size if the file size could change
// Also find if we are going to create a new file.
switch (mode) {
case FileMode.CreateNew: // Assume new file
#if FEATURE_ISOSTORE_LIGHT
// We are going to call Reserve so we need to lock the store.
m_isf.Lock(ref fLock);
#endif
fNewFile = true;
break;
case FileMode.Create: // Check for New file & Unreserve
case FileMode.OpenOrCreate: // Check for new file
case FileMode.Truncate: // Unreserve old file size
case FileMode.Append: // Check for new file
m_isf.Lock(ref fLock); // oldFileSize needs to be
// protected
try {
#if FEATURE_ISOSTORE_LIGHT
oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)(FileInfo.UnsafeCreateFileInfo(m_FullPath).Length));
#else
oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(m_FullPath));
#endif
} catch (FileNotFoundException) {
fNewFile = true;
} catch {
}
break;
case FileMode.Open: // Open existing, else exception
break;
}
if (fNewFile)
m_isf.ReserveOneBlock();
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
try {
#if FEATURE_CORECLR
// Since FileStream's .ctor won't do a demand, we need to do our access check here.
m_isf.Demand(m_FullPath);
#endif
#if FEATURE_ISOSTORE_LIGHT
m_fs = new
FileStream(m_FullPath, mode, access, share, bufferSize,
FileOptions.None, m_GivenPath, true);
} catch (Exception e) {
#else
m_fs = new
FileStream(m_FullPath, mode, access, share, bufferSize,
FileOptions.None, m_GivenPath, true, true);
} catch {
#endif
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
if (fNewFile)
m_isf.UnreserveOneBlock();
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
#if FEATURE_ISOSTORE_LIGHT
// IsoStore generally does not let arbitrary exceptions flow out: a
// IsolatedStorageException is thrown instead (see examples in IsolatedStorageFile.cs
// Keeping this scoped to coreclr just because changing the exception type thrown is a
// breaking change and that should not be introduced into the desktop without deliberation.
//
// Note that GetIsolatedStorageException may set InnerException. To the real exception
// Today it always does this, for debug and chk builds, and for other builds asks the host
// if it is okay to do so.
throw IsolatedStorageFile.GetIsolatedStorageException("IsolatedStorage_Operation_ISFS", e);
#else
throw;
#endif // FEATURE_ISOSTORE_LIGHT
}
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
// make adjustment to the Reserve / Unreserve state
if ((fNewFile == false) &&
((mode == FileMode.Truncate) || (mode == FileMode.Create)))
{
newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length);
if (oldFileSize > newFileSize)
m_isf.Unreserve(oldFileSize - newFileSize);
else if (newFileSize > oldFileSize) // Can this happen ?
m_isf.Reserve(newFileSize - oldFileSize);
}
} finally {
if (fLock)
m_isf.Unlock();
}
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
#if !FEATURE_CORECLR
CodeAccessPermission.RevertAll();
#endif
}
public override bool CanRead {
[Pure]
get {
return m_fs.CanRead;
}
}
public override bool CanWrite {
[Pure]
get {
return m_fs.CanWrite;
}
}
public override bool CanSeek {
[Pure]
get {
return m_fs.CanSeek;
}
}
public override bool IsAsync {
get {
return m_fs.IsAsync;
}
}
public override long Length {
get {
return m_fs.Length;
}
}
public override long Position {
get {
return m_fs.Position;
}
set {
if (value < 0)
{
throw new ArgumentOutOfRangeException("value",
Environment.GetResourceString(
"ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
Seek(value, SeekOrigin.Begin);
}
}
#if FEATURE_LEGACYNETCF
public new string Name {
[SecurityCritical]
get {
return m_FullPath;
}
}
#endif
#if false
unsafe private static void AsyncFSCallback(uint errorCode,
uint numBytes, NativeOverlapped* pOverlapped) {
NotPermittedError();
}
#endif
protected override void Dispose(bool disposing)
{
try {
if (disposing) {
try {
if (m_fs != null)
m_fs.Close();
}
finally {
if (m_OwnedStore && m_isf != null)
m_isf.Close();
}
}
}
finally {
base.Dispose(disposing);
}
}
public override void Flush() {
m_fs.Flush();
}
public override void Flush(Boolean flushToDisk) {
m_fs.Flush(flushToDisk);
}
[Obsolete("This property has been deprecated. Please use IsolatedStorageFileStream's SafeFileHandle property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public override IntPtr Handle {
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#endif
get {
NotPermittedError();
return Win32Native.INVALID_HANDLE_VALUE;
}
}
public override SafeFileHandle SafeFileHandle {
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#endif
get {
NotPermittedError();
return null;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
bool locked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_isf.Lock(ref locked); // oldLen needs to be protected
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
ulong oldLen = (ulong)m_fs.Length;
ulong newLen = (ulong)value;
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
// Reserve before the operation.
m_isf.Reserve(oldLen, newLen);
try {
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
ZeroInit(oldLen, newLen);
m_fs.SetLength(value);
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
} catch {
// Undo the reserve
m_isf.UndoReserveOperation(oldLen, newLen);
throw;
}
// Unreserve if this operation reduced the file size.
if (oldLen > newLen)
{
// params oldlen, newlength reversed on purpose.
m_isf.UndoReserveOperation(newLen, oldLen);
}
} finally {
if (locked)
m_isf.Unlock();
}
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
}
public override void Lock(long position, long length)
{
if (position < 0 || length < 0)
throw new ArgumentOutOfRangeException((position < 0 ? "position" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_fs.Lock(position, length);
}
public override void Unlock(long position, long length)
{
if (position < 0 || length < 0)
throw new ArgumentOutOfRangeException((position < 0 ? "position" : "length"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
m_fs.Unlock(position, length);
}
// 0 out the allocated disk so that
// untrusted apps won't be able to read garbage, which
// is a security hole, if allowed.
// This may not be necessary in some file systems ?
private void ZeroInit(ulong oldLen, ulong newLen)
{
if (oldLen >= newLen)
return;
ulong rem = newLen - oldLen;
byte[] buffer = new byte[s_BlockSize]; // buffer is zero inited
// here by the runtime
// memory allocator.
// back up the current position.
long pos = m_fs.Position;
m_fs.Seek((long)oldLen, SeekOrigin.Begin);
// If we have a small number of bytes to write, do that and
// we are done.
if (rem <= (ulong)s_BlockSize)
{
m_fs.Write(buffer, 0, (int)rem);
m_fs.Position = pos;
return;
}
// Block write is better than writing a byte in a loop
// or all bytes. The number of bytes to write could
// be very large.
// Align to block size
// allign = s_BlockSize - (int)(oldLen % s_BlockSize);
// Converting % to & operation since s_BlockSize is a power of 2
int allign = s_BlockSize - (int)(oldLen & ((ulong)s_BlockSize - 1));
/*
this will never happen since we already handled this case
leaving this code here for documentation
if ((ulong)allign > rem)
allign = (int)rem;
*/
m_fs.Write(buffer, 0, allign);
rem -= (ulong)allign;
int nBlocks = (int)(rem / s_BlockSize);
// Write out one block at a time.
for (int i=0; i<nBlocks; ++i)
m_fs.Write(buffer, 0, s_BlockSize);
// Write out the remaining bytes.
// m_fs.Write(buffer, 0, (int) (rem % s_BlockSize));
// Converting % to & operation since s_BlockSize is a power of 2
m_fs.Write(buffer, 0, (int) (rem & ((ulong)s_BlockSize - 1)));
// restore the current position
m_fs.Position = pos;
}
public override int Read(byte[] buffer, int offset, int count) {
return m_fs.Read(buffer, offset, count);
}
public override int ReadByte() {
return m_fs.ReadByte();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override long Seek(long offset, SeekOrigin origin)
{
long ret;
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
bool locked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_isf.Lock(ref locked); // oldLen needs to be protected
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
// Seek operation could increase the file size, make sure
// that the quota is updated, and file is zeroed out
ulong oldLen;
ulong newLen;
oldLen = (ulong) m_fs.Length;
// Note that offset can be negative too.
switch (origin) {
case SeekOrigin.Begin:
newLen = (ulong)((offset < 0)?0:offset);
break;
case SeekOrigin.Current:
newLen = (ulong) ((m_fs.Position + offset) < 0 ? 0 : (m_fs.Position + offset));
break;
case SeekOrigin.End:
newLen = (ulong)((m_fs.Length + offset) < 0 ? 0 : (m_fs.Length + offset));
break;
default:
throw new ArgumentException(
Environment.GetResourceString(
"IsolatedStorage_SeekOrigin"));
}
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
m_isf.Reserve(oldLen, newLen);
try {
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
ZeroInit(oldLen, newLen);
ret = m_fs.Seek(offset, origin);
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
} catch {
m_isf.UndoReserveOperation(oldLen, newLen);
throw;
}
}
finally
{
if (locked)
m_isf.Unlock();
}
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
return ret;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count)
{
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
bool locked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_isf.Lock(ref locked); // oldLen needs to be protected
ulong oldLen = (ulong)m_fs.Length;
ulong newLen = (ulong)(m_fs.Position + count);
m_isf.Reserve(oldLen, newLen);
try {
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
m_fs.Write(buffer, offset, count);
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
} catch {
m_isf.UndoReserveOperation(oldLen, newLen);
throw;
}
}
finally
{
if (locked)
m_isf.Unlock();
}
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void WriteByte(byte value)
{
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
bool locked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_isf.Lock(ref locked); // oldLen needs to be protected
ulong oldLen = (ulong)m_fs.Length;
ulong newLen = (ulong)m_fs.Position + 1;
m_isf.Reserve(oldLen, newLen);
try {
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
m_fs.WriteByte(value);
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
} catch {
m_isf.UndoReserveOperation(oldLen, newLen);
throw;
}
}
finally {
if (locked)
m_isf.Unlock();
}
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
}
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginRead(byte[] buffer, int offset,
int numBytes, AsyncCallback userCallback, Object stateObject) {
return m_fs.BeginRead(buffer, offset, numBytes, userCallback, stateObject);
}
public override int EndRead(IAsyncResult asyncResult) {
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
// try-catch to avoid leaking path info
return m_fs.EndRead(asyncResult);
}
[System.Security.SecuritySafeCritical] // auto-generated
[HostProtection(ExternalThreading=true)]
public override IAsyncResult BeginWrite(byte[] buffer, int offset,
int numBytes, AsyncCallback userCallback, Object stateObject) {
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
bool locked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
m_isf.Lock(ref locked); // oldLen needs to be protected
ulong oldLen = (ulong)m_fs.Length;
ulong newLen = (ulong)m_fs.Position + (ulong)numBytes;
m_isf.Reserve(oldLen, newLen);
try {
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
return m_fs.BeginWrite(buffer, offset, numBytes, userCallback, stateObject);
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
} catch {
m_isf.UndoReserveOperation(oldLen, newLen);
throw;
}
}
finally
{
if(locked)
m_isf.Unlock();
}
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
}
public override void EndWrite(IAsyncResult asyncResult) {
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
Contract.EndContractBlock();
m_fs.EndWrite(asyncResult);
}
internal void NotPermittedError(String str) {
throw new IsolatedStorageException(str);
}
internal void NotPermittedError() {
NotPermittedError(Environment.GetResourceString(
"IsolatedStorage_Operation_ISFS"));
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using RedditSharp.Things;
using System.Threading.Tasks;
namespace RedditSharp
{
/// <summary>
/// Class to communicate with Reddit.com
/// </summary>
public class Reddit
{
#region Constant Urls
private const string SslLoginUrl = "https://ssl.reddit.com/api/login";
private const string LoginUrl = "/api/login/username";
private const string UserInfoUrl = "/user/{0}/about.json";
private const string MeUrl = "/api/me.json";
private const string OAuthMeUrl = "/api/v1/me.json";
private const string SubredditAboutUrl = "/r/{0}/about.json";
private const string ComposeMessageUrl = "/api/compose";
private const string RegisterAccountUrl = "/api/register";
private const string GetThingUrl = "/api/info.json?id={0}";
private const string GetCommentUrl = "/r/{0}/comments/{1}/foo/{2}";
private const string GetPostUrl = "{0}.json";
private const string DomainUrl = "www.reddit.com";
private const string OAuthDomainUrl = "oauth.reddit.com";
private const string SearchUrl = "/search.json?q={0}&restrict_sr=off&sort={1}&t={2}";
private const string UrlSearchPattern = "url:'{0}'";
#endregion
#region Static Variables
static Reddit()
{
WebAgent.UserAgent = "";
WebAgent.RateLimit = WebAgent.RateLimitMode.Pace;
WebAgent.Protocol = "http";
WebAgent.RootDomain = "www.reddit.com";
}
#endregion
internal readonly IWebAgent _webAgent;
/// <summary>
/// Captcha solver instance to use when solving captchas.
/// </summary>
public ICaptchaSolver CaptchaSolver;
/// <summary>
/// The authenticated user for this instance.
/// </summary>
public AuthenticatedUser User { get; set; }
/// <summary>
/// Sets the Rate Limiting Mode of the underlying WebAgent
/// </summary>
public WebAgent.RateLimitMode RateLimit
{
get { return WebAgent.RateLimit; }
set { WebAgent.RateLimit = value; }
}
internal JsonSerializerSettings JsonSerializerSettings { get; set; }
/// <summary>
/// Gets the FrontPage using the current Reddit instance.
/// </summary>
public Subreddit FrontPage
{
get { return Subreddit.GetFrontPage(this); }
}
/// <summary>
/// Gets /r/All using the current Reddit instance.
/// </summary>
public Subreddit RSlashAll
{
get { return Subreddit.GetRSlashAll(this); }
}
public Reddit()
{
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
_webAgent = new WebAgent();
CaptchaSolver = new ConsoleCaptchaSolver();
}
public Reddit(WebAgent.RateLimitMode limitMode) : this()
{
WebAgent.UserAgent = "";
WebAgent.RateLimit = limitMode;
WebAgent.RootDomain = "www.reddit.com";
}
public Reddit(string username, string password, bool useSsl = true) : this()
{
LogIn(username, password, useSsl);
}
public Reddit(string accessToken) : this()
{
WebAgent.Protocol = "https";
WebAgent.RootDomain = OAuthDomainUrl;
_webAgent.AccessToken = accessToken;
InitOrUpdateUser();
}
/// <summary>
/// Logs in the current Reddit instance.
/// </summary>
/// <param name="username">The username of the user to log on to.</param>
/// <param name="password">The password of the user to log on to.</param>
/// <param name="useSsl">Whether to use SSL or not. (default: true)</param>
/// <returns></returns>
public AuthenticatedUser LogIn(string username, string password, bool useSsl = true)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
_webAgent.Cookies = new CookieContainer();
HttpWebRequest request;
if (useSsl)
request = _webAgent.CreatePost(SslLoginUrl);
else
request = _webAgent.CreatePost(LoginUrl);
var stream = request.GetRequestStream();
if (useSsl)
{
_webAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json"
});
}
else
{
_webAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json",
op = "login"
});
}
stream.Close();
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result)["json"];
if (json["errors"].Count() != 0)
throw new AuthenticationException("Incorrect login.");
InitOrUpdateUser();
return User;
}
public RedditUser GetUser(string name)
{
var request = _webAgent.CreateGet(string.Format(UserInfoUrl, name));
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new RedditUser().Init(this, json, _webAgent);
}
/// <summary>
/// Initializes the User property if it's null,
/// otherwise replaces the existing user object
/// with a new one fetched from reddit servers.
/// </summary>
public void InitOrUpdateUser()
{
var request = _webAgent.CreateGet(string.IsNullOrEmpty(_webAgent.AccessToken) ? MeUrl : OAuthMeUrl);
var response = (HttpWebResponse)request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
User = new AuthenticatedUser().Init(this, json, _webAgent);
}
#region Obsolete Getter Methods
[Obsolete("Use User property instead")]
public AuthenticatedUser GetMe()
{
return User;
}
#endregion Obsolete Getter Methods
public Subreddit GetSubreddit(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
return GetThing<Subreddit>(string.Format(SubredditAboutUrl, name));
}
/// <summary>
/// Returns the subreddit.
/// </summary>
/// <param name="name">The name of the subreddit</param>
/// <returns>The Subreddit by given name</returns>
public async Task<Subreddit> GetSubredditAsync(string name)
{
if (name.StartsWith("r/"))
name = name.Substring(2);
if (name.StartsWith("/r/"))
name = name.Substring(3);
return await GetThingAsync<Subreddit>(string.Format(SubredditAboutUrl, name));
}
public Domain GetDomain(string domain)
{
if (!domain.StartsWith("http://") && !domain.StartsWith("https://"))
domain = "http://" + domain;
var uri = new Uri(domain);
return new Domain(this, uri, _webAgent);
}
public JToken GetToken(Uri uri)
{
var url = uri.AbsoluteUri;
if (url.EndsWith("/"))
url = url.Remove(url.Length - 1);
var request = _webAgent.CreateGet(string.Format(GetPostUrl, url));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return json[0]["data"]["children"].First;
}
public Post GetPost(Uri uri)
{
return new Post().Init(this, GetToken(uri), _webAgent);
}
public void ComposePrivateMessage(string subject, string body, string to, string captchaId = "", string captchaAnswer = "")
{
if (User == null)
throw new Exception("User can not be null.");
var request = _webAgent.CreatePost(ComposeMessageUrl);
_webAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
subject,
text = body,
to,
uh = User.Modhash,
iden = captchaId,
captcha = captchaAnswer
});
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
ICaptchaSolver solver = CaptchaSolver; // Prevent race condition
if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
{
captchaId = json["json"]["captcha"].ToString();
CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));
if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
ComposePrivateMessage(subject, body, to, captchaId, captchaResponse.Answer);
}
}
/// <summary>
/// Registers a new Reddit user
/// </summary>
/// <param name="userName">The username for the new account.</param>
/// <param name="passwd">The password for the new account.</param>
/// <param name="email">The optional recovery email for the new account.</param>
/// <returns>The newly created user account</returns>
public AuthenticatedUser RegisterAccount(string userName, string passwd, string email = "")
{
var request = _webAgent.CreatePost(RegisterAccountUrl);
_webAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
email = email,
passwd = passwd,
passwd2 = passwd,
user = userName
});
var response = request.GetResponse();
var result = _webAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new AuthenticatedUser().Init(this, json, _webAgent);
// TODO: Error
}
public Thing GetThingByFullname(string fullname)
{
var request = _webAgent.CreateGet(string.Format(GetThingUrl, fullname));
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return Thing.Parse(this, json["data"]["children"][0], _webAgent);
}
public Comment GetComment(string subreddit, string name, string linkName)
{
try
{
if (linkName.StartsWith("t3_"))
linkName = linkName.Substring(3);
if (name.StartsWith("t1_"))
name = name.Substring(3);
var url = string.Format(GetCommentUrl, subreddit, linkName, name);
return GetComment(new Uri(url));
}
catch (WebException)
{
return null;
}
}
public Comment GetComment(Uri uri)
{
var url = string.Format(GetPostUrl, uri.AbsoluteUri);
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var sender = new Post().Init(this, json[0]["data"]["children"][0], _webAgent);
return new Comment().Init(this, json[1]["data"]["children"][0], _webAgent, sender);
}
public Listing<T> SearchByUrl<T>(string url) where T : Thing
{
var urlSearchQuery = string.Format(UrlSearchPattern, url);
return Search<T>(urlSearchQuery);
}
public Listing<T> Search<T>(string query) where T : Thing
{
return new Listing<T>(this, string.Format(SearchUrl, query, "relevance", "all"), _webAgent);
}
#region Helpers
protected async internal Task<T> GetThingAsync<T>(string url) where T : Thing
{
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var ret = await Thing.ParseAsync(this, json, _webAgent);
return (T)ret;
}
protected internal T GetThing<T>(string url) where T : Thing
{
var request = _webAgent.CreateGet(url);
var response = request.GetResponse();
var data = _webAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return (T)Thing.Parse(this, json, _webAgent);
}
#endregion
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Controls;
using Avalonia.UnitTests;
using System;
using Xunit;
using System.Collections.Generic;
namespace Avalonia.Layout.UnitTests
{
public class LayoutManagerTests
{
[Fact]
public void Measures_And_Arranges_InvalidateMeasured_Control()
{
var target = new LayoutManager();
using (Start(target))
{
var control = new LayoutTestControl();
var root = new LayoutTestRoot { Child = control };
target.ExecuteInitialLayoutPass(root);
control.Measured = control.Arranged = false;
control.InvalidateMeasure();
target.ExecuteLayoutPass();
Assert.True(control.Measured);
Assert.True(control.Arranged);
}
}
[Fact]
public void Arranges_InvalidateArranged_Control()
{
var target = new LayoutManager();
using (Start(target))
{
var control = new LayoutTestControl();
var root = new LayoutTestRoot { Child = control };
target.ExecuteInitialLayoutPass(root);
control.Measured = control.Arranged = false;
control.InvalidateArrange();
target.ExecuteLayoutPass();
Assert.False(control.Measured);
Assert.True(control.Arranged);
}
}
[Fact]
public void Measures_Parent_Of_Newly_Added_Control()
{
var target = new LayoutManager();
using (Start(target))
{
var control = new LayoutTestControl();
var root = new LayoutTestRoot();
target.ExecuteInitialLayoutPass(root);
root.Child = control;
root.Measured = root.Arranged = false;
target.ExecuteLayoutPass();
Assert.True(root.Measured);
Assert.True(root.Arranged);
Assert.True(control.Measured);
Assert.True(control.Arranged);
}
}
[Fact]
public void Measures_In_Correct_Order()
{
var target = new LayoutManager();
using (Start(target))
{
LayoutTestControl control1;
LayoutTestControl control2;
var root = new LayoutTestRoot
{
Child = control1 = new LayoutTestControl
{
Child = control2 = new LayoutTestControl(),
}
};
var order = new List<ILayoutable>();
Size MeasureOverride(ILayoutable control, Size size)
{
order.Add(control);
return new Size(10, 10);
}
root.DoMeasureOverride = MeasureOverride;
control1.DoMeasureOverride = MeasureOverride;
control2.DoMeasureOverride = MeasureOverride;
target.ExecuteInitialLayoutPass(root);
control2.InvalidateMeasure();
control1.InvalidateMeasure();
root.InvalidateMeasure();
order.Clear();
target.ExecuteLayoutPass();
Assert.Equal(new ILayoutable[] { root, control1, control2 }, order);
}
}
[Fact]
public void Measures_Root_And_Grandparent_In_Correct_Order()
{
var target = new LayoutManager();
using (Start(target))
{
LayoutTestControl control1;
LayoutTestControl control2;
var root = new LayoutTestRoot
{
Child = control1 = new LayoutTestControl
{
Child = control2 = new LayoutTestControl(),
}
};
var order = new List<ILayoutable>();
Size MeasureOverride(ILayoutable control, Size size)
{
order.Add(control);
return new Size(10, 10);
}
root.DoMeasureOverride = MeasureOverride;
control1.DoMeasureOverride = MeasureOverride;
control2.DoMeasureOverride = MeasureOverride;
target.ExecuteInitialLayoutPass(root);
control2.InvalidateMeasure();
root.InvalidateMeasure();
order.Clear();
target.ExecuteLayoutPass();
Assert.Equal(new ILayoutable[] { root, control2 }, order);
}
}
[Fact]
public void Doesnt_Measure_Non_Invalidated_Root()
{
var target = new LayoutManager();
using (Start(target))
{
var control = new LayoutTestControl();
var root = new LayoutTestRoot { Child = control };
target.ExecuteInitialLayoutPass(root);
root.Measured = root.Arranged = false;
control.Measured = control.Arranged = false;
control.InvalidateMeasure();
target.ExecuteLayoutPass();
Assert.False(root.Measured);
Assert.False(root.Arranged);
Assert.True(control.Measured);
Assert.True(control.Arranged);
}
}
[Fact]
public void Doesnt_Measure_Removed_Control()
{
var target = new LayoutManager();
using (Start(target))
{
var control = new LayoutTestControl();
var root = new LayoutTestRoot { Child = control };
target.ExecuteInitialLayoutPass(root);
control.Measured = control.Arranged = false;
control.InvalidateMeasure();
root.Child = null;
target.ExecuteLayoutPass();
Assert.False(control.Measured);
Assert.False(control.Arranged);
}
}
[Fact]
public void Measures_Root_With_Infinity()
{
var target = new LayoutManager();
using (Start(target))
{
var root = new LayoutTestRoot();
var availableSize = default(Size);
// Should not measure with this size.
root.MaxClientSize = new Size(123, 456);
root.DoMeasureOverride = (_, s) =>
{
availableSize = s;
return new Size(100, 100);
};
target.ExecuteInitialLayoutPass(root);
Assert.Equal(Size.Infinity, availableSize);
}
}
[Fact]
public void Arranges_Root_With_DesiredSize()
{
var target = new LayoutManager();
using (Start(target))
{
var root = new LayoutTestRoot
{
Width = 100,
Height = 100,
};
var arrangeSize = default(Size);
root.DoArrangeOverride = (_, s) =>
{
arrangeSize = s;
return s;
};
target.ExecuteInitialLayoutPass(root);
Assert.Equal(new Size(100, 100), arrangeSize);
root.Width = 120;
target.ExecuteLayoutPass();
Assert.Equal(new Size(120, 100), arrangeSize);
}
}
[Fact]
public void Invalidating_Child_Remeasures_Parent()
{
var target = new LayoutManager();
using (Start(target))
{
AvaloniaLocator.CurrentMutable.Bind<ILayoutManager>().ToConstant(target);
Border border;
StackPanel panel;
var root = new LayoutTestRoot
{
Child = panel = new StackPanel
{
Children = new Controls.Controls
{
(border = new Border())
}
}
};
target.ExecuteInitialLayoutPass(root);
Assert.Equal(new Size(0, 0), root.DesiredSize);
border.Width = 100;
border.Height = 100;
target.ExecuteLayoutPass();
Assert.Equal(new Size(100, 100), panel.DesiredSize);
}
}
private IDisposable Start(LayoutManager layoutManager)
{
var result = AvaloniaLocator.EnterScope();
AvaloniaLocator.CurrentMutable.Bind<ILayoutManager>().ToConstant(layoutManager);
return result;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// 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 Google Inc. 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.
#endregion
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Base for handling both client side and server side calls.
/// Manages native call lifecycle and provides convenience methods.
/// </summary>
internal abstract class AsyncCallBase<TWrite, TRead>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
readonly Func<TWrite, byte[]> serializer;
readonly Func<byte[], TRead> deserializer;
protected readonly object myLock = new object();
protected CallSafeHandle call;
protected bool disposed;
protected bool started;
protected bool errorOccured;
protected bool cancelRequested;
protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected AsyncCompletionDelegate<TRead> readCompletionDelegate; // Completion of a pending send or sendclose if not null.
protected bool readingDone;
protected bool halfcloseRequested;
protected bool halfclosed;
protected bool finished; // True if close has been received from the peer.
protected bool initialMetadataSent;
protected long streamingWritesCounter;
public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer)
{
this.serializer = Preconditions.CheckNotNull(serializer);
this.deserializer = Preconditions.CheckNotNull(deserializer);
}
/// <summary>
/// Requests cancelling the call.
/// </summary>
public void Cancel()
{
lock (myLock)
{
Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.Cancel();
}
}
}
/// <summary>
/// Requests cancelling the call with given status.
/// </summary>
public void CancelWithStatus(Status status)
{
lock (myLock)
{
Preconditions.CheckState(started);
cancelRequested = true;
if (!disposed)
{
call.CancelWithStatus(status);
}
}
}
protected void InitializeInternal(CallSafeHandle call)
{
lock (myLock)
{
this.call = call;
}
}
/// <summary>
/// Initiates sending a message. Only one send operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartSendMessageInternal(TWrite msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate)
{
byte[] payload = UnsafeSerialize(msg);
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent);
sendCompletionDelegate = completionDelegate;
initialMetadataSent = true;
streamingWritesCounter++;
}
}
/// <summary>
/// Initiates reading a message. Only one read operation can be active at a time.
/// completionDelegate is invoked upon completion.
/// </summary>
protected void StartReadMessageInternal(AsyncCompletionDelegate<TRead> completionDelegate)
{
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckReadingAllowed();
call.StartReceiveMessage(HandleReadFinished);
readCompletionDelegate = completionDelegate;
}
}
// TODO(jtattermusch): find more fitting name for this method.
/// <summary>
/// Default behavior just completes the read observer, but more sofisticated behavior might be required
/// by subclasses.
/// </summary>
protected virtual void ProcessLastRead(AsyncCompletionDelegate<TRead> completionDelegate)
{
FireCompletion(completionDelegate, default(TRead), null);
}
/// <summary>
/// If there are no more pending actions and no new actions can be started, releases
/// the underlying native resources.
/// </summary>
protected bool ReleaseResourcesIfPossible()
{
if (!disposed && call != null)
{
bool noMoreSendCompletions = halfclosed || (cancelRequested && sendCompletionDelegate == null);
if (noMoreSendCompletions && readingDone && finished)
{
ReleaseResources();
return true;
}
}
return false;
}
private void ReleaseResources()
{
if (call != null)
{
call.Dispose();
}
disposed = true;
OnAfterReleaseResources();
}
protected virtual void OnAfterReleaseResources()
{
}
protected void CheckSendingAllowed()
{
Preconditions.CheckState(started);
Preconditions.CheckState(!errorOccured);
CheckNotCancelled();
Preconditions.CheckState(!disposed);
Preconditions.CheckState(!halfcloseRequested, "Already halfclosed.");
Preconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time");
}
protected virtual void CheckReadingAllowed()
{
Preconditions.CheckState(started);
Preconditions.CheckState(!disposed);
Preconditions.CheckState(!errorOccured);
Preconditions.CheckState(!readingDone, "Stream has already been closed.");
Preconditions.CheckState(readCompletionDelegate == null, "Only one read can be pending at a time");
}
protected void CheckNotCancelled()
{
if (cancelRequested)
{
throw new OperationCanceledException("Remote call has been cancelled.");
}
}
protected byte[] UnsafeSerialize(TWrite msg)
{
return serializer(msg);
}
protected bool TrySerialize(TWrite msg, out byte[] payload)
{
try
{
payload = serializer(msg);
return true;
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while trying to serialize message");
payload = null;
return false;
}
}
protected bool TryDeserialize(byte[] payload, out TRead msg)
{
try
{
msg = deserializer(payload);
return true;
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while trying to deserialize message.");
msg = default(TRead);
return false;
}
}
protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error)
{
try
{
completionDelegate(value, error);
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
/// <summary>
/// Handles send completion.
/// </summary>
protected void HandleSendFinished(bool success, BatchContextSafeHandle ctx)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Send failed"));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles halfclose completion.
/// </summary>
protected void HandleHalfclosed(bool success, BatchContextSafeHandle ctx)
{
AsyncCompletionDelegate<object> origCompletionDelegate = null;
lock (myLock)
{
halfclosed = true;
origCompletionDelegate = sendCompletionDelegate;
sendCompletionDelegate = null;
ReleaseResourcesIfPossible();
}
if (!success)
{
FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Halfclose failed"));
}
else
{
FireCompletion(origCompletionDelegate, null, null);
}
}
/// <summary>
/// Handles streaming read completion.
/// </summary>
protected void HandleReadFinished(bool success, BatchContextSafeHandle ctx)
{
var payload = ctx.GetReceivedMessage();
AsyncCompletionDelegate<TRead> origCompletionDelegate = null;
lock (myLock)
{
origCompletionDelegate = readCompletionDelegate;
if (payload != null)
{
readCompletionDelegate = null;
}
else
{
// This was the last read. Keeping the readCompletionDelegate
// to be either fired by this handler or by client-side finished
// handler.
readingDone = true;
}
ReleaseResourcesIfPossible();
}
// TODO: handle the case when error occured...
if (payload != null)
{
// TODO: handle deserialization error
TRead msg;
TryDeserialize(payload, out msg);
FireCompletion(origCompletionDelegate, msg, null);
}
else
{
ProcessLastRead(origCompletionDelegate);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using DDay.iCal.Serialization;
using DDay.iCal.Serialization.iCalendar;
namespace DDay.iCal
{
/// <summary>
/// A class that represents an iCalendar object. To load an iCalendar object, generally a
/// static LoadFromXXX method is used.
/// <example>
/// For example, use the following code to load an iCalendar object from a URL:
/// <code>
/// IICalendar iCal = iCalendar.LoadFromUri(new Uri("http://somesite.com/calendar.ics"));
/// </code>
/// </example>
/// Once created, an iCalendar object can be used to gathers relevant information about
/// events, todos, time zones, journal entries, and free/busy time.
/// </summary>
/// <remarks>
/// <para>
/// The following is an example of loading an iCalendar and displaying a text-based calendar.
///
/// <code>
/// //
/// // The following code loads and displays an iCalendar
/// // with US Holidays for 2006.
/// //
/// IICalendar iCal = iCalendar.LoadFromUri(new Uri("http://www.applegatehomecare.com/Calendars/USHolidays.ics"));
///
/// IList<Occurrence> occurrences = iCal.GetOccurrences(
/// new iCalDateTime(2006, 1, 1, "US-Eastern", iCal),
/// new iCalDateTime(2006, 12, 31, "US-Eastern", iCal));
///
/// foreach (Occurrence o in occurrences)
/// {
/// IEvent evt = o.Component as IEvent;
/// if (evt != null)
/// {
/// // Display the date of the event
/// Console.Write(o.Period.StartTime.Local.Date.ToString("MM/dd/yyyy") + " -\t");
///
/// // Display the event summary
/// Console.Write(evt.Summary);
///
/// // Display the time the event happens (unless it's an all-day event)
/// if (evt.Start.HasTime)
/// {
/// Console.Write(" (" + evt.Start.Local.ToShortTimeString() + " - " + evt.End.Local.ToShortTimeString());
/// if (evt.Start.TimeZoneInfo != null)
/// Console.Write(" " + evt.Start.TimeZoneInfo.TimeZoneName);
/// Console.Write(")");
/// }
///
/// Console.Write(Environment.NewLine);
/// }
/// }
/// </code>
/// </para>
/// <para>
/// The following example loads all active to-do items from an iCalendar:
///
/// <code>
/// //
/// // The following code loads and displays active todo items from an iCalendar
/// // for January 6th, 2006.
/// //
/// IICalendar iCal = iCalendar.LoadFromUri(new Uri("http://somesite.com/calendar.ics"));
///
/// iCalDateTime dt = new iCalDateTime(2006, 1, 6, "US-Eastern", iCal);
/// foreach(Todo todo in iCal.Todos)
/// {
/// if (todo.IsActive(dt))
/// {
/// // Display the todo summary
/// Console.WriteLine(todo.Summary);
/// }
/// }
/// </code>
/// </para>
/// </remarks>
#if !SILVERLIGHT
[Serializable]
#endif
public class iCalendar :
CalendarComponent,
IICalendar,
IDisposable
{
#region Static Public Methods
#region LoadFromFile(...)
#region LoadFromFile(string filepath) variants
/// <summary>
/// Loads an <see cref="iCalendar"/> from the file system.
/// </summary>
/// <param name="Filepath">The path to the file to load.</param>
/// <returns>An <see cref="iCalendar"/> object</returns>
static public IICalendarCollection LoadFromFile(string filepath)
{
return LoadFromFile(filepath, Encoding.UTF8, new iCalendarSerializer());
}
static public IICalendarCollection LoadFromFile<T>(string filepath) where T : IICalendar
{
return LoadFromFile(typeof(T), filepath);
}
static public IICalendarCollection LoadFromFile(Type iCalendarType, string filepath)
{
ISerializer serializer = new iCalendarSerializer();
serializer.GetService<ISerializationSettings>().iCalendarType = iCalendarType;
return LoadFromFile(filepath, Encoding.UTF8, serializer);
}
#endregion
#region LoadFromFile(string filepath, Encoding encoding) variants
static public IICalendarCollection LoadFromFile(string filepath, Encoding encoding)
{
return LoadFromFile(filepath, encoding, new iCalendarSerializer());
}
static public IICalendarCollection LoadFromFile<T>(string filepath, Encoding encoding) where T : IICalendar
{
return LoadFromFile(typeof(T), filepath, encoding);
}
static public IICalendarCollection LoadFromFile(Type iCalendarType, string filepath, Encoding encoding)
{
ISerializer serializer = new iCalendarSerializer();
serializer.GetService<ISerializationSettings>().iCalendarType = iCalendarType;
return LoadFromFile(filepath, encoding, serializer);
}
static public IICalendarCollection LoadFromFile(string filepath, Encoding encoding, ISerializer serializer)
{
FileStream fs = new FileStream(filepath, FileMode.Open);
IICalendarCollection calendars = LoadFromStream(fs, encoding, serializer);
fs.Close();
return calendars;
}
#endregion
#endregion
#region LoadFromStream(...)
#region LoadFromStream(Stream s) variants
/// <summary>
/// Loads an <see cref="iCalendar"/> from an open stream.
/// </summary>
/// <param name="s">The stream from which to load the <see cref="iCalendar"/> object</param>
/// <returns>An <see cref="iCalendar"/> object</returns>
static public new IICalendarCollection LoadFromStream(Stream s)
{
return LoadFromStream(s, Encoding.UTF8, new iCalendarSerializer());
}
static public IICalendarCollection LoadFromStream<T>(Stream s) where T : IICalendar
{
return LoadFromStream(typeof(T), s);
}
static public IICalendarCollection LoadFromStream(Type iCalendarType, Stream s)
{
ISerializer serializer = new iCalendarSerializer();
serializer.GetService<ISerializationSettings>().iCalendarType = iCalendarType;
return LoadFromStream(s, Encoding.UTF8, serializer);
}
#endregion
#region LoadFromStream(Stream s, Encoding encoding) variants
static public new IICalendarCollection LoadFromStream(Stream s, Encoding encoding)
{
return LoadFromStream(s, encoding, new iCalendarSerializer());
}
static public new IICalendarCollection LoadFromStream<T>(Stream s, Encoding encoding) where T : IICalendar
{
return LoadFromStream(typeof(T), s, encoding);
}
static public IICalendarCollection LoadFromStream(Type iCalendarType, Stream s, Encoding encoding)
{
ISerializer serializer = new iCalendarSerializer();
serializer.GetService<ISerializationSettings>().iCalendarType = iCalendarType;
return LoadFromStream(s, encoding, serializer);
}
static public new IICalendarCollection LoadFromStream(Stream s, Encoding e, ISerializer serializer)
{
return serializer.Deserialize(s, e) as IICalendarCollection;
}
#endregion
#region LoadFromStream(TextReader tr) variants
static public new IICalendarCollection LoadFromStream(TextReader tr)
{
return LoadFromStream(tr, new iCalendarSerializer());
}
static public new IICalendarCollection LoadFromStream<T>(TextReader tr) where T : IICalendar
{
return LoadFromStream(typeof(T), tr);
}
static public IICalendarCollection LoadFromStream(Type iCalendarType, TextReader tr)
{
ISerializer serializer = new iCalendarSerializer();
serializer.GetService<ISerializationSettings>().iCalendarType = iCalendarType;
return LoadFromStream(tr, serializer);
}
static public IICalendarCollection LoadFromStream(TextReader tr, ISerializer serializer)
{
string text = tr.ReadToEnd();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text));
return LoadFromStream(ms, Encoding.UTF8, serializer);
}
#endregion
#endregion
#region LoadFromUri(...)
#region LoadFromUri(Uri uri) variants
/// <summary>
/// Loads an <see cref="iCalendar"/> from a given Uri.
/// </summary>
/// <param name="url">The Uri from which to load the <see cref="iCalendar"/> object</param>
/// <returns>An <see cref="iCalendar"/> object</returns>
static public IICalendarCollection LoadFromUri(Uri uri)
{
return LoadFromUri(typeof(iCalendar), uri, null, null, null);
}
static public IICalendarCollection LoadFromUri<T>(Uri uri) where T : IICalendar
{
return LoadFromUri(typeof(T), uri, null, null, null);
}
static public IICalendarCollection LoadFromUri(Type iCalendarType, Uri uri)
{
return LoadFromUri(iCalendarType, uri, null, null, null);
}
#if !SILVERLIGHT
static public IICalendarCollection LoadFromUri(Uri uri, WebProxy proxy)
{
return LoadFromUri(typeof(iCalendar), uri, null, null, proxy);
}
static public IICalendarCollection LoadFromUri<T>(Uri uri, WebProxy proxy)
{
return LoadFromUri(typeof(T), uri, null, null, proxy);
}
static public IICalendarCollection LoadFromUri(Type iCalendarType, Uri uri, WebProxy proxy)
{
return LoadFromUri(iCalendarType, uri, null, null, proxy);
}
#endif
#endregion
#region LoadFromUri(Uri uri, string username, string password) variants
/// <summary>
/// Loads an <see cref="iCalendar"/> from a given Uri, using a
/// specified <paramref name="username"/> and <paramref name="password"/>
/// for credentials.
/// </summary>
/// <param name="url">The Uri from which to load the <see cref="iCalendar"/> object</param>
/// <returns>an <see cref="iCalendar"/> object</returns>
static public IICalendarCollection LoadFromUri(Uri uri, string username, string password)
{
return LoadFromUri(typeof(iCalendar), uri, username, password, null);
}
static public IICalendarCollection LoadFromUri<T>(Uri uri, string username, string password) where T : IICalendar
{
return LoadFromUri(typeof(T), uri, username, password, null);
}
static public IICalendarCollection LoadFromUri(Type iCalendarType, Uri uri, string username, string password)
{
return LoadFromUri(iCalendarType, uri, username, password, null);
}
#if !SILVERLIGHT
static public IICalendarCollection LoadFromUri(Uri uri, string username, string password, WebProxy proxy)
{
return LoadFromUri(typeof(iCalendar), uri, username, password, proxy);
}
#endif
#endregion
#region LoadFromUri(Type iCalendarType, Uri uri, string username, string password, WebProxy proxy)
#if SILVERLIGHT
static public IICalendarCollection LoadFromUri(Type iCalendarType, Uri uri, string username, string password, object unusedProxy)
#else
static public IICalendarCollection LoadFromUri(Type iCalendarType, Uri uri, string username, string password, WebProxy proxy)
#endif
{
try
{
WebRequest request = WebRequest.Create(uri);
if (username != null && password != null)
request.Credentials = new System.Net.NetworkCredential(username, password);
#if !SILVERLIGHT
if (proxy != null)
request.Proxy = proxy;
#endif
AutoResetEvent evt = new AutoResetEvent(false);
string str = null;
request.BeginGetResponse(new AsyncCallback(
delegate(IAsyncResult result)
{
Encoding e = Encoding.UTF8;
try
{
using (WebResponse resp = request.EndGetResponse(result))
{
// Try to determine the content encoding
try
{
List<string> keys = new List<string>(resp.Headers.AllKeys);
if (keys.Contains("Content-Encoding"))
e = Encoding.GetEncoding(resp.Headers["Content-Encoding"]);
}
catch
{
// Fail gracefully back to UTF-8
}
using (Stream stream = resp.GetResponseStream())
using (StreamReader sr = new StreamReader(stream, e))
{
str = sr.ReadToEnd();
}
}
}
finally
{
evt.Set();
}
}
), null);
evt.WaitOne();
if (str != null)
return LoadFromStream(new StringReader(str));
return null;
}
catch (System.Net.WebException)
{
return null;
}
}
#endregion
#endregion
#endregion
#region Private Fields
private IUniqueComponentList<IUniqueComponent> m_UniqueComponents;
private IUniqueComponentList<IEvent> m_Events;
private IUniqueComponentList<ITodo> m_Todos;
private IUniqueComponentList<IJournal> m_Journals;
private IUniqueComponentList<IFreeBusy> m_FreeBusy;
private IFilteredCalendarObjectList<ITimeZone> m_TimeZones;
#endregion
#region Constructors
/// <summary>
/// To load an existing an iCalendar object, use one of the provided LoadFromXXX methods.
/// <example>
/// For example, use the following code to load an iCalendar object from a URL:
/// <code>
/// IICalendar iCal = iCalendar.LoadFromUri(new Uri("http://somesite.com/calendar.ics"));
/// </code>
/// </example>
/// </summary>
public iCalendar()
{
Initialize();
}
private void Initialize()
{
this.Name = Components.CALENDAR;
m_UniqueComponents = new UniqueComponentList<IUniqueComponent>(this);
m_Events = new UniqueComponentList<IEvent>(this);
m_Todos = new UniqueComponentList<ITodo>(this);
m_Journals = new UniqueComponentList<IJournal>(this);
m_FreeBusy = new UniqueComponentList<IFreeBusy>(this);
m_TimeZones = new FilteredCalendarObjectList<ITimeZone>(this);
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
public override bool Equals(object obj)
{
IICalendar iCal = obj as iCalendar;
if (iCal != null)
{
bool isEqual =
object.Equals(Version, iCal.Version) &&
object.Equals(ProductID, iCal.ProductID) &&
object.Equals(Scale, iCal.Scale) &&
object.Equals(Method, iCal.Method) &&
(
(UniqueComponents == null && iCal.UniqueComponents == null) ||
(UniqueComponents != null && iCal.UniqueComponents != null && object.Equals(UniqueComponents.Count, iCal.UniqueComponents.Count))
);
if (isEqual)
{
if (UniqueComponents.Count != iCal.UniqueComponents.Count)
return false;
IEnumerator<IUniqueComponent> e1 = UniqueComponents.GetEnumerator();
IEnumerator<IUniqueComponent> e2 = iCal.UniqueComponents.GetEnumerator();
while (e1.MoveNext())
{
if (!e2.MoveNext())
return false;
if (!object.Equals(e1.Current, e2.Current))
return false;
}
return !e2.MoveNext();
}
return false;
}
return base.Equals(obj);
}
#endregion
#region IICalendar Members
virtual public IUniqueComponentList<IUniqueComponent> UniqueComponents
{
get { return m_UniqueComponents; }
}
virtual public IEnumerable<IRecurrable> RecurringItems
{
get
{
foreach (object obj in Children)
{
if (obj is IRecurrable)
yield return (IRecurrable)obj;
}
}
}
/// <summary>
/// A collection of <see cref="Event"/> components in the iCalendar.
/// </summary>
virtual public IUniqueComponentList<IEvent> Events
{
get { return m_Events; }
}
/// <summary>
/// A collection of <see cref="DDay.iCal.FreeBusy"/> components in the iCalendar.
/// </summary>
virtual public IUniqueComponentList<IFreeBusy> FreeBusy
{
get { return m_FreeBusy; }
}
/// <summary>
/// A collection of <see cref="Journal"/> components in the iCalendar.
/// </summary>
virtual public IUniqueComponentList<IJournal> Journals
{
get { return m_Journals; }
}
/// <summary>
/// A collection of <see cref="DDay.iCal.TimeZone"/> components in the iCalendar.
/// </summary>
virtual public IFilteredCalendarObjectList<ITimeZone> TimeZones
{
get { return m_TimeZones; }
}
/// <summary>
/// A collection of <see cref="Todo"/> components in the iCalendar.
/// </summary>
virtual public IUniqueComponentList<ITodo> Todos
{
get { return m_Todos; }
}
virtual public string Version
{
get { return Properties.Get<string>("VERSION"); }
set { Properties.Set("VERSION", value); }
}
virtual public string ProductID
{
get { return Properties.Get<string>("PRODID"); }
set { Properties.Set("PRODID", value); }
}
virtual public string Scale
{
get { return Properties.Get<string>("CALSCALE"); }
set { Properties.Set("CALSCALE", value); }
}
virtual public string Method
{
get { return Properties.Get<string>("METHOD"); }
set { Properties.Set("METHOD", value); }
}
virtual public RecurrenceRestrictionType RecurrenceRestriction
{
get { return Properties.Get<RecurrenceRestrictionType>("X-DDAY-ICAL-RECURRENCE-RESTRICTION"); }
set { Properties.Set("X-DDAY-ICAL-RECURRENCE-RESTRICTION", value); }
}
virtual public RecurrenceEvaluationModeType RecurrenceEvaluationMode
{
get { return Properties.Get<RecurrenceEvaluationModeType>("X-DDAY-ICAL-RECURRENCE-EVALUATION-MODE"); }
set { Properties.Set("X-DDAY-ICAL-RECURRENCE-EVALUATION-MODE", value); }
}
/// <summary>
/// Adds a time zone to the iCalendar. This time zone may
/// then be used in date/time objects contained in the
/// calendar.
/// </summary>
/// <returns>The time zone added to the calendar.</returns>
public ITimeZone AddTimeZone(ITimeZone tz)
{
AddChild(tz);
return tz;
}
#if !SILVERLIGHT
/// <summary>
/// Adds a system time zone to the iCalendar. This time zone may
/// then be used in date/time objects contained in the
/// calendar.
/// </summary>
/// <param name="tzi">A System.TimeZoneInfo object to add to the calendar.</param>
/// <returns>The time zone added to the calendar.</returns>
public ITimeZone AddTimeZone(System.TimeZoneInfo tzi)
{
ITimeZone tz = iCalTimeZone.FromSystemTimeZone(tzi);
AddChild(tz);
return tz;
}
public ITimeZone AddTimeZone(System.TimeZoneInfo tzi, DateTime earliestDateTimeToSupport, bool includeHistoricalData)
{
ITimeZone tz = iCalTimeZone.FromSystemTimeZone(tzi, earliestDateTimeToSupport, includeHistoricalData);
AddChild(tz);
return tz;
}
/// <summary>
/// Adds the local system time zone to the iCalendar.
/// This time zone may then be used in date/time
/// objects contained in the calendar.
/// </summary>
/// <returns>The time zone added to the calendar.</returns>
public ITimeZone AddLocalTimeZone()
{
ITimeZone tz = iCalTimeZone.FromLocalTimeZone();
AddChild(tz);
return tz;
}
public ITimeZone AddLocalTimeZone(DateTime earliestDateTimeToSupport, bool includeHistoricalData)
{
ITimeZone tz = iCalTimeZone.FromLocalTimeZone(earliestDateTimeToSupport, includeHistoricalData);
AddChild(tz);
return tz;
}
#endif
/// <summary>
/// Retrieves the <see cref="DDay.iCal.TimeZone" /> object for the specified
/// <see cref="TZID"/> (Time Zone Identifier).
/// </summary>
/// <param name="tzid">A valid <see cref="TZID"/> object, or a valid <see cref="TZID"/> string.</param>
/// <returns>A <see cref="TimeZone"/> object for the <see cref="TZID"/>.</returns>
public ITimeZone GetTimeZone(string tzid)
{
foreach (ITimeZone tz in TimeZones)
{
if (tz.TZID.Equals(tzid))
{
return tz;
}
}
return null;
}
/// <summary>
/// Evaluates component recurrences for the given range of time.
/// <example>
/// For example, if you are displaying a month-view for January 2007,
/// you would want to evaluate recurrences for Jan. 1, 2007 to Jan. 31, 2007
/// to display relevant information for those dates.
/// </example>
/// </summary>
/// <param name="FromDate">The beginning date/time of the range to test.</param>
/// <param name="ToDate">The end date/time of the range to test.</param>
[Obsolete("This method is no longer supported. Use GetOccurrences() instead.")]
public void Evaluate(IDateTime FromDate, IDateTime ToDate)
{
throw new NotSupportedException("Evaluate() is no longer supported as a public method. Use GetOccurrences() instead.");
}
/// <summary>
/// Evaluates component recurrences for the given range of time, for
/// the type of recurring component specified.
/// </summary>
/// <typeparam name="T">The type of component to be evaluated for recurrences.</typeparam>
/// <param name="FromDate">The beginning date/time of the range to test.</param>
/// <param name="ToDate">The end date/time of the range to test.</param>
[Obsolete("This method is no longer supported. Use GetOccurrences() instead.")]
public void Evaluate<T>(IDateTime FromDate, IDateTime ToDate)
{
throw new NotSupportedException("Evaluate() is no longer supported as a public method. Use GetOccurrences() instead.");
}
/// <summary>
/// Clears recurrence evaluations for recurring components.
/// </summary>
public void ClearEvaluation()
{
foreach (IRecurrable recurrable in RecurringItems)
recurrable.ClearEvaluation();
}
/// <summary>
/// Returns a list of occurrences of each recurring component
/// for the date provided (<paramref name="dt"/>).
/// </summary>
/// <param name="dt">The date for which to return occurrences. Time is ignored on this parameter.</param>
/// <returns>A list of occurrences that occur on the given date (<paramref name="dt"/>).</returns>
virtual public IList<Occurrence> GetOccurrences(IDateTime dt)
{
return GetOccurrences<IRecurringComponent>(
new iCalDateTime(dt.Local.Date),
new iCalDateTime(dt.Local.Date.AddDays(1).AddSeconds(-1)));
}
virtual public IList<Occurrence> GetOccurrences(DateTime dt)
{
return GetOccurrences<IRecurringComponent>(
new iCalDateTime(dt.Date),
new iCalDateTime(dt.Date.AddDays(1).AddSeconds(-1)));
}
/// <summary>
/// Returns a list of occurrences of each recurring component
/// that occur between <paramref name="FromDate"/> and <paramref name="ToDate"/>.
/// </summary>
/// <param name="FromDate">The beginning date/time of the range.</param>
/// <param name="ToDate">The end date/time of the range.</param>
/// <returns>A list of occurrences that fall between the dates provided.</returns>
virtual public IList<Occurrence> GetOccurrences(IDateTime startTime, IDateTime endTime)
{
return GetOccurrences<IRecurringComponent>(startTime, endTime);
}
virtual public IList<Occurrence> GetOccurrences(DateTime startTime, DateTime endTime)
{
return GetOccurrences<IRecurringComponent>(new iCalDateTime(startTime), new iCalDateTime(endTime));
}
/// <summary>
/// Returns all occurrences of components of type T that start on the date provided.
/// All components starting between 12:00:00AM and 11:59:59 PM will be
/// returned.
/// <note>
/// This will first Evaluate() the date range required in order to
/// determine the occurrences for the date provided, and then return
/// the occurrences.
/// </note>
/// </summary>
/// <param name="dt">The date for which to return occurrences.</param>
/// <returns>A list of Periods representing the occurrences of this object.</returns>
virtual public IList<Occurrence> GetOccurrences<T>(IDateTime dt) where T : IRecurringComponent
{
return GetOccurrences<T>(
new iCalDateTime(dt.Local.Date),
new iCalDateTime(dt.Local.Date.AddDays(1).AddTicks(-1)));
}
virtual public IList<Occurrence> GetOccurrences<T>(DateTime dt) where T : IRecurringComponent
{
return GetOccurrences<T>(
new iCalDateTime(dt.Date),
new iCalDateTime(dt.Date.AddDays(1).AddTicks(-1)));
}
/// <summary>
/// Returns all occurrences of components of type T that start within the date range provided.
/// All components occurring between <paramref name="startTime"/> and <paramref name="endTime"/>
/// will be returned.
/// </summary>
/// <param name="startTime">The starting date range</param>
/// <param name="endTime">The ending date range</param>
virtual public IList<Occurrence> GetOccurrences<T>(IDateTime startTime, IDateTime endTime) where T : IRecurringComponent
{
List<Occurrence> occurrences = new List<Occurrence>();
foreach (IRecurrable recurrable in RecurringItems)
{
if (recurrable is T)
occurrences.AddRange(recurrable.GetOccurrences(startTime, endTime));
}
occurrences.Sort();
return occurrences;
}
virtual public IList<Occurrence> GetOccurrences<T>(DateTime startTime, DateTime endTime) where T : IRecurringComponent
{
return GetOccurrences<T>(new iCalDateTime(startTime), new iCalDateTime(endTime));
}
/// <summary>
/// Creates a typed object that is a direct child of the iCalendar itself. Generally,
/// you would invoke this method to create an Event, Todo, Journal, TimeZone, FreeBusy,
/// or other base component type.
/// </summary>
/// <example>
/// To create an event, use the following:
/// <code>
/// IICalendar iCal = new iCalendar();
///
/// Event evt = iCal.Create<Event>();
/// </code>
///
/// This creates the event, and adds it to the Events list of the iCalendar.
/// </example>
/// <typeparam name="T">The type of object to create</typeparam>
/// <returns>An object of the type specified</returns>
public T Create<T>() where T : ICalendarComponent
{
ICalendarObject obj = Activator.CreateInstance(typeof(T)) as ICalendarObject;
if (obj is T)
{
AddChild(obj);
return (T)obj;
}
return default(T);
}
#endregion
#region IDisposable Members
public void Dispose()
{
Children.Clear();
}
#endregion
#region IMergeable Members
virtual public void MergeWith(IMergeable obj)
{
IICalendar c = obj as IICalendar;
if (c != null)
{
if (Name == null)
Name = c.Name;
Method = c.Method;
Version = c.Version;
ProductID = c.ProductID;
Scale = c.Scale;
foreach (ICalendarProperty p in c.Properties)
{
if (!Properties.ContainsKey(p.Name))
Properties.Add(p.Copy<ICalendarProperty>());
}
foreach (ICalendarObject child in c.Children)
{
if (child is IUniqueComponent)
{
if (!UniqueComponents.ContainsKey(((IUniqueComponent)child).UID))
AddChild(child.Copy<ICalendarObject>());
}
else if (child is ITimeZone)
{
ITimeZone tz = GetTimeZone(((ITimeZone)child).TZID);
if (tz == null)
AddChild(child.Copy<ICalendarObject>());
}
else
{
AddChild(child.Copy<ICalendarObject>());
}
}
}
}
#endregion
#region IGetFreeBusy Members
virtual public IFreeBusy GetFreeBusy(IFreeBusy freeBusyRequest)
{
return DDay.iCal.FreeBusy.Create(this, freeBusyRequest);
}
virtual public IFreeBusy GetFreeBusy(IDateTime fromInclusive, IDateTime toExclusive)
{
return DDay.iCal.FreeBusy.Create(this, DDay.iCal.FreeBusy.CreateRequest(fromInclusive, toExclusive, null, null));
}
virtual public IFreeBusy GetFreeBusy(IOrganizer organizer, IAttendee[] contacts, IDateTime fromInclusive, IDateTime toExclusive)
{
return DDay.iCal.FreeBusy.Create(this, DDay.iCal.FreeBusy.CreateRequest(fromInclusive, toExclusive, organizer, contacts));
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules;
using OpenSim.Region;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using log4net;
namespace OpenSim.Region.ScriptEngine.DotNetEngine
{
/// <summary>
/// Prepares events so they can be directly executed upon a script by EventQueueManager, then queues it.
/// </summary>
[Serializable]
public class EventManager
{
//
// Class is instanced in "ScriptEngine" and Uses "EventQueueManager"
// that is also instanced in "ScriptEngine".
// This class needs a bit of explaining:
//
// This class it the link between an event inside OpenSim and
// the corresponding event in a user script being executed.
//
// For example when an user touches an object then the
// "myScriptEngine.World.EventManager.OnObjectGrab" event is fired
// inside OpenSim.
// We hook up to this event and queue a touch_start in
// EventQueueManager with the proper LSL parameters.
// It will then be delivered to the script by EventQueueManager.
//
// You can check debug C# dump of an LSL script if you need to
// verify what exact parameters are needed.
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ScriptEngine myScriptEngine;
public EventManager(ScriptEngine _ScriptEngine, bool performHookUp)
{
myScriptEngine = _ScriptEngine;
ReadConfig();
if (performHookUp)
{
myScriptEngine.World.EventManager.OnRezScript += OnRezScript;
}
}
public void HookUpEvents()
{
m_log.Info("[" + myScriptEngine.ScriptEngineName +
"]: Hooking up to server events");
myScriptEngine.World.EventManager.OnObjectGrab +=
touch_start;
myScriptEngine.World.EventManager.OnObjectDeGrab +=
touch_end;
myScriptEngine.World.EventManager.OnRemoveScript +=
OnRemoveScript;
myScriptEngine.World.EventManager.OnScriptChangedEvent +=
changed;
myScriptEngine.World.EventManager.OnScriptAtTargetEvent +=
at_target;
myScriptEngine.World.EventManager.OnScriptNotAtTargetEvent +=
not_at_target;
myScriptEngine.World.EventManager.OnScriptControlEvent +=
control;
myScriptEngine.World.EventManager.OnScriptColliderStart +=
collision_start;
myScriptEngine.World.EventManager.OnScriptColliding +=
collision;
myScriptEngine.World.EventManager.OnScriptCollidingEnd +=
collision_end;
IMoneyModule money =
myScriptEngine.World.RequestModuleInterface<IMoneyModule>();
if (money != null)
money.OnObjectPaid+=HandleObjectPaid;
}
public void ReadConfig()
{
}
private void HandleObjectPaid(UUID objectID, UUID agentID, int amount)
{
SceneObjectPart part =
myScriptEngine.World.GetSceneObjectPart(objectID);
if (part != null)
{
money(part.LocalId, agentID, amount);
}
}
public void changed(uint localID, uint change)
{
// Add to queue for all scripts in localID, Object pass change.
myScriptEngine.PostObjectEvent(localID, new EventParams(
"changed",new object[] { new LSL_Types.LSLInteger(change) },
new DetectParams[0]));
}
public void state_entry(uint localID)
{
// Add to queue for all scripts in ObjectID object
myScriptEngine.PostObjectEvent(localID, new EventParams(
"state_entry",new object[] { },
new DetectParams[0]));
}
public void touch_start(uint localID, uint originalID,
Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
if (originalID == 0)
{
SceneObjectPart part =
myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart =
myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch_start", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void touch(uint localID, uint originalID, Vector3 offsetPos,
IClientAPI remoteClient)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
det[0].OffsetPos = new LSL_Types.Vector3(offsetPos.X,
offsetPos.Y,
offsetPos.Z);
if (originalID == 0)
{
SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void touch_end(uint localID, uint originalID, IClientAPI remoteClient,
SurfaceTouchEventArgs surfaceArgs)
{
// Add to queue for all scripts in ObjectID object
DetectParams[] det = new DetectParams[1];
det[0] = new DetectParams();
det[0].Key = remoteClient.AgentId;
det[0].Populate(myScriptEngine.World);
if (originalID == 0)
{
SceneObjectPart part =
myScriptEngine.World.GetSceneObjectPart(localID);
if (part == null)
return;
det[0].LinkNum = part.LinkNum;
}
else
{
SceneObjectPart originalPart =
myScriptEngine.World.GetSceneObjectPart(originalID);
det[0].LinkNum = originalPart.LinkNum;
}
if (surfaceArgs != null)
{
det[0].SurfaceTouchArgs = surfaceArgs;
}
myScriptEngine.PostObjectEvent(localID, new EventParams(
"touch_end", new Object[] { new LSL_Types.LSLInteger(1) },
det));
}
public void OnRezScript(uint localID, UUID itemID, string script,
int startParam, bool postOnRez, string engine, int stateSource)
{
if (script.StartsWith("//MRM:"))
return;
List<IScriptModule> engines =
new List<IScriptModule>(
myScriptEngine.World.RequestModuleInterfaces<IScriptModule>());
List<string> names = new List<string>();
foreach (IScriptModule m in engines)
names.Add(m.ScriptEngineName);
int lineEnd = script.IndexOf('\n');
if (lineEnd > 1)
{
string firstline = script.Substring(0, lineEnd).Trim();
int colon = firstline.IndexOf(':');
if (firstline.Length > 2 &&
firstline.Substring(0, 2) == "//" && colon != -1)
{
string engineName = firstline.Substring(2, colon-2);
if (names.Contains(engineName))
{
engine = engineName;
script = "//" + script.Substring(script.IndexOf(':')+1);
}
else
{
if (engine == myScriptEngine.ScriptEngineName)
{
SceneObjectPart part =
myScriptEngine.World.GetSceneObjectPart(
localID);
TaskInventoryItem item =
part.Inventory.GetInventoryItem(itemID);
ScenePresence presence =
myScriptEngine.World.GetScenePresence(
item.OwnerID);
if (presence != null)
{
presence.ControllingClient.SendAgentAlertMessage(
"Selected engine unavailable. "+
"Running script on "+
myScriptEngine.ScriptEngineName,
false);
}
}
}
}
}
if (engine != myScriptEngine.ScriptEngineName)
return;
m_log.Debug("OnRezScript localID: " + localID +
" LLUID: " + itemID.ToString() + " Size: " +
script.Length);
myScriptEngine.m_ScriptManager.StartScript(localID, itemID, script,
startParam, postOnRez);
}
public void OnRemoveScript(uint localID, UUID itemID)
{
m_log.Debug("OnRemoveScript localID: " + localID + " LLUID: " + itemID.ToString());
myScriptEngine.m_ScriptManager.StopScript(
localID,
itemID
);
}
public void money(uint localID, UUID agentID, int amount)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"money", new object[] {
new LSL_Types.LSLString(agentID.ToString()),
new LSL_Types.LSLInteger(amount) },
new DetectParams[0]));
}
// TODO: Replace placeholders below
// NOTE! THE PARAMETERS FOR THESE FUNCTIONS ARE NOT CORRECT!
// These needs to be hooked up to OpenSim during init of this class
// then queued in EventQueueManager.
// When queued in EventQueueManager they need to be LSL compatible (name and params)
public void state_exit(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"state_exit", new object[] { },
new DetectParams[0]));
}
public void collision_start(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision_start",
new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void collision(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision", new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void collision_end(uint localID, ColliderArgs col)
{
// Add to queue for all scripts in ObjectID object
List<DetectParams> det = new List<DetectParams>();
foreach (DetectedObject detobj in col.Colliders)
{
DetectParams d = new DetectParams();
d.Key =detobj.keyUUID;
d.Populate(myScriptEngine.World);
det.Add(d);
}
if (det.Count > 0)
myScriptEngine.PostObjectEvent(localID, new EventParams(
"collision_end",
new Object[] { new LSL_Types.LSLInteger(det.Count) },
det.ToArray()));
}
public void land_collision_start(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision_start",
new object[0],
new DetectParams[0]));
}
public void land_collision(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision",
new object[0],
new DetectParams[0]));
}
public void land_collision_end(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"land_collision_end",
new object[0],
new DetectParams[0]));
}
// Handled by long commands
public void timer(uint localID, UUID itemID)
{
}
public void listen(uint localID, UUID itemID)
{
}
public void control(uint localID, UUID itemID, UUID agentID, uint held, uint change)
{
if ((change == 0) && (myScriptEngine.m_EventQueueManager.CheckEeventQueueForEvent(localID,"control"))) return;
myScriptEngine.PostObjectEvent(localID, new EventParams(
"control",new object[] {
new LSL_Types.LSLString(agentID.ToString()),
new LSL_Types.LSLInteger(held),
new LSL_Types.LSLInteger(change)},
new DetectParams[0]));
}
public void email(uint localID, UUID itemID, string timeSent,
string address, string subject, string message, int numLeft)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"email",new object[] {
new LSL_Types.LSLString(timeSent),
new LSL_Types.LSLString(address),
new LSL_Types.LSLString(subject),
new LSL_Types.LSLString(message),
new LSL_Types.LSLInteger(numLeft)},
new DetectParams[0]));
}
public void at_target(uint localID, uint handle, Vector3 targetpos,
Vector3 atpos)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"at_target", new object[] {
new LSL_Types.LSLInteger(handle),
new LSL_Types.Vector3(targetpos.X,targetpos.Y,targetpos.Z),
new LSL_Types.Vector3(atpos.X,atpos.Y,atpos.Z) },
new DetectParams[0]));
}
public void not_at_target(uint localID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"not_at_target",new object[0],
new DetectParams[0]));
}
public void at_rot_target(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"at_rot_target",new object[0],
new DetectParams[0]));
}
public void not_at_rot_target(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"not_at_rot_target",new object[0],
new DetectParams[0]));
}
public void attach(uint localID, UUID itemID)
{
}
public void dataserver(uint localID, UUID itemID)
{
}
public void link_message(uint localID, UUID itemID)
{
}
public void moving_start(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"moving_start",new object[0],
new DetectParams[0]));
}
public void moving_end(uint localID, UUID itemID)
{
myScriptEngine.PostObjectEvent(localID, new EventParams(
"moving_end",new object[0],
new DetectParams[0]));
}
public void object_rez(uint localID, UUID itemID)
{
}
public void remote_data(uint localID, UUID itemID)
{
}
// Handled by long commands
public void http_response(uint localID, UUID itemID)
{
}
/// <summary>
/// If set to true then threads and stuff should try to make a graceful exit
/// </summary>
public bool PleaseShutdown
{
get { return _PleaseShutdown; }
set { _PleaseShutdown = value; }
}
private bool _PleaseShutdown = false;
}
}
| |
using System.Linq;
using System.Web.Mvc;
using CRP.Controllers.Helpers;
using CRP.Controllers.ViewModels;
using CRP.Core.Domain;
using CRP.Core.Resources;
using MvcContrib;
using UCDArch.Web.Validator;
namespace CRP.Controllers
{
[Authorize]
public class QuestionController : ApplicationController
{
/// <summary>
/// GET: /Question/Create/{questionSetId}
/// Tested 20200421
/// </summary>
/// <param name="questionSetId">Question set Id</param>
/// <returns></returns>
public ActionResult Create(int questionSetId)
{
var questionSet = Repository.OfType<QuestionSet>().GetNullableById(questionSetId);
if (questionSet == null || !Access.HasQuestionSetAccess(Repository, CurrentUser, questionSet))
{
// go back to the question set edit view
return this.RedirectToAction<QuestionSetController>(a => a.List());
}
// Check to make sure the question set hasn't been used yet
// If it is reusable, and it has already been used, we can add a question to it.
if ((questionSet.SystemReusable || questionSet.CollegeReusable || questionSet.UserReusable) && questionSet.Items.Count > 0)
{
Message = "Question cannot be added to the question set because it is already being used by an item.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
// check to make sure it isn't the system's default contact information set
if (questionSet.Name == StaticValues.QuestionSet_ContactInformation && questionSet.SystemReusable)
{
Message = "This is a system default question set and cannot be modified.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
// lookups
ViewBag.QuestionTypes = Repository.OfType<QuestionType>().GetAll().ToList();
ViewBag.Validators = Repository.OfType<Validator>().GetAll().ToList();
var viewModel = new QuestionViewModel();
return View(viewModel);
}
/// <summary>
/// POST: /Question/Create/{questionSetId}
/// Tested 202020421
/// </summary>
/// <remarks>
/// Description:
/// Creates a question and associates it with a question set.
/// Assumption:
/// User trying to create the question is someone allowed to edit the question set container
/// PreCondition:
/// Question Set already exists
/// Question Set does not already have any items associated with it
/// PostCondition:
/// Question was created
/// Options were created if question needs them
/// </remarks>
/// <returns></returns>
[HttpPost]
public ActionResult Create(int questionSetId, QuestionViewModel model)
{
ModelState.Clear();
// look for question set
var questionSet = Repository.OfType<QuestionSet>().GetNullableById(questionSetId);
if (questionSet == null || !Access.HasQuestionSetAccess(Repository, CurrentUser, questionSet))
{
// go back to the question set edit view
return this.RedirectToAction<QuestionSetController>(a => a.List());
}
// Check to make sure the question set hasn't been used yet
// If it is reusable, and it has already been used, we can add a question to it.
if ((questionSet.SystemReusable || questionSet.CollegeReusable || questionSet.UserReusable) && questionSet.Items.Count > 0)
{
Message = "Question cannot be added to the question set because it is already being used by an item.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
// check to make sure it isn't the system's default contact information set
if (questionSet.Name == StaticValues.QuestionSet_ContactInformation && questionSet.SystemReusable)
{
Message = "This is a system default question set and cannot be modified.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
// lookups
ViewBag.QuestionTypes = Repository.OfType<QuestionType>().GetAll().ToList();
ViewBag.Validators = Repository.OfType<Validator>().GetAll().ToList();
// build new question
var question = new Question();
question.Name = model.Name;
// find question type
var questionType = Repository.OfType<QuestionType>().GetNullableById(model.QuestionTypeId);
if (questionType == null)
{
ModelState.AddModelError("Question.QuestionType", "Question Type not found.");
return View(model);
}
question.QuestionType = questionType;
// process the options
if (questionType.HasOptions)
{
foreach (var s in model.Options)
{
if (!string.IsNullOrEmpty(s))
{
var option = new QuestionOption(s);
question.AddOption(option);
}
}
}
// add the validators
foreach (var validatorId in model.Validators)
{
var validator = Repository.OfType<Validator>().GetNullableById(validatorId);
if (validator != null)
{
question.Validators.Add(validator);
}
}
// add the question to the set
questionSet.AddQuestion(question);
var validatorsSelected = question.Validators.Count(validator => validator.Class.ToLower().Trim() != "required");
// Validator and Question type validation:
switch (questionType.Name)
{
case "Text Box":
//All possible, but only a combination of required and others
if (validatorsSelected > 1)
{
ModelState.AddModelError("Question.Validators", "Cannot have Email, Url, Date, or Phone Number validators selected together.");
}
break;
case "Boolean":
if (question.Validators.Count > 0) //Count of all validators
{
ModelState.AddModelError("Question.Validators", "Boolean Question Type should not have validators.");
}
break;
case "Radio Buttons":
case "Checkbox List":
case "Drop Down":
case "Text Area":
if (validatorsSelected > 0) //count of all validators excluding required
{
ModelState.AddModelError("Question.Validators", string.Format("The only validator allowed for a Question Type of {0} is Required.", question.QuestionType.Name));
}
break;
case "Date":
foreach (var validator in question.Validators)
{
if (validator.Class.ToLower().Trim() != "required" && validator.Class.ToLower().Trim() != "date")
{
ModelState.AddModelError("Question.Validators", string.Format("{0} is not a valid validator for a Question Type of {1}", validator.Name, question.QuestionType.Name));
}
}
break;
case "No Answer":
foreach (var validator in question.Validators)
{
ModelState.AddModelError("Question.Validators", string.Format("{0} is not a valid validator for a Question Type of {1}", validator.Name, question.QuestionType.Name));
}
break;
default:
//No checks
break;
}
// check to make sure there are options if needed
if (questionType.HasOptions && question.Options.Count <= 0)
{
ModelState.AddModelError("Question.Options", "The question type requires at least one option.");
}
// check any other complex issues
MvcValidationAdapter.TransferValidationMessagesTo(ModelState, question.ValidationResults());
// not valid, go back
if (!ModelState.IsValid)
{
return View(model);
}
// valid redirect to edit
Repository.OfType<Question>().EnsurePersistent(question);
Message = NotificationMessages.STR_ObjectCreated.Replace(NotificationMessages.ObjectType, "Question");
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
/// <summary>
/// POST: /Question/Delete/{id}
/// Tested 20200421
/// </summary>
/// <remarks>
/// Assumption:
/// User trying to delete the question is someone allowed to edit the question set container
/// Description:
/// Delete a question from a question set.
/// PreCondition:
/// Question exists
/// Question set that the question is associated with is not used with any item
/// PostCondition:
/// Question is deleted.
/// </remarks>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Delete(int id)
{
var question = Repository.OfType<Question>().GetNullableById(id);
if (question == null || !Access.HasQuestionSetAccess(Repository, CurrentUser, question.QuestionSet))
{
return this.RedirectToAction<QuestionSetController>(a => a.List());
}
var questionSetId = question.QuestionSet.Id;
// Check to make sure the question set hasn't been used yet
if (question.QuestionSet.Items.Count > 0 &&
(question.QuestionSet.CollegeReusable || question.QuestionSet.SystemReusable || question.QuestionSet.UserReusable))
{
Message = "Question cannot be deleted from the question set because it is already being used by an item.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
// check to make sure it isn't the system's default contact information set
if (question.QuestionSet.Name == StaticValues.QuestionSet_ContactInformation && question.QuestionSet.SystemReusable)
{
//ModelState.AddModelError("Question Set", "This is a sytem default question set and cannot be modified.");
Message = "Question cannot be deleted from the question set because it is a system default.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
//Check to make sure there isn't an answer
if(Repository.OfType<TransactionAnswer>().Queryable.Where(a => a.Question == question).Any()
|| Repository.OfType<QuantityAnswer>().Queryable.Where(a => a.Question == question).Any())
{
Message =
"Question cannot be deleted from the question set because it has an answer associated with it.";
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
// delete the object
Repository.OfType<Question>().Remove(question);
Message = NotificationMessages.STR_ObjectRemoved.Replace(NotificationMessages.ObjectType, "Question");
return this.RedirectToAction<QuestionSetController>(a => a.Edit(questionSetId));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Cairo;
using Gdk;
using Gtk;
using NLog;
using SlimeSimulation.Controller.WindowComponentController;
using SlimeSimulation.Model;
namespace SlimeSimulation.View.WindowComponent
{
public class GraphDrawingArea : DrawingArea
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private const double MaxLineWidth = 8;
private const double WindowSpacePercentToDrawIn = 0.9;
private const double LinePaddingPercent = 0.05;
public const double MinEdgeWeightToDraw = 0;
private readonly LineViewController _lineViewController;
private readonly NodeViewController _nodeViewController;
private readonly ICollection<Edge> _edges = new List<Edge>();
private readonly ISet<Node> _nodes = new HashSet<Node>();
private EdgeDrawing _edgeDrawingOption = EdgeDrawing.WithoutWeight;
private readonly double _maxNodeX;
private readonly double _maxNodeY;
private readonly double _minNodeY;
private readonly double _minNodeX;
private double _maxWindowX = 100;
private double _maxWindowY = 100;
public GraphDrawingArea(ICollection<Edge> edges, LineViewController lineWidthController,
NodeViewController nodeViewController)
{
_nodeViewController = nodeViewController;
foreach (var edge in edges)
{
AddEdge(edge);
}
var nodesSortedByXAscending = Nodes.SortByXAscending(_nodes);
_minNodeX = nodesSortedByXAscending.First().X;
_maxNodeX = nodesSortedByXAscending.Last().X;
var nodesSortedByYAscending = Nodes.SortByYAscending(_nodes);
_minNodeY = nodesSortedByYAscending.First().Y;
_maxNodeY = nodesSortedByYAscending.Last().Y;
_lineViewController = lineWidthController;
Logger.Debug("[Constructor] Given number of edges: {0}", edges.Count);
}
private void AddEdge(Edge slimeEdge)
{
_edges.Add(slimeEdge);
_nodes.Add(slimeEdge.A);
_nodes.Add(slimeEdge.B);
}
private void DrawPoint(Context graphic, Node node)
{
graphic.Save();
var xscaled = ScaleX(node.X);
var yscaled = ScaleY(node.Y);
Logger.Trace("[DrawPoint] Drawing at: {0},{1}", xscaled, yscaled);
var color = _nodeViewController.GetColourForNode(node);
Logger.Trace($"[DrawPoint] Using colour: {color} for node {node}");
double size = _nodeViewController.GetSizeForNode(node);
graphic.SetSourceRGB(color.R, color.G, color.B);
graphic.Rectangle(xscaled - size / 2, yscaled - size / 2, size, size);
graphic.Fill();
graphic.Stroke();
graphic.Restore();
}
protected virtual void DrawEdge(Context graphic, Edge edge)
{
if (Math.Abs(_lineViewController.GetLineWeightForEdge(edge)) < MinEdgeWeightToDraw)
{
return;
}
graphic.Save();
Logger.Trace("[DrawEdge] Drawing from {0},{1} to {2},{3}", ScaleX(edge.A.X), ScaleY(edge.A.Y),
ScaleX(edge.B.X), ScaleY(edge.B.Y));
graphic.MoveTo(ScaleX(edge.A.X), ScaleY(edge.A.Y));
var color = _lineViewController.GetColourForEdge(edge);
graphic.SetSourceRGB(color.R, color.G, color.B);
graphic.LineWidth = GetLineWidthForEdge(edge);
Logger.Trace("[DrawEdge] For SlimeEdge {0}, using lineWidth: {1}", edge, graphic.LineWidth);
graphic.LineTo(ScaleX(edge.B.X), ScaleY(edge.B.Y));
graphic.Stroke();
graphic.Restore();
if (_edgeDrawingOption == EdgeDrawing.WithWeight)
{
DrawTextNearCoord(graphic, "w:" + String.Format("{0:0.000}", _lineViewController.GetLineWeightForEdge(edge)),
ScaleX((edge.A.X + edge.B.X) / 2), ScaleY(edge.A.Y + edge.B.Y) / 2);
}
}
private void DrawXyKey(Context graphic)
{
for (int x = Math.Min(0, (int)_minNodeX); x <= _maxNodeX; x++)
{
DrawTextNearCoord(graphic, x.ToString(), ScaleX(x), 50);
}
for (int y = Math.Min(0, (int)_minNodeY); y <= _maxNodeY; y++)
{
DrawTextNearCoord(graphic, y.ToString(), 50, ScaleY(y));
}
}
private void DrawTextNearCoord(Context graphic, String s, double x, double y)
{
#if DEBUG
Logger.Trace("[DrawTextNearCoord] Drawing {0} at {1}, {2}", s, x, y);
graphic.Save();
graphic.MoveTo(x - 5, y - 5);
graphic.ShowText(s);
graphic.Restore();
#endif
}
private double ScaleX(double x)
{
var percent = (x - _minNodeX) / (_maxNodeX - _minNodeX);
var availableDrawingSpace = _maxWindowX * WindowSpacePercentToDrawIn;
var padding = (_maxWindowX - availableDrawingSpace) / 2;
return availableDrawingSpace * percent + padding;
}
private double ScaleY(double y)
{
var percent = (y - _minNodeY) / (_maxNodeY - _minNodeY);
var availableDrawingSpace = _maxWindowY * WindowSpacePercentToDrawIn;
var padding = (_maxWindowY - availableDrawingSpace) / 2;
return availableDrawingSpace * percent + padding;
}
private double GetLineWidthForEdge(Edge slimeEdge)
{
var weight = _lineViewController.GetLineWeightForEdge(slimeEdge);
var percentAsNumberBetweenOneAndZero = weight / _lineViewController.GetMaximumLineWeight();
if (_lineViewController.GetMaximumLineWeight() == 0)
{
percentAsNumberBetweenOneAndZero = 0;
}
var padding = MaxLineWidth * LinePaddingPercent;
return percentAsNumberBetweenOneAndZero * (MaxLineWidth - 2 * padding) + padding;
}
protected override bool OnExposeEvent(EventExpose args)
{
Logger.Debug("[OnExposeEvent] Redrawing");
var allocation = Allocation;
_maxWindowX = allocation.Width;
_maxWindowY = allocation.Height;
using (var g = CairoHelper.Create(args.Window))
{
DrawEdges(g);
DrawNodes(g);
if (_edgeDrawingOption == EdgeDrawing.WithWeight)
{
DrawXyKey(g);
}
}
return true;
}
protected void DrawEdges(Context context)
{
Logger.Trace("[OnExposeEvent] Drawing all edges, total #: {0}", _edges.Count);
foreach (var edge in _edges)
{
DrawEdge(context, edge);
}
}
protected void DrawNodes(Context context)
{
Logger.Trace("[OnExposeEvent] Drawing all nodes, total #: {0}", _nodes.Count);
foreach (var node in _nodes)
{
if (node.IsFoodSource)
{
DrawPoint(context, node);
}
else
{
DrawPoint(context, node);
}
}
}
public void InvertEdgeDrawing()
{
if (_edgeDrawingOption == EdgeDrawing.WithoutWeight)
{
_edgeDrawingOption = EdgeDrawing.WithWeight;
}
else
{
_edgeDrawingOption = EdgeDrawing.WithoutWeight;
}
QueueDraw();
}
}
public enum EdgeDrawing
{
WithWeight,
WithoutWeight
}
}
| |
// 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.Threading;
namespace System.Transactions
{
public enum TransactionScopeOption
{
Required,
RequiresNew,
Suppress,
}
//
// The legacy TransactionScope uses TLS to store the ambient transaction. TLS data doesn't flow across thread continuations and hence legacy TransactionScope does not compose well with
// new .Net async programming model constructs like Tasks and async/await. To enable TransactionScope to work with Task and async/await, a new TransactionScopeAsyncFlowOption
// is introduced. When users opt-in the async flow option, ambient transaction will automatically flow across thread continuations and user can compose TransactionScope with Task and/or
// async/await constructs.
//
public enum TransactionScopeAsyncFlowOption
{
Suppress, // Ambient transaction will be stored in TLS and will not flow across thread continuations.
Enabled, // Ambient transaction will be stored in CallContext and will flow across thread continuations. This option will enable TransactionScope to compose well with Task and async/await.
}
public enum EnterpriseServicesInteropOption
{
None = 0,
Automatic = 1,
Full = 2
}
public sealed class TransactionScope : IDisposable
{
public TransactionScope() : this(TransactionScopeOption.Required)
{
}
public TransactionScope(TransactionScopeOption scopeOption)
: this(scopeOption, TransactionScopeAsyncFlowOption.Suppress)
{
}
public TransactionScope(TransactionScopeAsyncFlowOption asyncFlowOption)
: this(TransactionScopeOption.Required, asyncFlowOption)
{
}
public TransactionScope(
TransactionScopeOption scopeOption,
TransactionScopeAsyncFlowOption asyncFlowOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateAndSetAsyncFlowOption(asyncFlowOption);
if (NeedToCreateTransaction(scopeOption))
{
_committableTransaction = new CommittableTransaction();
_expectedCurrent = _committableTransaction.Clone();
}
if (null == _expectedCurrent)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction);
}
}
else
{
TransactionScopeResult scopeResult;
if (null == _committableTransaction)
{
scopeResult = TransactionScopeResult.UsingExistingCurrent;
}
else
{
scopeResult = TransactionScopeResult.CreatedTransaction;
}
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(_expectedCurrent.TransactionTraceId, scopeResult);
}
}
PushScope();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout)
: this(scopeOption, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress)
{
}
public TransactionScope(
TransactionScopeOption scopeOption,
TimeSpan scopeTimeout,
TransactionScopeAsyncFlowOption asyncFlowOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateScopeTimeout(nameof(scopeTimeout), scopeTimeout);
TimeSpan txTimeout = TransactionManager.ValidateTimeout(scopeTimeout);
ValidateAndSetAsyncFlowOption(asyncFlowOption);
if (NeedToCreateTransaction(scopeOption))
{
_committableTransaction = new CommittableTransaction(txTimeout);
_expectedCurrent = _committableTransaction.Clone();
}
if ((null != _expectedCurrent) && (null == _committableTransaction) && (TimeSpan.Zero != scopeTimeout))
{
// BUGBUG: Scopes should not use individual timers
_scopeTimer = new Timer(
TimerCallback,
this,
scopeTimeout,
TimeSpan.Zero);
}
if (null == _expectedCurrent)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction);
}
}
else
{
TransactionScopeResult scopeResult;
if (null == _committableTransaction)
{
scopeResult = TransactionScopeResult.UsingExistingCurrent;
}
else
{
scopeResult = TransactionScopeResult.CreatedTransaction;
}
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(_expectedCurrent.TransactionTraceId, scopeResult);
}
}
PushScope();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions)
: this(scopeOption, transactionOptions, TransactionScopeAsyncFlowOption.Suppress)
{
}
public TransactionScope(
TransactionScopeOption scopeOption,
TransactionOptions transactionOptions,
TransactionScopeAsyncFlowOption asyncFlowOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateScopeTimeout("transactionOptions.Timeout", transactionOptions.Timeout);
TimeSpan scopeTimeout = transactionOptions.Timeout;
transactionOptions.Timeout = TransactionManager.ValidateTimeout(transactionOptions.Timeout);
TransactionManager.ValidateIsolationLevel(transactionOptions.IsolationLevel);
ValidateAndSetAsyncFlowOption(asyncFlowOption);
if (NeedToCreateTransaction(scopeOption))
{
_committableTransaction = new CommittableTransaction(transactionOptions);
_expectedCurrent = _committableTransaction.Clone();
}
else
{
if (null != _expectedCurrent)
{
// If the requested IsolationLevel is stronger than that of the specified transaction, throw.
if ((IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && (_expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel))
{
throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, "transactionOptions.IsolationLevel");
}
}
}
if ((null != _expectedCurrent) && (null == _committableTransaction) && (TimeSpan.Zero != scopeTimeout))
{
// BUGBUG: Scopes should use a shared timer
_scopeTimer = new Timer(
TimerCallback,
this,
scopeTimeout,
TimeSpan.Zero);
}
if (null == _expectedCurrent)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction);
}
}
else
{
TransactionScopeResult scopeResult;
if (null == _committableTransaction)
{
scopeResult = TransactionScopeResult.UsingExistingCurrent;
}
else
{
scopeResult = TransactionScopeResult.CreatedTransaction;
}
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(_expectedCurrent.TransactionTraceId, scopeResult);
}
}
PushScope();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
public TransactionScope(
TransactionScopeOption scopeOption,
TransactionOptions transactionOptions,
EnterpriseServicesInteropOption interopOption)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateScopeTimeout("transactionOptions.Timeout", transactionOptions.Timeout);
TimeSpan scopeTimeout = transactionOptions.Timeout;
transactionOptions.Timeout = TransactionManager.ValidateTimeout(transactionOptions.Timeout);
TransactionManager.ValidateIsolationLevel(transactionOptions.IsolationLevel);
ValidateInteropOption(interopOption);
_interopModeSpecified = true;
_interopOption = interopOption;
if (NeedToCreateTransaction(scopeOption))
{
_committableTransaction = new CommittableTransaction(transactionOptions);
_expectedCurrent = _committableTransaction.Clone();
}
else
{
if (null != _expectedCurrent)
{
// If the requested IsolationLevel is stronger than that of the specified transaction, throw.
if ((IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && (_expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel))
{
throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, "transactionOptions.IsolationLevel");
}
}
}
if ((null != _expectedCurrent) && (null == _committableTransaction) && (TimeSpan.Zero != scopeTimeout))
{
// BUGBUG: Scopes should use a shared timer
_scopeTimer = new Timer(
TimerCallback,
this,
scopeTimeout,
TimeSpan.Zero);
}
if (null == _expectedCurrent)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction);
}
}
else
{
TransactionScopeResult scopeResult;
if (null == _committableTransaction)
{
scopeResult = TransactionScopeResult.UsingExistingCurrent;
}
else
{
scopeResult = TransactionScopeResult.CreatedTransaction;
}
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(_expectedCurrent.TransactionTraceId, scopeResult);
}
}
PushScope();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
public TransactionScope(Transaction transactionToUse)
: this(transactionToUse, TransactionScopeAsyncFlowOption.Suppress)
{
}
public TransactionScope(
Transaction transactionToUse,
TransactionScopeAsyncFlowOption asyncFlowOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateAndSetAsyncFlowOption(asyncFlowOption);
Initialize(
transactionToUse,
TimeSpan.Zero,
false);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout)
: this(transactionToUse, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress)
{
}
public TransactionScope(
Transaction transactionToUse,
TimeSpan scopeTimeout,
TransactionScopeAsyncFlowOption asyncFlowOption)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateAndSetAsyncFlowOption(asyncFlowOption);
Initialize(
transactionToUse,
scopeTimeout,
false);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
public TransactionScope(
Transaction transactionToUse,
TimeSpan scopeTimeout,
EnterpriseServicesInteropOption interopOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
ValidateInteropOption(interopOption);
_interopOption = interopOption;
Initialize(
transactionToUse,
scopeTimeout,
true);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
private bool NeedToCreateTransaction(TransactionScopeOption scopeOption)
{
bool retVal = false;
CommonInitialize();
// If the options specify NoTransactionNeeded, that trumps everything else.
switch (scopeOption)
{
case TransactionScopeOption.Suppress:
_expectedCurrent = null;
retVal = false;
break;
case TransactionScopeOption.Required:
_expectedCurrent = _savedCurrent;
// If current is null, we need to create one.
if (null == _expectedCurrent)
{
retVal = true;
}
break;
case TransactionScopeOption.RequiresNew:
retVal = true;
break;
default:
throw new ArgumentOutOfRangeException(nameof(scopeOption));
}
return retVal;
}
private void Initialize(
Transaction transactionToUse,
TimeSpan scopeTimeout,
bool interopModeSpecified)
{
if (null == transactionToUse)
{
throw new ArgumentNullException(nameof(transactionToUse));
}
ValidateScopeTimeout(nameof(scopeTimeout), scopeTimeout);
CommonInitialize();
if (TimeSpan.Zero != scopeTimeout)
{
_scopeTimer = new Timer(
TimerCallback,
this,
scopeTimeout,
TimeSpan.Zero
);
}
_expectedCurrent = transactionToUse;
_interopModeSpecified = interopModeSpecified;
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCreated(_expectedCurrent.TransactionTraceId, TransactionScopeResult.TransactionPassed);
}
PushScope();
}
// We don't have a finalizer (~TransactionScope) because all it would be able to do is try to
// operate on other managed objects (the transaction), which is not safe to do because they may
// already have been finalized.
public void Dispose()
{
bool successful = false;
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
if (_disposed)
{
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
return;
}
// Dispose for a scope can only be called on the thread where the scope was created.
if ((_scopeThread != Thread.CurrentThread) && !AsyncFlowEnabled)
{
if (etwLog.IsEnabled())
{
etwLog.InvalidOperation("TransactionScope", "InvalidScopeThread");
}
throw new InvalidOperationException(SR.InvalidScopeThread);
}
Exception exToThrow = null;
try
{
// Single threaded from this point
_disposed = true;
// First, lets pop the "stack" of TransactionScopes and dispose each one that is above us in
// the stack, making sure they are NOT consistent before disposing them.
// Optimize the first lookup by getting both the actual current scope and actual current
// transaction at the same time.
TransactionScope actualCurrentScope = _threadContextData.CurrentScope;
Transaction contextTransaction = null;
Transaction current = Transaction.FastGetTransaction(actualCurrentScope, _threadContextData, out contextTransaction);
if (!Equals(actualCurrentScope))
{
// Ok this is bad. But just how bad is it. The worst case scenario is that someone is
// poping scopes out of order and has placed a new transaction in the top level scope.
// Check for that now.
if (actualCurrentScope == null)
{
// Something must have gone wrong trying to clean up a bad scope
// stack previously.
// Make a best effort to abort the active transaction.
Transaction rollbackTransaction = _committableTransaction;
if (rollbackTransaction == null)
{
rollbackTransaction = _dependentTransaction;
}
Debug.Assert(rollbackTransaction != null);
rollbackTransaction.Rollback();
successful = true;
throw TransactionException.CreateInvalidOperationException(
TraceSourceType.TraceSourceBase, SR.TransactionScopeInvalidNesting, null, rollbackTransaction.DistributedTxId);
}
// Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None.
else if (EnterpriseServicesInteropOption.None == actualCurrentScope._interopOption)
{
if (((null != actualCurrentScope._expectedCurrent) && (!actualCurrentScope._expectedCurrent.Equals(current)))
||
((null != current) && (null == actualCurrentScope._expectedCurrent))
)
{
TransactionTraceIdentifier myId;
TransactionTraceIdentifier currentId;
if (null == current)
{
currentId = TransactionTraceIdentifier.Empty;
}
else
{
currentId = current.TransactionTraceId;
}
if (null == _expectedCurrent)
{
myId = TransactionTraceIdentifier.Empty;
}
else
{
myId = _expectedCurrent.TransactionTraceId;
}
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCurrentChanged(currentId, myId);
}
exToThrow = TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.TransactionScopeIncorrectCurrent, null,
current == null ? Guid.Empty : current.DistributedTxId);
// If there is a current transaction, abort it.
if (null != current)
{
try
{
current.Rollback();
}
catch (TransactionException)
{
// we are already going to throw and exception, so just ignore this one.
}
catch (ObjectDisposedException)
{
// Dito
}
}
}
}
// Now fix up the scopes
while (!Equals(actualCurrentScope))
{
if (null == exToThrow)
{
exToThrow = TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.TransactionScopeInvalidNesting, null,
current == null ? Guid.Empty : current.DistributedTxId);
}
if (null == actualCurrentScope._expectedCurrent)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeNestedIncorrectly(TransactionTraceIdentifier.Empty);
}
}
else
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeNestedIncorrectly(actualCurrentScope._expectedCurrent.TransactionTraceId);
}
}
actualCurrentScope._complete = false;
try
{
actualCurrentScope.InternalDispose();
}
catch (TransactionException)
{
// we are already going to throw an exception, so just ignore this one.
}
actualCurrentScope = _threadContextData.CurrentScope;
// We want to fail this scope, too, because work may have been done in one of these other
// nested scopes that really should have been done in my scope.
_complete = false;
}
}
else
{
// Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None.
// If we got here, actualCurrentScope is the same as "this".
if (EnterpriseServicesInteropOption.None == _interopOption)
{
if (((null != _expectedCurrent) && (!_expectedCurrent.Equals(current)))
|| ((null != current) && (null == _expectedCurrent))
)
{
TransactionTraceIdentifier myId;
TransactionTraceIdentifier currentId;
if (null == current)
{
currentId = TransactionTraceIdentifier.Empty;
}
else
{
currentId = current.TransactionTraceId;
}
if (null == _expectedCurrent)
{
myId = TransactionTraceIdentifier.Empty;
}
else
{
myId = _expectedCurrent.TransactionTraceId;
}
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeCurrentChanged(currentId, myId);
}
if (null == exToThrow)
{
exToThrow = TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.TransactionScopeIncorrectCurrent, null,
current == null ? Guid.Empty : current.DistributedTxId);
}
// If there is a current transaction, abort it.
if (null != current)
{
try
{
current.Rollback();
}
catch (TransactionException)
{
// we are already going to throw and exception, so just ignore this one.
}
catch (ObjectDisposedException)
{
// Dito
}
}
// Set consistent to false so that the subsequent call to
// InternalDispose below will rollback this.expectedCurrent.
_complete = false;
}
}
}
successful = true;
}
finally
{
if (!successful)
{
PopScope();
}
}
// No try..catch here. Just let any exception thrown by InternalDispose go out.
InternalDispose();
if (null != exToThrow)
{
throw exToThrow;
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
private void InternalDispose()
{
// Set this if it is called internally.
_disposed = true;
try
{
PopScope();
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (null == _expectedCurrent)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeDisposed(TransactionTraceIdentifier.Empty);
}
}
else
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeDisposed(_expectedCurrent.TransactionTraceId);
}
}
// If Transaction.Current is not null, we have work to do. Otherwise, we don't, except to replace
// the previous value.
if (null != _expectedCurrent)
{
if (!_complete)
{
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeIncomplete(_expectedCurrent.TransactionTraceId);
}
//
// Note: Rollback is not called on expected current because someone could conceiveably
// dispose expectedCurrent out from under the transaction scope.
//
Transaction rollbackTransaction = _committableTransaction;
if (rollbackTransaction == null)
{
rollbackTransaction = _dependentTransaction;
}
Debug.Assert(rollbackTransaction != null);
rollbackTransaction.Rollback();
}
else
{
// If we are supposed to commit on dispose, cast to CommittableTransaction and commit it.
if (null != _committableTransaction)
{
_committableTransaction.Commit();
}
else
{
Debug.Assert(null != _dependentTransaction, "null != this.dependentTransaction");
_dependentTransaction.Complete();
}
}
}
}
finally
{
if (null != _scopeTimer)
{
_scopeTimer.Dispose();
}
if (null != _committableTransaction)
{
_committableTransaction.Dispose();
// If we created the committable transaction then we placed a clone in expectedCurrent
// and it needs to be disposed as well.
_expectedCurrent.Dispose();
}
if (null != _dependentTransaction)
{
_dependentTransaction.Dispose();
}
}
}
public void Complete()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this);
}
if (_disposed)
{
throw new ObjectDisposedException(nameof(TransactionScope));
}
if (_complete)
{
throw TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.DisposeScope, null);
}
_complete = true;
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, this);
}
}
private static void TimerCallback(object state)
{
TransactionScope scope = state as TransactionScope;
if (null == scope)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeInternalError("TransactionScopeTimerObjectInvalid");
}
throw TransactionException.Create(TraceSourceType.TraceSourceBase, SR.InternalError + SR.TransactionScopeTimerObjectInvalid, null);
}
scope.Timeout();
}
private void Timeout()
{
if ((!_complete) && (null != _expectedCurrent))
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionScopeTimeout(_expectedCurrent.TransactionTraceId);
}
try
{
_expectedCurrent.Rollback();
}
catch (ObjectDisposedException ex)
{
// Tolerate the fact that the transaction has already been disposed.
if (etwLog.IsEnabled())
{
etwLog.ExceptionConsumed(TraceSourceType.TraceSourceBase, ex);
}
}
catch (TransactionException txEx)
{
// Tolerate transaction exceptions
if (etwLog.IsEnabled())
{
etwLog.ExceptionConsumed(TraceSourceType.TraceSourceBase, txEx);
}
}
}
}
private void CommonInitialize()
{
ContextKey = new ContextKey();
_complete = false;
_dependentTransaction = null;
_disposed = false;
_committableTransaction = null;
_expectedCurrent = null;
_scopeTimer = null;
_scopeThread = Thread.CurrentThread;
Transaction.GetCurrentTransactionAndScope(
AsyncFlowEnabled ? TxLookup.DefaultCallContext : TxLookup.DefaultTLS,
out _savedCurrent,
out _savedCurrentScope,
out _contextTransaction
);
// Calling validate here as we need to make sure the existing parent ambient transaction scope is already looked up to see if we have ES interop enabled.
ValidateAsyncFlowOptionAndESInteropOption();
}
// PushScope
//
// Push a transaction scope onto the stack.
private void PushScope()
{
// Fixup the interop mode before we set current.
if (!_interopModeSpecified)
{
// Transaction.InteropMode will take the interop mode on
// for the scope in currentScope into account.
_interopOption = Transaction.InteropMode(_savedCurrentScope);
}
// async function yield at await points and main thread can continue execution. We need to make sure the TLS data are restored appropriately.
SaveTLSContextData();
if (AsyncFlowEnabled)
{
// Async Flow is enabled and CallContext will be used for ambient transaction.
_threadContextData = CallContextCurrentData.CreateOrGetCurrentData(ContextKey);
if (_savedCurrentScope == null && _savedCurrent == null)
{
// Clear TLS data so that transaction doesn't leak from current thread.
ContextData.TLSCurrentData = null;
}
}
else
{
// Legacy TransactionScope. Use TLS to track ambient transaction context.
_threadContextData = ContextData.TLSCurrentData;
CallContextCurrentData.ClearCurrentData(ContextKey, false);
}
// This call needs to be done first
SetCurrent(_expectedCurrent);
_threadContextData.CurrentScope = this;
}
// PopScope
//
// Pop the current transaction scope off the top of the stack
private void PopScope()
{
bool shouldRestoreContextData = true;
// Clear the current TransactionScope CallContext data
if (AsyncFlowEnabled)
{
CallContextCurrentData.ClearCurrentData(ContextKey, true);
}
if (_scopeThread == Thread.CurrentThread)
{
// async function yield at await points and main thread can continue execution. We need to make sure the TLS data are restored appropriately.
// Restore the TLS only if the thread Ids match.
RestoreSavedTLSContextData();
}
// Restore threadContextData to parent CallContext or TLS data
if (_savedCurrentScope != null)
{
if (_savedCurrentScope.AsyncFlowEnabled)
{
_threadContextData = CallContextCurrentData.CreateOrGetCurrentData(_savedCurrentScope.ContextKey);
}
else
{
if (_savedCurrentScope._scopeThread != Thread.CurrentThread)
{
// Clear TLS data so that transaction doesn't leak from current thread.
shouldRestoreContextData = false;
ContextData.TLSCurrentData = null;
}
else
{
_threadContextData = ContextData.TLSCurrentData;
}
CallContextCurrentData.ClearCurrentData(_savedCurrentScope.ContextKey, false);
}
}
else
{
// No parent TransactionScope present
// Clear any CallContext data
CallContextCurrentData.ClearCurrentData(null, false);
if (_scopeThread != Thread.CurrentThread)
{
// Clear TLS data so that transaction doesn't leak from current thread.
shouldRestoreContextData = false;
ContextData.TLSCurrentData = null;
}
else
{
// Restore the current data to TLS.
ContextData.TLSCurrentData = _threadContextData;
}
}
// prevent restoring the context in an unexpected thread due to thread switch during TransactionScope's Dispose
if (shouldRestoreContextData)
{
_threadContextData.CurrentScope = _savedCurrentScope;
RestoreCurrent();
}
}
// SetCurrent
//
// Place the given value in current by whatever means necessary for interop mode.
private void SetCurrent(Transaction newCurrent)
{
// Keep a dependent clone of current if we don't have one and we are not committable
if (_dependentTransaction == null && _committableTransaction == null)
{
if (newCurrent != null)
{
_dependentTransaction = newCurrent.DependentClone(DependentCloneOption.RollbackIfNotComplete);
}
}
switch (_interopOption)
{
case EnterpriseServicesInteropOption.None:
_threadContextData.CurrentTransaction = newCurrent;
break;
case EnterpriseServicesInteropOption.Automatic:
EnterpriseServices.VerifyEnterpriseServicesOk();
if (EnterpriseServices.UseServiceDomainForCurrent())
{
EnterpriseServices.PushServiceDomain(newCurrent);
}
else
{
_threadContextData.CurrentTransaction = newCurrent;
}
break;
case EnterpriseServicesInteropOption.Full:
EnterpriseServices.VerifyEnterpriseServicesOk();
EnterpriseServices.PushServiceDomain(newCurrent);
break;
}
}
private void SaveTLSContextData()
{
if (_savedTLSContextData == null)
{
_savedTLSContextData = new ContextData(false);
}
_savedTLSContextData.CurrentScope = ContextData.TLSCurrentData.CurrentScope;
_savedTLSContextData.CurrentTransaction = ContextData.TLSCurrentData.CurrentTransaction;
_savedTLSContextData.DefaultComContextState = ContextData.TLSCurrentData.DefaultComContextState;
_savedTLSContextData.WeakDefaultComContext = ContextData.TLSCurrentData.WeakDefaultComContext;
}
private void RestoreSavedTLSContextData()
{
if (_savedTLSContextData != null)
{
ContextData.TLSCurrentData.CurrentScope = _savedTLSContextData.CurrentScope;
ContextData.TLSCurrentData.CurrentTransaction = _savedTLSContextData.CurrentTransaction;
ContextData.TLSCurrentData.DefaultComContextState = _savedTLSContextData.DefaultComContextState;
ContextData.TLSCurrentData.WeakDefaultComContext = _savedTLSContextData.WeakDefaultComContext;
}
}
// RestoreCurrent
//
// Restore current to it's previous value depending on how it was changed for this scope.
private void RestoreCurrent()
{
if (EnterpriseServices.CreatedServiceDomain)
{
EnterpriseServices.LeaveServiceDomain();
}
// Only restore the value that was actually in the context.
_threadContextData.CurrentTransaction = _contextTransaction;
}
// ValidateInteropOption
//
// Validate a given interop Option
private void ValidateInteropOption(EnterpriseServicesInteropOption interopOption)
{
if (interopOption < EnterpriseServicesInteropOption.None || interopOption > EnterpriseServicesInteropOption.Full)
{
throw new ArgumentOutOfRangeException(nameof(interopOption));
}
}
// ValidateScopeTimeout
//
// Scope timeouts are not governed by MaxTimeout and therefore need a special validate function
private void ValidateScopeTimeout(string paramName, TimeSpan scopeTimeout)
{
if (scopeTimeout < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(paramName);
}
}
private void ValidateAndSetAsyncFlowOption(TransactionScopeAsyncFlowOption asyncFlowOption)
{
if (asyncFlowOption < TransactionScopeAsyncFlowOption.Suppress || asyncFlowOption > TransactionScopeAsyncFlowOption.Enabled)
{
throw new ArgumentOutOfRangeException(nameof(asyncFlowOption));
}
if (asyncFlowOption == TransactionScopeAsyncFlowOption.Enabled)
{
AsyncFlowEnabled = true;
}
}
// The validate method assumes that the existing parent ambient transaction scope is already looked up.
private void ValidateAsyncFlowOptionAndESInteropOption()
{
if (AsyncFlowEnabled)
{
EnterpriseServicesInteropOption currentInteropOption = _interopOption;
if (!_interopModeSpecified)
{
// Transaction.InteropMode will take the interop mode on
// for the scope in currentScope into account.
currentInteropOption = Transaction.InteropMode(_savedCurrentScope);
}
if (currentInteropOption != EnterpriseServicesInteropOption.None)
{
throw new NotSupportedException(SR.AsyncFlowAndESInteropNotSupported);
}
}
}
// Denotes the action to take when the scope is disposed.
private bool _complete;
internal bool ScopeComplete
{
get
{
return _complete;
}
}
// Storage location for the previous current transaction.
private Transaction _savedCurrent;
// To ensure that we don't restore a value for current that was
// returned to us by an external entity keep the value that was actually
// in TLS when the scope was created.
private Transaction _contextTransaction;
// Storage for the value to restore to current
private TransactionScope _savedCurrentScope;
// Store a reference to the context data object for this scope.
private ContextData _threadContextData;
private ContextData _savedTLSContextData;
// Store a reference to the value that this scope expects for current
private Transaction _expectedCurrent;
// Store a reference to the committable form of this transaction if
// the scope made one.
private CommittableTransaction _committableTransaction;
// Store a reference to the scopes transaction guard.
private DependentTransaction _dependentTransaction;
// Note when the scope is disposed.
private bool _disposed;
// BUGBUG: A shared timer should be used.
// Individual timer for this scope.
private Timer _scopeTimer;
// Store a reference to the thread on which the scope was created so that we can
// check to make sure that the dispose pattern for scope is being used correctly.
private Thread _scopeThread;
// Store the interop mode for this transaction scope.
private bool _interopModeSpecified = false;
private EnterpriseServicesInteropOption _interopOption;
internal EnterpriseServicesInteropOption InteropMode
{
get
{
return _interopOption;
}
}
internal ContextKey ContextKey
{
get;
private set;
}
internal bool AsyncFlowEnabled
{
get;
private set;
}
}
}
| |
namespace OmniXaml.Typing
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Glass.Core;
using TypeConversion;
public class XamlType
{
public XamlType(Type type, ITypeRepository typeRepository, ITypeFactory typeTypeFactory, ITypeFeatureProvider featureProvider)
{
Guard.ThrowIfNull(type, nameof(type));
Guard.ThrowIfNull(typeRepository, nameof(typeRepository));
Guard.ThrowIfNull(featureProvider, nameof(featureProvider));
TypeRepository = typeRepository;
TypeFactory = typeTypeFactory;
FeatureProvider = featureProvider;
UnderlyingType = type;
Name = type.Name;
}
private XamlType(Type type)
{
UnderlyingType = type;
}
public Type UnderlyingType { get; }
public string Name { get; }
public bool IsCollection
{
get
{
var typeInfo = UnderlyingType.GetTypeInfo();
var isCollection = typeof(ICollection).GetTypeInfo().IsAssignableFrom(typeInfo);
var isEnumerable = typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(typeInfo);
return UnderlyingType != typeof(string) && (isCollection || isEnumerable);
}
}
public bool IsContainer => IsCollection || IsDictionary;
public bool IsDictionary
{
get
{
var typeInfo = UnderlyingType.GetTypeInfo();
var isDictionary = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeInfo);
return isDictionary;
}
}
public bool NeedsConstructionParameters => UnderlyingType.GetTypeInfo().DeclaredConstructors.All(info => info.GetParameters().Any());
// ReSharper disable once MemberCanBeProtected.Global
public ITypeRepository TypeRepository { get; }
// ReSharper disable once MemberCanBeProtected.Global
public ITypeFactory TypeFactory { get; }
// ReSharper disable once MemberCanBeProtected.Global
public ITypeFeatureProvider FeatureProvider { get; }
public Member ContentProperty
{
get
{
var propertyName = FeatureProvider.GetContentPropertyName(UnderlyingType);
if (propertyName == null)
{
return null;
}
var member = TypeRepository.GetByType(UnderlyingType).GetMember(propertyName);
return member;
}
}
public ITypeConverter TypeConverter => FeatureProvider.GetTypeConverter(UnderlyingType);
protected bool Equals(XamlType other)
{
return UnderlyingType == other.UnderlyingType;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return Equals((XamlType)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((UnderlyingType?.GetHashCode() ?? 0) * 397);
}
}
public Member GetMember(string name)
{
return LookupMember(name);
}
protected virtual Member LookupMember(string name)
{
return new Member(name, this, TypeRepository, FeatureProvider);
}
public AttachableMember GetAttachableMember(string name)
{
return LookupAttachableMember(name);
}
public override string ToString()
{
return "XamlType: " + Name;
}
public object CreateInstance(object[] parameters)
{
return TypeFactory.Create(UnderlyingType, parameters);
}
public static XamlType Create(Type underlyingType,
ITypeRepository typeRepository,
ITypeFactory typeFactory,
ITypeFeatureProvider featureProvider)
{
Guard.ThrowIfNull(underlyingType, nameof(typeRepository));
return new XamlType(underlyingType, typeRepository, typeFactory, featureProvider);
}
public static XamlType CreateForBuiltInType(Type type)
{
Guard.ThrowIfNull(type, nameof(type));
return new XamlType(type);
}
protected virtual AttachableMember LookupAttachableMember(string name)
{
var getter = UnderlyingType.GetTypeInfo().GetDeclaredMethod("Get" + name);
var setter = UnderlyingType.GetTypeInfo().GetDeclaredMethod("Set" + name);
return TypeRepository.GetAttachableMember(name, getter, setter);
}
public IEnumerable<MemberBase> GetAllMembers()
{
var properties = UnderlyingType.GetRuntimeProperties().Where(IsValidMember).ToList();
return properties.Select(props => GetMember(props.Name));
}
private static bool IsValidMember(PropertyInfo info)
{
var isIndexer = info.GetIndexParameters().Any();
var hasValidSetter = info.SetMethod != null && info.SetMethod.IsPublic;
var hasValidGetter = info.GetMethod != null && info.GetMethod.IsPublic;
return hasValidGetter && hasValidSetter && !isIndexer;
}
public virtual INameScope GetNamescope(object instance)
{
return instance as INameScope;
}
public Member RuntimeNamePropertyMember
{
get
{
if (TypeRepository == null)
{
return null;
}
var metadata = FeatureProvider.GetMetadata(UnderlyingType);
var runtimeNameProperty = metadata?.RuntimePropertyName;
if (runtimeNameProperty == null)
{
return null;
}
var propInfo = UnderlyingType.GetRuntimeProperty(runtimeNameProperty);
if (propInfo == null)
{
return null;
}
return GetMember(runtimeNameProperty);
}
}
public virtual void BeforeInstanceSetup(object instance)
{
}
public virtual void AfterInstanceSetup(object instance)
{
}
public virtual void AfterAssociationToParent(object instance)
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
namespace Microsoft.AspNetCore.Mvc.ModelBinding
{
/// <summary>
/// A metadata object representing a source of data for model binding.
/// </summary>
[DebuggerDisplay("Source: {DisplayName}")]
public class BindingSource : IEquatable<BindingSource?>
{
/// <summary>
/// A <see cref="BindingSource"/> for the request body.
/// </summary>
public static readonly BindingSource Body = new BindingSource(
"Body",
Resources.BindingSource_Body,
isGreedy: true,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for a custom model binder (unknown data source).
/// </summary>
public static readonly BindingSource Custom = new BindingSource(
"Custom",
Resources.BindingSource_Custom,
isGreedy: true,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for the request form-data.
/// </summary>
public static readonly BindingSource Form = new BindingSource(
"Form",
Resources.BindingSource_Form,
isGreedy: false,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for the request headers.
/// </summary>
public static readonly BindingSource Header = new BindingSource(
"Header",
Resources.BindingSource_Header,
isGreedy: true,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for model binding. Includes form-data, query-string
/// and route data from the request.
/// </summary>
public static readonly BindingSource ModelBinding = new BindingSource(
"ModelBinding",
Resources.BindingSource_ModelBinding,
isGreedy: false,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for the request url path.
/// </summary>
public static readonly BindingSource Path = new BindingSource(
"Path",
Resources.BindingSource_Path,
isGreedy: false,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for the request query-string.
/// </summary>
public static readonly BindingSource Query = new BindingSource(
"Query",
Resources.BindingSource_Query,
isGreedy: false,
isFromRequest: true);
/// <summary>
/// A <see cref="BindingSource"/> for request services.
/// </summary>
public static readonly BindingSource Services = new BindingSource(
"Services",
Resources.BindingSource_Services,
isGreedy: true,
isFromRequest: false);
/// <summary>
/// A <see cref="BindingSource"/> for special parameter types that are not user input.
/// </summary>
public static readonly BindingSource Special = new BindingSource(
"Special",
Resources.BindingSource_Special,
isGreedy: true,
isFromRequest: false);
/// <summary>
/// A <see cref="BindingSource"/> for <see cref="IFormFile"/>, <see cref="IFormCollection"/>, and <see cref="IFormFileCollection"/>.
/// </summary>
public static readonly BindingSource FormFile = new BindingSource(
"FormFile",
Resources.BindingSource_FormFile,
isGreedy: true,
isFromRequest: true);
/// <summary>
/// Creates a new <see cref="BindingSource"/>.
/// </summary>
/// <param name="id">The id, a unique identifier.</param>
/// <param name="displayName">The display name.</param>
/// <param name="isGreedy">A value indicating whether or not the source is greedy.</param>
/// <param name="isFromRequest">
/// A value indicating whether or not the data comes from the HTTP request.
/// </param>
public BindingSource(string id, string displayName, bool isGreedy, bool isFromRequest)
{
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
Id = id;
DisplayName = displayName;
IsGreedy = isGreedy;
IsFromRequest = isFromRequest;
}
/// <summary>
/// Gets the display name for the source.
/// </summary>
public string DisplayName { get; }
/// <summary>
/// Gets the unique identifier for the source. Sources are compared based on their Id.
/// </summary>
public string Id { get; }
/// <summary>
/// Gets a value indicating whether or not a source is greedy. A greedy source will bind a model in
/// a single operation, and will not decompose the model into sub-properties.
/// </summary>
/// <remarks>
/// <para>
/// For sources based on a <see cref="IValueProvider"/>, setting <see cref="IsGreedy"/> to <c>false</c>
/// will most closely describe the behavior. This value is used inside the default model binders to
/// determine whether or not to attempt to bind properties of a model.
/// </para>
/// <para>
/// Set <see cref="IsGreedy"/> to <c>true</c> for most custom <see cref="IModelBinder"/> implementations.
/// </para>
/// <para>
/// If a source represents an <see cref="IModelBinder"/> which will recursively traverse a model's properties
/// and bind them individually using <see cref="IValueProvider"/>, then set <see cref="IsGreedy"/> to
/// <c>true</c>.
/// </para>
/// </remarks>
public bool IsGreedy { get; }
/// <summary>
/// Gets a value indicating whether or not the binding source uses input from the current HTTP request.
/// </summary>
/// <remarks>
/// Some sources (like <see cref="BindingSource.Services"/>) are based on application state and not user
/// input. These are excluded by default from ApiExplorer diagnostics.
/// </remarks>
public bool IsFromRequest { get; }
/// <summary>
/// Gets a value indicating whether or not the <see cref="BindingSource"/> can accept
/// data from <paramref name="bindingSource"/>.
/// </summary>
/// <param name="bindingSource">The <see cref="BindingSource"/> to consider as input.</param>
/// <returns><c>True</c> if the source is compatible, otherwise <c>false</c>.</returns>
/// <remarks>
/// When using this method, it is expected that the left-hand-side is metadata specified
/// on a property or parameter for model binding, and the right hand side is a source of
/// data used by a model binder or value provider.
///
/// This distinction is important as the left-hand-side may be a composite, but the right
/// may not.
/// </remarks>
public virtual bool CanAcceptDataFrom(BindingSource bindingSource)
{
if (bindingSource == null)
{
throw new ArgumentNullException(nameof(bindingSource));
}
if (bindingSource is CompositeBindingSource)
{
var message = Resources.FormatBindingSource_CannotBeComposite(
bindingSource.DisplayName,
nameof(CanAcceptDataFrom));
throw new ArgumentException(message, nameof(bindingSource));
}
if (this == bindingSource)
{
return true;
}
if (this == ModelBinding)
{
return bindingSource == Form || bindingSource == Path || bindingSource == Query;
}
return false;
}
/// <inheritdoc />
public bool Equals(BindingSource? other)
{
return string.Equals(other?.Id, Id, StringComparison.Ordinal);
}
/// <inheritdoc />
public override bool Equals(object? obj)
{
return Equals(obj as BindingSource);
}
/// <inheritdoc />
public override int GetHashCode()
{
return Id.GetHashCode();
}
/// <inheritdoc />
public static bool operator ==(BindingSource? s1, BindingSource? s2)
{
if (s1 is null)
{
return s2 is null;
}
return s1.Equals(s2);
}
/// <inheritdoc />
public static bool operator !=(BindingSource? s1, BindingSource? s2)
{
return !(s1 == s2);
}
}
}
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for EnvironmentsOperations.
/// </summary>
public static partial class EnvironmentsOperationsExtensions
{
/// <summary>
/// List environments in a given user profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<DtlEnvironment> List(this IEnvironmentsOperations operations, string labName, string userName, ODataQuery<DtlEnvironment> odataQuery = default(ODataQuery<DtlEnvironment>))
{
return Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).ListAsync(labName, userName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List environments in a given user profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DtlEnvironment>> ListAsync(this IEnvironmentsOperations operations, string labName, string userName, ODataQuery<DtlEnvironment> odataQuery = default(ODataQuery<DtlEnvironment>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(labName, userName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get environment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($select=deploymentProperties)'
/// </param>
public static DtlEnvironment Get(this IEnvironmentsOperations operations, string labName, string userName, string name, string expand = default(string))
{
return Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).GetAsync(labName, userName, name, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get environment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='expand'>
/// Specify the $expand query. Example:
/// 'properties($select=deploymentProperties)'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DtlEnvironment> GetAsync(this IEnvironmentsOperations operations, string labName, string userName, string name, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(labName, userName, name, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing environment. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='dtlEnvironment'>
/// An environment, which is essentially an ARM template deployment.
/// </param>
public static DtlEnvironment CreateOrUpdate(this IEnvironmentsOperations operations, string labName, string userName, string name, DtlEnvironment dtlEnvironment)
{
return Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).CreateOrUpdateAsync(labName, userName, name, dtlEnvironment), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing environment. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='dtlEnvironment'>
/// An environment, which is essentially an ARM template deployment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DtlEnvironment> CreateOrUpdateAsync(this IEnvironmentsOperations operations, string labName, string userName, string name, DtlEnvironment dtlEnvironment, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(labName, userName, name, dtlEnvironment, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create or replace an existing environment. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='dtlEnvironment'>
/// An environment, which is essentially an ARM template deployment.
/// </param>
public static DtlEnvironment BeginCreateOrUpdate(this IEnvironmentsOperations operations, string labName, string userName, string name, DtlEnvironment dtlEnvironment)
{
return Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).BeginCreateOrUpdateAsync(labName, userName, name, dtlEnvironment), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or replace an existing environment. This operation can take a while
/// to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='dtlEnvironment'>
/// An environment, which is essentially an ARM template deployment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<DtlEnvironment> BeginCreateOrUpdateAsync(this IEnvironmentsOperations operations, string labName, string userName, string name, DtlEnvironment dtlEnvironment, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(labName, userName, name, dtlEnvironment, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete environment. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
public static void Delete(this IEnvironmentsOperations operations, string labName, string userName, string name)
{
Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).DeleteAsync(labName, userName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete environment. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IEnvironmentsOperations operations, string labName, string userName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(labName, userName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete environment. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
public static void BeginDelete(this IEnvironmentsOperations operations, string labName, string userName, string name)
{
Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).BeginDeleteAsync(labName, userName, name), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete environment. This operation can take a while to complete.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='userName'>
/// The name of the user profile.
/// </param>
/// <param name='name'>
/// The name of the environment.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IEnvironmentsOperations operations, string labName, string userName, string name, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(labName, userName, name, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// List environments in a given user profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<DtlEnvironment> ListNext(this IEnvironmentsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IEnvironmentsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List environments in a given user profile.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<DtlEnvironment>> ListNextAsync(this IEnvironmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
public class ParamsObjectsCreation : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+ParamsObjectsCreation
// Test Case
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding Comment") { Param = "XComment", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order, without decl") { Param = "Mix2", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding PI") { Param = "XPI", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding element") { Param = "XElement", Priority = 0 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - adding string/whitespace") { Param = "Whitespace", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParams) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order") { Param = "Mix1", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order, cloned") { Param = "Mix1", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding string/whitespace") { Param = "Whitespace", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding Comment cloned") { Param = "XComment", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding element cloned") { Param = "XElement", Priority = 0 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - combination off allowed types in correct order, without decl; cloned") { Param = "Mix2", Priority = 1 } });
AddChild(new TestVariation(XDocumentAddParamsCloning) { Attribute = new VariationAttribute("XDocument - adding PI cloned") { Param = "XPI", Priority = 1 } });
AddChild(new TestVariation(CreateXDocumentMixNoArrayNotConnected) { Attribute = new VariationAttribute("XDocument - params no array") { Priority = 0 } });
AddChild(new TestVariation(CreateXDocumentMixNoArrayConnected) { Attribute = new VariationAttribute("XDocument - params no array - connected") { Priority = 0 } });
AddChild(new TestVariation(XDocumentAddParamsInvalid) { Attribute = new VariationAttribute("XDocument - Invalid case - XDocument node") { Param = "Document", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParamsInvalid) { Attribute = new VariationAttribute("XDocument - Invalid case - Mix with attribute") { Param = "MixAttr", Priority = 2 } });
AddChild(new TestVariation(XDocumentAddParamsInvalid) { Attribute = new VariationAttribute("XDocument - Invalid case - attribute node") { Param = "Attribute", Priority = 1 } });
AddChild(new TestVariation(XDocumentInvalidCloneSanity) { Attribute = new VariationAttribute("XDocument - Invalid case with clone - double root - sanity") { Priority = 1 } });
AddChild(new TestVariation(XDocumentTheSameReferenceSanity) { Attribute = new VariationAttribute("XDocument - the same node instance, connected - sanity") { Param = true, Priority = 1 } });
AddChild(new TestVariation(XDocumentTheSameReferenceSanity) { Attribute = new VariationAttribute("XDocument - the same node instance - sanity") { Param = false, Priority = 1 } });
AddChild(new TestVariation(XDocumentIEnumerable) { Attribute = new VariationAttribute("XDocument - IEnumerable - connected") { Param = true, Priority = 0 } });
AddChild(new TestVariation(XDocumentIEnumerable) { Attribute = new VariationAttribute("XDocument - IEnumerable - not connected") { Param = false, Priority = 0 } });
AddChild(new TestVariation(XDocument2xIEnumerable) { Attribute = new VariationAttribute("XDocument - 2 x IEnumerable - sanity") { Priority = 0 } });
}
// XDocument
// - from node without parent, from nodes with parent
// - allowed types
// - attributes
// - Document
// - doubled decl, root elem, doctype
// - the same valid object instance multiple times
// - array/IEnumerable of allowed types
// - array/IEnumerable including not allowed types
//[Variation(Priority = 0, Desc = "XDocument - adding element", Param = "XElement")]
//[Variation(Priority = 1, Desc = "XDocument - adding PI", Param = "XPI")]
//[Variation(Priority = 1, Desc = "XDocument - adding XmlDecl", Param = "XmlDecl")]
//[Variation (Priority=1, Desc="XDocument - adding dot type")]
//[Variation(Priority = 1, Desc = "XDocument - adding Comment", Param = "XComment")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order", Param = "Mix1")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order, without decl", Param = "Mix2")]
//[Variation(Priority = 2, Desc = "XDocument - adding string/whitespace", Param = "Whitespace")]
public void CreateXDocumentMixNoArrayConnected()
{
var doc1 = new XDocument(new XProcessingInstruction("PI", "data"), new XComment("comm1"), new XElement("root", new XAttribute("id", "a1")), new XComment("comm2"));
var nodes = new XNode[4];
XNode nn = doc1.FirstNode;
for (int i = 0; i < nodes.Length; i++)
{
nodes[i] = nn;
nn = nn.NextNode;
}
var doc = new XDocument(nodes[0], nodes[1], nodes[2], nodes[3]);
int nodeCounter = 0;
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
TestLog.Compare(n != nodes[nodeCounter], "identity");
TestLog.Compare(XNode.DeepEquals(n, nodes[nodeCounter]), "Equals");
TestLog.Compare(nodes[nodeCounter].Document == doc1, "orig Document");
TestLog.Compare(n.Document == doc, "new Document");
nodeCounter++;
}
TestLog.Compare(nodeCounter, nodes.Length, "All nodes added");
}
public void CreateXDocumentMixNoArrayNotConnected()
{
XNode[] nodes = { new XProcessingInstruction("PI", "data"), new XComment("comm1"), new XElement("root", new XAttribute("id", "a1")), new XComment("comm2") };
var doc = new XDocument(nodes[0], nodes[1], nodes[2], nodes[3]);
int nodeCounter = 0;
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
TestLog.Compare(n == nodes[nodeCounter], "identity");
TestLog.Compare(XNode.DeepEquals(n, nodes[nodeCounter]), "Equals");
TestLog.Compare(n.Document == doc, "Document");
nodeCounter++;
}
TestLog.Compare(nodeCounter, nodes.Length, "All nodes added");
}
public void XDocument2xIEnumerable()
{
XDocument doc1 = null;
var paras = new object[2];
doc1 = new XDocument(new XProcessingInstruction("PI", "data"), new XElement("root"));
var list1 = new List<XNode>();
for (XNode n = doc1.FirstNode; n != null; n = n.NextNode)
{
list1.Add(n);
}
paras[0] = list1;
var list2 = new List<XNode>();
list2.Add(new XProcessingInstruction("PI2", "data"));
list2.Add(new XComment("como"));
paras[1] = list2;
var doc = new XDocument(paras);
IEnumerator ien = (paras[0] as IEnumerable).GetEnumerator();
bool enumerablesSwitched = false;
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
if (!ien.MoveNext())
{
ien = (paras[1] as IEnumerable).GetEnumerator();
ien.MoveNext();
enumerablesSwitched = true;
}
var orig = ien.Current as XNode;
TestLog.Compare(XNode.DeepEquals(n, orig), "n.Equals(orig)");
if (!enumerablesSwitched)
{
TestLog.Compare(orig != n, "orig != n");
TestLog.Compare(orig.Document == doc1, "orig Document connected");
TestLog.Compare(n.Document == doc, "node Document connected");
}
else
{
TestLog.Compare(orig == n, "orig == n");
TestLog.Compare(orig.Document == doc, "orig Document NOT connected");
TestLog.Compare(n.Document == doc, "node Document NOT connected");
}
}
}
public void XDocumentAddParams()
{
object[] parameters = null;
var paramType = Variation.Param as string;
switch (paramType)
{
case "XElement":
parameters = new object[] { new XElement("root") };
break;
case "XPI":
parameters = new object[] { new XProcessingInstruction("Click", "data") };
break;
case "XComment":
parameters = new object[] { new XComment("comment") };
break;
case "Whitespace":
parameters = new object[] { new XText(" ") };
break;
case "Mix1":
parameters = new object[] { new XComment("comment"), new XProcessingInstruction("Click", "data"), new XElement("root"), new XProcessingInstruction("Click2", "data2") };
break;
case "Mix2":
parameters = new object[] { new XComment("comment"), new XProcessingInstruction("Click", "data"), new XElement("root"), new XProcessingInstruction("Click2", "data2") };
break;
default:
TestLog.Compare(false, "Test case: Wrong param");
break;
}
var doc = new XDocument(parameters);
TestLog.Compare(doc != null, "doc!=null");
TestLog.Compare(doc.Document == doc, "doc.Document property");
TestLog.Compare(doc.Parent == null, "doc.Parent property");
int counter = 0;
for (XNode node = doc.FirstNode; node.NextNode != null; node = node.NextNode)
{
TestLog.Compare(node != null, "node != null");
TestLog.Compare(node == parameters[counter], "Node identity");
TestLog.Compare(XNode.DeepEquals(node, parameters[counter] as XNode), "node equals param");
TestLog.Compare(node.Document, doc, "Document property");
counter++;
}
}
//[Variation(Priority = 0, Desc = "XDocument - adding element cloned", Param = "XElement")]
//[Variation(Priority = 1, Desc = "XDocument - adding PI cloned", Param = "XPI")]
//[Variation(Priority = 1, Desc = "XDocument - adding XmlDecl cloned", Param = "XmlDecl")]
//[Variation (Priority=1, Desc="XDocument - adding dot type")]
//[Variation(Priority = 1, Desc = "XDocument - adding Comment cloned", Param = "XComment")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order, cloned", Param = "Mix1")]
//[Variation(Priority = 1, Desc = "XDocument - combination off allowed types in correct order, without decl; cloned", Param = "Mix2")]
//[Variation(Priority = 2, Desc = "XDocument - adding string/whitespace", Param = "Whitespace")]
public void XDocumentAddParamsCloning()
{
object[] paras = null;
var paramType = Variation.Param as string;
var doc1 = new XDocument();
switch (paramType)
{
case "XElement":
var xe = new XElement("root");
doc1.Add(xe);
paras = new object[] { xe };
break;
case "XPI":
var pi = new XProcessingInstruction("Click", "data");
doc1.Add(pi);
paras = new object[] { pi };
break;
case "XComment":
var comm = new XComment("comment");
doc1.Add(comm);
paras = new object[] { comm };
break;
case "Whitespace":
var txt = new XText(" ");
doc1.Add(txt);
paras = new object[] { txt };
break;
case "Mix1":
{
var a2 = new XComment("comment");
doc1.Add(a2);
var a3 = new XProcessingInstruction("Click", "data");
doc1.Add(a3);
var a4 = new XElement("root");
doc1.Add(a4);
var a5 = new XProcessingInstruction("Click2", "data2");
doc1.Add(a5);
paras = new object[] { a2, a3, a4, a5 };
}
break;
case "Mix2":
{
var a2 = new XComment("comment");
doc1.Add(a2);
var a3 = new XProcessingInstruction("Click", "data");
doc1.Add(a3);
var a4 = new XElement("root");
doc1.Add(a4);
var a5 = new XProcessingInstruction("Click2", "data2");
doc1.Add(a5);
paras = new object[] { a2, a3, a4, a5 };
}
break;
default:
TestLog.Compare(false, "Test case: Wrong param");
break;
}
var doc = new XDocument(paras);
TestLog.Compare(doc != null, "doc!=null");
TestLog.Compare(doc.Document == doc, "doc.Document property");
int counter = 0;
for (XNode node = doc.FirstNode; node.NextNode != null; node = node.NextNode)
{
TestLog.Compare(node != null, "node != null");
var orig = paras[counter] as XNode;
TestLog.Compare(node != orig, "Not the same instance, cloned");
TestLog.Compare(orig.Document, doc1, "Orig Document");
TestLog.Compare(XNode.DeepEquals(node, orig), "node equals param");
TestLog.Compare(node.Document, doc, "Document property");
counter++;
}
}
//[Variation(Priority = 0, Desc = "XDocument - params no array")]
//[Variation(Priority = 1, Desc = "XDocument - Invalid case - attribute node", Param = "Attribute")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - XDocument node", Param = "Document")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - Mix with attribute", Param = "MixAttr")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - Double root element", Param = "DoubleRoot")]
//[Variation(Priority = 2, Desc = "XDocument - Invalid case - Double XmlDecl", Param = "DoubleDecl")]
//[Variation(Priority = 1, Desc = "XDocument - Invalid case - Invalid order ... Decl is not the first", Param = "InvalIdOrder")]
public void XDocumentAddParamsInvalid()
{
object[] paras = null;
var paramType = Variation.Param as string;
switch (paramType)
{
case "Attribute":
paras = new object[] { new XAttribute("mu", "hu") };
break;
case "Document":
paras = new object[] { new XDocument(), new XProcessingInstruction("Click", "data") };
break;
case "MixAttr":
paras = new object[] { new XElement("aloha"), new XProcessingInstruction("PI", "data"), new XAttribute("id", "a") };
break;
case "DoubleRoot":
paras = new object[] { new XElement("first"), new XElement("Second") };
break;
case "DoubleDocType":
paras = new object[] { new XDocumentType("root", "", "", ""), new XDocumentType("root", "", "", "") };
break;
case "InvalidOrder":
paras = new object[] { new XElement("first"), new XDocumentType("root", "", "", "") };
break;
default:
TestLog.Compare(false, "Test case: Wrong param");
break;
}
XDocument doc = null;
try
{
doc = new XDocument(paras);
TestLog.Compare(false, "Should throw exception");
}
catch (ArgumentException)
{
TestLog.Compare(doc == null, "Should be null if exception appears");
return;
}
throw new TestException(TestResult.Failed, "");
}
public void XDocumentIEnumerable()
{
var connected = (bool)Variation.Param;
XDocument doc1 = null;
object[] paras = null;
if (connected)
{
doc1 = new XDocument(
new XProcessingInstruction("PI", "data"), new XElement("root"));
var list = new List<XNode>();
for (XNode n = doc1.FirstNode; n != null; n = n.NextNode)
{
list.Add(n);
}
paras = new object[] { list };
}
else
{
var list = new List<XNode>();
list.Add(new XProcessingInstruction("PI", "data"));
list.Add(new XElement("root"));
paras = new object[] { list };
}
var doc = new XDocument(paras);
IEnumerator ien = (paras[0] as IEnumerable).GetEnumerator();
for (XNode n = doc.FirstNode; n != null; n = n.NextNode)
{
ien.MoveNext();
var orig = ien.Current as XNode;
TestLog.Compare(XNode.DeepEquals(n, orig), "XNode.DeepEquals(n,orig)");
if (connected)
{
TestLog.Compare(orig != n, "orig != n");
TestLog.Compare(orig.Document == doc1, "orig Document connected");
TestLog.Compare(n.Document == doc, "node Document connected");
}
else
{
TestLog.Compare(orig == n, "orig == n");
TestLog.Compare(orig.Document == doc, "orig Document NOT connected");
TestLog.Compare(n.Document == doc, "node Document NOT connected");
}
}
TestLog.Compare(!ien.MoveNext(), "enumerator should be exhausted");
}
//[Variation(Priority = 1, Desc = "XDocument - Invalid case with clone - double root - sanity")]
public void XDocumentInvalidCloneSanity()
{
var doc1 = new XDocument(new XElement("root", new XElement("A"), new XElement("B")));
string origXml = doc1.ToString(SaveOptions.DisableFormatting);
var paras = new object[] { doc1.Root.Element("A"), doc1.Root.Element("B") };
XDocument doc = null;
try
{
doc = new XDocument(paras);
TestLog.Compare(false, "should throw");
}
catch (Exception)
{
foreach (object o in paras)
{
var e = o as XElement;
TestLog.Compare(e.Parent, doc1.Root, "Orig Parent");
TestLog.Compare(e.Document, doc1, "Orig Document");
}
TestLog.Compare(doc1.ToString(SaveOptions.DisableFormatting), origXml, "Orig XML");
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation(Priority = 1, Desc = "XDocument - the same node instance, connected - sanity", Param = true)]
//[Variation(Priority = 1, Desc = "XDocument - the same node instance - sanity", Param = false)]
public void XDocumentTheSameReferenceSanity()
{
object[] paras = null;
var connected = (bool)Variation.Param;
XDocument doc1 = null;
if (connected)
{
doc1 = new XDocument(new XElement("root", new XElement("A"), new XProcessingInstruction("PI", "data")));
paras = new object[] { doc1.Root.LastNode, doc1.Root.LastNode, doc1.Root.Element("A") };
}
else
{
var e = new XElement("A");
var pi = new XProcessingInstruction("PI", "data");
paras = new object[] { pi, pi, e };
}
var doc = new XDocument(paras);
XNode firstPI = doc.FirstNode;
XNode secondPI = firstPI.NextNode;
XNode rootElem = secondPI.NextNode;
TestLog.Compare(firstPI != null, "firstPI != null");
TestLog.Compare(firstPI.NodeType, XmlNodeType.ProcessingInstruction, "firstPI nodetype");
TestLog.Compare(firstPI is XProcessingInstruction, "firstPI is XPI");
TestLog.Compare(secondPI != null, "secondPI != null");
TestLog.Compare(secondPI.NodeType, XmlNodeType.ProcessingInstruction, "secondPI nodetype");
TestLog.Compare(secondPI is XProcessingInstruction, "secondPI is XPI");
TestLog.Compare(rootElem != null, "rootElem != null");
TestLog.Compare(rootElem.NodeType, XmlNodeType.Element, "rootElem nodetype");
TestLog.Compare(rootElem is XElement, "rootElem is XElement");
TestLog.Compare(rootElem.NextNode == null, "rootElem NextNode");
TestLog.Compare(firstPI != secondPI, "firstPI != secondPI");
TestLog.Compare(XNode.DeepEquals(firstPI, secondPI), "XNode.DeepEquals(firstPI,secondPI)");
foreach (object o in paras)
{
var e = o as XNode;
if (connected)
{
TestLog.Compare(e.Parent, doc1.Root, "Orig Parent");
TestLog.Compare(e.Document, doc1, "Orig Document");
}
else
{
TestLog.Compare(e.Parent == null, "Orig Parent not connected");
TestLog.Compare(e.Document, doc, "Orig Document not connected");
}
}
}
#endregion
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime
{
public interface ICorePerformanceMetrics
{
float CpuUsage { get; }
long AvailablePhysicalMemory { get; }
long MemoryUsage { get; }
long TotalPhysicalMemory { get; }
int SendQueueLength { get; }
int ReceiveQueueLength { get; }
long SentMessages { get; }
long ReceivedMessages { get; }
}
public interface ISiloPerformanceMetrics : ICorePerformanceMetrics
{
long RequestQueueLength { get; }
int ActivationCount { get; }
int RecentlyUsedActivationCount { get; }
long ClientCount { get; }
// More TBD
bool IsOverloaded { get; }
void LatchIsOverload(bool overloaded);
void UnlatchIsOverloaded();
void LatchCpuUsage(float value);
void UnlatchCpuUsage();
}
public interface IClientPerformanceMetrics : ICorePerformanceMetrics
{
long ConnectedGatewayCount { get; }
}
public interface ISiloMetricsDataPublisher
{
Task Init(string deploymentId, string storageConnectionString, SiloAddress siloAddress, string siloName, IPEndPoint gateway, string hostName);
Task ReportMetrics(ISiloPerformanceMetrics metricsData);
}
public interface IConfigurableSiloMetricsDataPublisher : ISiloMetricsDataPublisher
{
void AddConfiguration(string deploymentId, bool isSilo, string siloName, SiloAddress address, System.Net.IPEndPoint gateway, string hostName);
}
public interface IClientMetricsDataPublisher
{
Task Init(ClientConfiguration config, IPAddress address, string clientId);
Task ReportMetrics(IClientPerformanceMetrics metricsData);
}
public interface IConfigurableClientMetricsDataPublisher : IClientMetricsDataPublisher
{
void AddConfiguration(string deploymentId, string hostName, string clientId, System.Net.IPAddress address);
}
public interface IStatisticsPublisher
{
Task ReportStats(List<ICounter> statsCounters);
Task Init(bool isSilo, string storageConnectionString, string deploymentId, string address, string siloName, string hostName);
}
public interface IConfigurableStatisticsPublisher : IStatisticsPublisher
{
void AddConfiguration(string deploymentId, bool isSilo, string siloName, SiloAddress address, System.Net.IPEndPoint gateway, string hostName);
}
/// <summary>
/// Snapshot of current runtime statistics for a silo
/// </summary>
[Serializable]
public class SiloRuntimeStatistics
{
/// <summary>
/// Total number of activations in a silo.
/// </summary>
public int ActivationCount { get; internal set; }
/// <summary>
/// Number of activations in a silo that have been recently used.
/// </summary>
public int RecentlyUsedActivationCount { get; internal set; }
/// <summary>
/// The size of the request queue.
/// </summary>
public long RequestQueueLength { get; internal set; }
/// <summary>
/// The size of the sending queue.
/// </summary>
public int SendQueueLength { get; internal set; }
/// <summary>
/// The size of the receiving queue.
/// </summary>
public int ReceiveQueueLength { get; internal set; }
/// <summary>
/// The CPU utilization.
/// </summary>
public float CpuUsage { get; internal set; }
/// <summary>
/// The amount of memory available in the silo [bytes].
/// </summary>
public float AvailableMemory { get; internal set; }
/// <summary>
/// The used memory size.
/// </summary>
public long MemoryUsage { get; internal set; }
/// <summary>
/// The total physical memory available [bytes].
/// </summary>
public long TotalPhysicalMemory { get; internal set; }
/// <summary>
/// Is this silo overloaded.
/// </summary>
public bool IsOverloaded { get; internal set; }
/// <summary>
/// The number of clients currently connected to that silo.
/// </summary>
public long ClientCount { get; internal set; }
public long ReceivedMessages { get; internal set; }
public long SentMessages { get; internal set; }
/// <summary>
/// The DateTime when this statistics was created.
/// </summary>
public DateTime DateTime { get; private set; }
internal SiloRuntimeStatistics() { }
internal SiloRuntimeStatistics(ISiloPerformanceMetrics metrics, DateTime dateTime)
{
ActivationCount = metrics.ActivationCount;
RecentlyUsedActivationCount = metrics.RecentlyUsedActivationCount;
RequestQueueLength = metrics.RequestQueueLength;
SendQueueLength = metrics.SendQueueLength;
ReceiveQueueLength = metrics.ReceiveQueueLength;
CpuUsage = metrics.CpuUsage;
AvailableMemory = metrics.AvailablePhysicalMemory;
MemoryUsage = metrics.MemoryUsage;
IsOverloaded = metrics.IsOverloaded;
ClientCount = metrics.ClientCount;
TotalPhysicalMemory = metrics.TotalPhysicalMemory;
ReceivedMessages = metrics.ReceivedMessages;
SentMessages = metrics.SentMessages;
DateTime = dateTime;
}
public override string ToString()
{
return String.Format("SiloRuntimeStatistics: ActivationCount={0} RecentlyUsedActivationCount={11} RequestQueueLength={1} SendQueueLength={2} " +
"ReceiveQueueLength={3} CpuUsage={4} AvailableMemory={5} MemoryUsage={6} IsOverloaded={7} " +
"ClientCount={8} TotalPhysicalMemory={9} DateTime={10}", ActivationCount, RequestQueueLength,
SendQueueLength, ReceiveQueueLength, CpuUsage, AvailableMemory, MemoryUsage, IsOverloaded,
ClientCount, TotalPhysicalMemory, DateTime, RecentlyUsedActivationCount);
}
}
/// <summary>
/// Snapshot of current statistics for a given grain type.
/// </summary>
[Serializable]
internal class GrainStatistic
{
/// <summary>
/// The type of the grain for this GrainStatistic.
/// </summary>
public string GrainType { get; set; }
/// <summary>
/// Number of grains of a this type.
/// </summary>
public int GrainCount { get; set; }
/// <summary>
/// Number of activation of a agrain of this type.
/// </summary>
public int ActivationCount { get; set; }
/// <summary>
/// Number of silos that have activations of this grain type.
/// </summary>
public int SiloCount { get; set; }
/// <summary>
/// Returns the string representatio of this GrainStatistic.
/// </summary>
public override string ToString()
{
return string.Format("GrainStatistic: GrainType={0} NumSilos={1} NumGrains={2} NumActivations={3} ", GrainType, SiloCount, GrainCount, ActivationCount);
}
}
/// <summary>
/// Simple snapshot of current statistics for a given grain type on a given silo.
/// </summary>
[Serializable]
public class SimpleGrainStatistic
{
/// <summary>
/// The type of the grain for this SimpleGrainStatistic.
/// </summary>
public string GrainType { get; set; }
/// <summary>
/// The silo address for this SimpleGrainStatistic.
/// </summary>
public SiloAddress SiloAddress { get; set; }
/// <summary>
/// The number of activations of this grain type on this given silo.
/// </summary>
public int ActivationCount { get; set; }
/// <summary>
/// Returns the string representatio of this SimpleGrainStatistic.
/// </summary>
public override string ToString()
{
return string.Format("SimpleGrainStatistic: GrainType={0} Silo={1} NumActivations={2} ", GrainType, SiloAddress, ActivationCount);
}
}
[Serializable]
internal class DetailedGrainReport
{
public GrainId Grain { get; set; }
public SiloAddress SiloAddress { get; set; } // silo on which these statistics come from
public string SiloName { get; set; } // silo on which these statistics come from
public List<ActivationAddress> LocalCacheActivationAddresses { get; set; } // activation addresses in the local directory cache
public List<ActivationAddress> LocalDirectoryActivationAddresses { get; set; } // activation addresses in the local directory.
public SiloAddress PrimaryForGrain { get; set; } // primary silo for this grain
public string GrainClassTypeName { get; set; } // the name of the class that implements this grain.
public List<string> LocalActivations { get; set; } // activations on this silo
public override string ToString()
{
return string.Format(Environment.NewLine
+ "**DetailedGrainReport for grain {0} from silo {1} SiloAddress={2}" + Environment.NewLine
+ " LocalCacheActivationAddresses={4}" + Environment.NewLine
+ " LocalDirectoryActivationAddresses={5}" + Environment.NewLine
+ " PrimaryForGrain={6}" + Environment.NewLine
+ " GrainClassTypeName={7}" + Environment.NewLine
+ " LocalActivations:" + Environment.NewLine
+ "{3}." + Environment.NewLine,
Grain.ToDetailedString(),
SiloName,
SiloAddress.ToLongString(),
Utils.EnumerableToString(LocalCacheActivationAddresses),
Utils.EnumerableToString(LocalDirectoryActivationAddresses),
PrimaryForGrain,
GrainClassTypeName,
Utils.EnumerableToString(LocalActivations, str => string.Format(" {0}", str), "\n"));
}
}
}
| |
namespace EnergyTrading.MDM.Test.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Moq;
using EnergyTrading;
using EnergyTrading.Data;
using EnergyTrading.Mapping;
using EnergyTrading.Search;
using EnergyTrading.Validation;
using EnergyTrading.MDM;
using EnergyTrading.MDM.Messages;
using EnergyTrading.MDM.Services;
[TestFixture]
public class PartyRoleMapFixture
{
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void NullRequestErrors()
{
// Arrange
var validatorFactory = new Mock<IValidatorEngine>();
var mappingEngine = new Mock<IMappingEngine>();
var repository = new Mock<IRepository>();
var searchCache = new Mock<ISearchCache>();
var service = new PartyRoleService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);
// Act
service.Map(null);
}
[Test]
public void UnsuccessfulMatchReturnsNotFound()
{
// Arrange
var validatorFactory = new Mock<IValidatorEngine>();
var mappingEngine = new Mock<IMappingEngine>();
var repository = new Mock<IRepository>();
var searchCache = new Mock<ISearchCache>();
var service = new PartyRoleService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);
var list = new List<PartyRoleMapping>();
repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable());
validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
var request = new MappingRequest { SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow() };
// Act
var contract = service.Map(request);
// Assert
repository.Verify(x => x.Queryable<PartyRoleMapping>());
Assert.IsNotNull(contract, "Contract null");
Assert.IsFalse(contract.IsValid, "Contract valid");
Assert.AreEqual(ErrorType.NotFound, contract.Error.Type, "ErrorType difers");
}
[Test]
public void SuccessMatch()
{
// Arrange
var validatorFactory = new Mock<IValidatorEngine>();
var mappingEngine = new Mock<IMappingEngine>();
var repository = new Mock<IRepository>();
var searchCache = new Mock<ISearchCache>();
var service = new PartyRoleService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);
// Domain details
var start = new DateTime(1999, 12, 31);
var finish = new DateTime(2020, 1, 1);
var system = new SourceSystem { Name = "Endur" };
var mapping = new PartyRoleMapping
{
System = system,
MappingValue = "A"
};
var details = new PartyRoleDetails
{
Name = "PartyRole 1",
Validity = new DateRange(start, finish)
};
var party = new PartyRole
{
Id = 1,
Party = new Party { Id = 999 }
};
party.AddDetails(details);
party.ProcessMapping(mapping);
// Contract details
var identifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Endur",
Identifier = "A"
};
var cDetails = new EnergyTrading.MDM.Contracts.Sample.PartyRoleDetails
{
Name = "PartyRole 1"
};
mappingEngine.Setup(x => x.Map<PartyRoleMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
mappingEngine.Setup(x => x.Map<PartyRoleDetails, EnergyTrading.MDM.Contracts.Sample.PartyRoleDetails>(details)).Returns(cDetails);
validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
var list = new List<PartyRoleMapping> { mapping };
repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable());
var request = new MappingRequest
{
SystemName = "Endur",
Identifier = "A",
ValidAt = SystemTime.UtcNow(),
Version = 1
};
// Act
var response = service.Map(request);
var candidate = response.Contract;
// Assert
repository.Verify(x => x.Queryable<PartyRoleMapping>());
Assert.IsTrue(response.IsValid);
Assert.IsNotNull(candidate, "Contract null");
mappingEngine.Verify(x => x.Map<PartyRoleMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping));
mappingEngine.Verify(x => x.Map<PartyRoleDetails, EnergyTrading.MDM.Contracts.Sample.PartyRoleDetails>(details));
Assert.AreEqual(2, candidate.Identifiers.Count, "Identifier count incorrect");
// NB This is order dependent
Assert.AreSame(identifier, candidate.Identifiers[1], "Different identifier assigned");
Assert.AreSame(cDetails, candidate.Details, "Different details assigned");
Assert.AreEqual(start, candidate.MdmSystemData.StartDate, "Start date differs");
Assert.AreEqual(finish, candidate.MdmSystemData.EndDate, "End date differs");
}
[Test]
public void SuccessMatchCurrentVersion()
{
// Arrange
var validatorFactory = new Mock<IValidatorEngine>();
var mappingEngine = new Mock<IMappingEngine>();
var repository = new Mock<IRepository>();
var searchCache = new Mock<ISearchCache>();
var service = new PartyRoleService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);
// Domain details
var start = new DateTime(1999, 12, 31);
var finish = new DateTime(2020, 1, 1);
var system = new SourceSystem { Name = "Endur" };
var mapping = new PartyRoleMapping
{
System = system,
MappingValue = "A"
};
var details = new PartyRoleDetails
{
Name = "PartyRole 1",
Validity = new DateRange(start, finish)
};
var party = new PartyRole
{
Id = 1
};
party.AddDetails(details);
party.ProcessMapping(mapping);
// Contract details
var identifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Endur",
Identifier = "A"
};
var cDetails = new EnergyTrading.MDM.Contracts.Sample.PartyRoleDetails
{
Name = "PartyRole 1"
};
mappingEngine.Setup(x => x.Map<PartyRoleMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier);
mappingEngine.Setup(x => x.Map<PartyRoleDetails, EnergyTrading.MDM.Contracts.Sample.PartyRoleDetails>(details)).Returns(cDetails);
validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
var list = new List<PartyRoleMapping> { mapping };
repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable());
var request = new MappingRequest
{
SystemName = "Endur",
Identifier = "A",
ValidAt = SystemTime.UtcNow(),
Version = 0
};
// Act
var response = service.Map(request);
// Assert
repository.Verify(x => x.Queryable<PartyRoleMapping>());
Assert.IsNull(response.Contract, "Contract not null");
Assert.IsTrue(response.IsValid);
Assert.AreEqual(0UL, response.Version);
}
}
}
| |
//==========================================================================================
//
// OpenNETCF.Windows.Forms.Rsa
// Copyright (c) 2003, OpenNETCF.org
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the OpenNETCF.org Shared Source License.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License
// for more details.
//
// You should have received a copy of the OpenNETCF.org Shared Source License
// along with this library; if not, email licensing@opennetcf.org to request a copy.
//
// If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please
// email licensing@opennetcf.org.
//
// For general enquiries, email enquiries@opennetcf.org or visit our website at:
// http://www.opennetcf.org
//
// !!! A HUGE thank-you goes out to Casey Chesnut for supplying this class library !!!
// !!! You can contact Casey at http://www.brains-n-brawn.com !!!
//
//==========================================================================================
using System;
using System.Xml;
using System.IO;
using System.Text;
namespace FlickrNet.Security.Cryptography.NativeMethods
{
internal class Rsa
{
public Rsa(){}
/// <summary>
/// rips apart rawKey into public byte [] for RsaParameters class
/// </summary>
public Rsa(byte [] rawKey)
{
this.rawKey = rawKey; //596
pks = new PUBLICKEYSTRUC();
pks.bType = rawKey[0]; //7
pks.bVersion = rawKey[1]; //2
pks.reserved = BitConverter.ToUInt16(rawKey, 2); //0
pks.aiKeyAlg = BitConverter.ToUInt32(rawKey, 4); //41984
kb = (KeyBlob) pks.bType; //PRIVATE
c = (Calg) pks.aiKeyAlg; //RSA_KEYX
if(kb != KeyBlob.PUBLICKEYBLOB && kb != KeyBlob.PRIVATEKEYBLOB)
throw new Exception("unsupported blob type");
rpk = new RSAPUBKEY();
rpk.magic = BitConverter.ToUInt32(rawKey, 8); //843141970
rpk.bitlen = BitConverter.ToUInt32(rawKey, 12); //1024
rpk.pubexp = BitConverter.ToUInt32(rawKey, 16); //65537
uint byteLen = rpk.bitlen / 8; //128
this.SetSizeAndPosition(rpk.bitlen);
//public
Modulus = Format.GetBytes(this.rawKey, modulusPos, modulusLen, true);
Exponent = Format.GetBytes(this.rawKey, exponentPos, exponentLen, true);
//private
if(kb == KeyBlob.PRIVATEKEYBLOB)
{
this.P = Format.GetBytes(this.rawKey, prime1Pos, prime1Len, true);
this.Q = Format.GetBytes(this.rawKey, prime2Pos, prime2Len, true);
this.DP = Format.GetBytes(this.rawKey, exponent1Pos, exponent1Len, true);
this.DQ = Format.GetBytes(this.rawKey, exponent2Pos, exponent2Len, true);
this.InverseQ = Format.GetBytes(this.rawKey, coefficientPos, coefficientLen, true);
this.D = Format.GetBytes(this.rawKey, privateExponentPos, privateExponentLen, true);
}
else
{
this.P = null;
this.Q = null;
this.DP = null;
this.DQ = null;
this.InverseQ = null;
this.D = null;
}
}
/// <summary>
/// returns public byte arrays in xml format
/// </summary>
public string ToXmlString(bool privateKey)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xtw = new XmlTextWriter(ms, null);
xtw.WriteStartElement("RSAKeyValue");
xtw.WriteElementString("Modulus", Format.GetB64(this.Modulus));
xtw.WriteElementString("Exponent", Format.GetB64(this.Exponent));
if(privateKey == true)
{
xtw.WriteElementString("P", Format.GetB64(this.P));
xtw.WriteElementString("Q", Format.GetB64(this.Q));
xtw.WriteElementString("DP", Format.GetB64(this.DP));
xtw.WriteElementString("DQ", Format.GetB64(this.DQ));
xtw.WriteElementString("InverseQ", Format.GetB64(this.InverseQ));
xtw.WriteElementString("D", Format.GetB64(this.D));
}
xtw.WriteEndElement();
xtw.Flush();
return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>
/// builds up public byte arrays, and rawKey from xml
/// </summary>
public void FromXmlString(string rsaKeyValue)
{
bool privateKey = false;
StringReader sr = new StringReader(rsaKeyValue);
XmlTextReader xtr = new XmlTextReader(sr);
xtr.WhitespaceHandling = WhitespaceHandling.None;
while(xtr.Read())
{
if(xtr.NodeType == XmlNodeType.Element)
{
switch(xtr.LocalName)
{
case "Modulus":
this.Modulus = Format.GetB64(xtr.ReadString());
break;
case "Exponent":
this.Exponent = Format.GetB64(xtr.ReadString());
break;
case "P":
this.P = Format.GetB64(xtr.ReadString());
break;
case "Q":
this.Q = Format.GetB64(xtr.ReadString());
break;
case "DP":
this.DP = Format.GetB64(xtr.ReadString());
break;
case "DQ":
this.DQ = Format.GetB64(xtr.ReadString());
break;
case "InverseQ":
this.InverseQ = Format.GetB64(xtr.ReadString());
break;
case "D":
privateKey = true;
this.D = Format.GetB64(xtr.ReadString());
break;
default:
break;
}
}
}
BuildRawKey(privateKey);
}
public void BuildRawKey(bool privateKey)
{
//build up rawKey byte[]
uint rsaMagic = 0;
int caSize = 0;
uint bitLen = (uint) this.Modulus.Length * 8;
if(privateKey == true)
{
kb = KeyBlob.PRIVATEKEYBLOB;
caSize = 20 + (9 * ((int)bitLen / 16));
rsaMagic = 0x32415352; //ASCII encoding of "RSA2"
}
else //public
{
kb = KeyBlob.PUBLICKEYBLOB;
caSize = 20 + ((int)bitLen / 8);
rsaMagic = 0x31415352; //ASCII encoding of "RSA1"
}
rawKey = new byte[caSize];
//PUBLICKEYSTRUC
rawKey[0] = (byte) kb; //bType
rawKey[1] = (byte) 2; //bVersion
//reserved 2,3
c = Calg.RSA_KEYX;
byte [] baKeyAlg = BitConverter.GetBytes((uint)c);//aiKeyAlg
Buffer.BlockCopy(baKeyAlg, 0, rawKey, 4, 4);
pks = new PUBLICKEYSTRUC();
pks.bType = rawKey[0];
pks.bVersion = rawKey[1];
pks.reserved = BitConverter.ToUInt16(rawKey, 2);
pks.aiKeyAlg = BitConverter.ToUInt32(rawKey, 4);
//RSAPUBKEY
byte [] baMagic = BitConverter.GetBytes(rsaMagic);//magic
Buffer.BlockCopy(baMagic, 0, rawKey, 8, 4);
byte [] baBitlen = BitConverter.GetBytes(bitLen);//bitlen
Buffer.BlockCopy(baBitlen, 0, rawKey, 12, 4);
this.SetSizeAndPosition(bitLen);
Format.SetBytes(this.rawKey, exponentPos, exponentLen, this.Exponent, true); //pubexp
rpk = new RSAPUBKEY();
rpk.magic = BitConverter.ToUInt32(rawKey, 8);
rpk.bitlen = BitConverter.ToUInt32(rawKey, 12);
rpk.pubexp = BitConverter.ToUInt32(rawKey, 16);
uint byteLen = rpk.bitlen / 8;
//public
Format.SetBytes(this.rawKey, modulusPos, modulusLen, this.Modulus, true);
Format.SetBytes(this.rawKey, exponentPos, exponentLen, this.Exponent, true);
//private
if(privateKey == true)
{
Format.SetBytes(this.rawKey, prime1Pos, prime1Len, this.P, true);
Format.SetBytes(this.rawKey, prime2Pos, prime2Len, this.Q, true);
Format.SetBytes(this.rawKey, exponent1Pos, exponent1Len, this.DP, true);
Format.SetBytes(this.rawKey, exponent2Pos, exponent2Len, this.DQ, true);
Format.SetBytes(this.rawKey, coefficientPos, coefficientLen, this.InverseQ, true);
Format.SetBytes(this.rawKey, privateExponentPos, privateExponentLen, this.D, true);
}
else
{
this.P = null;
this.Q = null;
this.DP = null;
this.DQ = null;
this.InverseQ = null;
this.D = null;
}
}
/// <summary>
/// used to extract session keys in the clear
/// </summary>
//http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q228/7/86.ASP&NoWebContent=1
public void ExponentOfOne()
{
this.Exponent = new byte[exponentLen];
this.Exponent[0] = 1;
Format.SetBytes(this.rawKey, exponentPos, exponentLen, this.Exponent, false);
this.DP = new byte[exponent1Len];
this.DP[0] = 1;
Format.SetBytes(this.rawKey, exponent1Pos, exponent1Len, this.DP, false);
this.DQ = new byte[exponent2Len];
this.DQ[0] = 1;
Format.SetBytes(this.rawKey, exponent2Pos, exponent2Len, this.DQ, false);
this.D = new byte[privateExponentLen];
this.D[0] = 1;
Format.SetBytes(this.rawKey, privateExponentPos, privateExponentLen, this.D, false);
}
public byte [] rawKey;
public PUBLICKEYSTRUC pks;
public RSAPUBKEY rpk;
public KeyBlob kb;
public Calg c;
//public
public byte [] Modulus; //n
public byte [] Exponent; //e
//private
public byte [] P;
public byte [] Q;
public byte [] DP;
public byte [] DQ;
public byte [] InverseQ;
public byte [] D;
private uint pksLen;
private uint rpkLen;
private uint exponentLen;
private uint modulusLen;
private uint prime1Len;
private uint prime2Len;
private uint exponent1Len;
private uint exponent2Len;
private uint coefficientLen;
private uint privateExponentLen;
private uint rpkPos;
private uint exponentPos;
private uint modulusPos;
private uint prime1Pos;
private uint prime2Pos;
private uint exponent1Pos;
private uint exponent2Pos;
private uint coefficientPos;
private uint privateExponentPos;
private uint privByteLen;
private uint pubByteLen;
private void SetSizeAndPosition(uint bitLen)
{
//size = 8 12 128 64 64 64 64 64 128 = 596!
pksLen = 8;
rpkLen = 12;
exponentLen = 4;
modulusLen = bitLen / 8; //128
prime1Len = bitLen / 16; //64
prime2Len = bitLen / 16; //64
exponent1Len = bitLen / 16; //64
exponent2Len = bitLen / 16; //64
coefficientLen = bitLen / 16; //64
privateExponentLen = bitLen / 8; //128
privByteLen = pksLen + rpkLen + modulusLen + prime1Len + prime2Len + exponent1Len + exponent2Len + coefficientLen + privateExponentLen; //596
pubByteLen = pksLen + rpkLen + modulusLen; //148
//1024 = 16 20 148 212 276 340 404 468
//uint pksPos = 0;
rpkPos = pksLen; //8
exponentPos = rpkPos + 8; //16
modulusPos = rpkPos + rpkLen; //20
prime1Pos = modulusPos + modulusLen; //148
prime2Pos = prime1Pos + prime1Len; //212
exponent1Pos = prime2Pos + prime2Len; //276
exponent2Pos = exponent1Pos + exponent1Len; //340
coefficientPos = exponent2Pos + exponent2Len; //404
privateExponentPos = coefficientPos + coefficientLen; //468
}
}
}
| |
#region Foreign-License
/*
This file implements the TclPosixException class, used to report posix errors in Tcl scripts.
Copyright (c) 1997 Sun Microsystems, Inc.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System;
namespace Tcl.Lang
{
/*
* This class implements exceptions used to report posix errors in Tcl scripts.
*/
class TclPosixException : TclException
{
internal const int EPERM = 1; /* Operation not permitted */
internal const int ENOENT = 2; /* No such file or directory */
internal const int ESRCH = 3; /* No such process */
internal const int EINTR = 4; /* Interrupted system call */
internal const int EIO = 5; /* Input/output error */
internal const int ENXIO = 6; /* Device not configured */
internal const int E2BIG = 7; /* Argument list too long */
internal const int ENOEXEC = 8; /* Exec format error */
internal const int EBADF = 9; /* Bad file descriptor */
internal const int ECHILD = 10; /* No child processes */
internal const int EDEADLK = 11; /* Resource deadlock avoided */
/* 11 was EAGAIN */
internal const int ENOMEM = 12; /* Cannot allocate memory */
internal const int EACCES = 13; /* Permission denied */
internal const int EFAULT = 14; /* Bad address */
internal const int ENOTBLK = 15; /* Block device required */
internal const int EBUSY = 16; /* Device busy */
internal const int EEXIST = 17; /* File exists */
internal const int EXDEV = 18; /* Cross-device link */
internal const int ENODEV = 19; /* Operation not supported by device */
internal const int ENOTDIR = 20; /* Not a directory */
internal const int EISDIR = 21; /* Is a directory */
internal const int EINVAL = 22; /* Invalid argument */
internal const int ENFILE = 23; /* Too many open files in system */
internal const int EMFILE = 24; /* Too many open files */
internal const int ENOTTY = 25; /* Inappropriate ioctl for device */
internal const int ETXTBSY = 26; /* Text file busy */
internal const int EFBIG = 27; /* File too large */
internal const int ENOSPC = 28; /* No space left on device */
internal const int ESPIPE = 29; /* Illegal seek */
internal const int EROFS = 30; /* Read-only file system */
internal const int EMLINK = 31; /* Too many links */
internal const int EPIPE = 32; /* Broken pipe */
internal const int EDOM = 33; /* Numerical argument out of domain */
internal const int ERANGE = 34; /* Result too large */
internal const int EAGAIN = 35; /* Resource temporarily unavailable */
internal const int EWOULDBLOCK = EAGAIN; /* Operation would block */
internal const int EINPROGRESS = 36; /* Operation now in progress */
internal const int EALREADY = 37; /* Operation already in progress */
internal const int ENOTSOCK = 38; /* Socket operation on non-socket */
internal const int EDESTADDRREQ = 39; /* Destination address required */
internal const int EMSGSIZE = 40; /* Message too long */
internal const int EPROTOTYPE = 41; /* Protocol wrong type for socket */
internal const int ENOPROTOOPT = 42; /* Protocol not available */
internal const int EPROTONOSUPPORT = 43; /* Protocol not supported */
internal const int ESOCKTNOSUPPORT = 44; /* Socket type not supported */
internal const int EOPNOTSUPP = 45; /* Operation not supported on socket */
internal const int EPFNOSUPPORT = 46; /* Protocol family not supported */
internal const int EAFNOSUPPORT = 47; /* Address family not supported by
/* protocol family */
internal const int EADDRINUSE = 48; /* Address already in use */
internal const int EADDRNOTAVAIL = 49; /* Can't assign requested
/* address */
internal const int ENETDOWN = 50; /* Network is down */
internal const int ENETUNREACH = 51; /* Network is unreachable */
internal const int ENETRESET = 52; /* Network dropped connection on reset */
internal const int ECONNABORTED = 53; /* Software caused connection abort */
internal const int ECONNRESET = 54; /* Connection reset by peer */
internal const int ENOBUFS = 55; /* No buffer space available */
internal const int EISCONN = 56; /* Socket is already connected */
internal const int ENOTCONN = 57; /* Socket is not connected */
internal const int ESHUTDOWN = 58; /* Can't send after socket shutdown */
internal const int ETOOMANYREFS = 59; /* Too many references: can't splice */
internal const int ETIMEDOUT = 60; /* Connection timed out */
internal const int ECONNREFUSED = 61; /* Connection refused */
internal const int ELOOP = 62; /* Too many levels of symbolic links */
internal const int ENAMETOOLONG = 63; /* File name too long */
internal const int EHOSTDOWN = 64; /* Host is down */
internal const int EHOSTUNREACH = 65; /* No route to host */
internal const int ENOTEMPTY = 66; /* Directory not empty */
internal const int EPROCLIM = 67; /* Too many processes */
internal const int EUSERS = 68; /* Too many users */
internal const int EDQUOT = 69; /* Disc quota exceeded */
internal const int ESTALE = 70; /* Stale NFS file handle */
internal const int EREMOTE = 71; /* Too many levels of remote in path */
internal const int EBADRPC = 72; /* RPC struct is bad */
internal const int ERPCMISMATCH = 73; /* RPC version wrong */
internal const int EPROGUNAVAIL = 74; /* RPC prog. not avail */
internal const int EPROGMISMATCH = 75; /* Program version wrong */
internal const int EPROCUNAVAIL = 76; /* Bad procedure for program */
internal const int ENOLCK = 77; /* No locks available */
internal const int ENOSYS = 78; /* Function not implemented */
internal const int EFTYPE = 79; /* Inappropriate file type or format */
public TclPosixException(Interp interp, int errno, string errorMsg)
: base(TCL.CompletionCode.ERROR)
{
string msg = getPosixMsg(errno);
TclObject threeEltListObj = TclList.NewInstance();
TclList.Append(interp, threeEltListObj, TclString.NewInstance("POSIX"));
TclList.Append(interp, threeEltListObj, TclString.NewInstance(getPosixId(errno)));
TclList.Append(interp, threeEltListObj, TclString.NewInstance(msg));
interp.SetErrorCode(threeEltListObj);
if (interp != null)
{
interp.SetResult(errorMsg);
}
}
public TclPosixException(Interp interp, int errno, bool appendPosixMsg, string errorMsg)
: base(TCL.CompletionCode.ERROR)
{
string msg = getPosixMsg(errno);
TclObject threeEltListObj = TclList.NewInstance();
TclList.Append(interp, threeEltListObj, TclString.NewInstance("POSIX"));
TclList.Append(interp, threeEltListObj, TclString.NewInstance(getPosixId(errno)));
TclList.Append(interp, threeEltListObj, TclString.NewInstance(msg));
interp.SetErrorCode(threeEltListObj);
if (interp != null)
{
if (appendPosixMsg)
{
interp.SetResult(errorMsg + ": " + msg);
}
else
{
interp.SetResult(errorMsg);
}
}
}
private static string getPosixId(int errno)
// Code of posix error.
{
switch (errno)
{
case E2BIG:
return "E2BIG";
case EACCES:
return "EACCES";
case EADDRINUSE:
return "EADDRINUSE";
case EADDRNOTAVAIL:
return "EADDRNOTAVAIL";
//case EADV: return "EADV";
case EAFNOSUPPORT:
return "EAFNOSUPPORT";
case EAGAIN:
return "EAGAIN";
//case EALIGN: return "EALIGN";
case EALREADY:
return "EALREADY";
//case EBADE: return "EBADE";
case EBADF:
return "EBADF";
//case EBADFD: return "EBADFD";
//case EBADMSG: return "EBADMSG";
//case EBADR: return "EBADR";
case EBADRPC:
return "EBADRPC";
//case EBADRQC: return "EBADRQC";
//case EBADSLT: return "EBADSLT";
//case EBFONT: return "EBFONT";
case EBUSY:
return "EBUSY";
case ECHILD:
return "ECHILD";
//case ECHRNG: return "ECHRNG";
//case ECOMM: return "ECOMM";
case ECONNABORTED:
return "ECONNABORTED";
case ECONNREFUSED:
return "ECONNREFUSED";
case ECONNRESET:
return "ECONNRESET";
case EDEADLK:
return "EDEADLK";
//case EDEADLOCK: return "EDEADLOCK";
case EDESTADDRREQ:
return "EDESTADDRREQ";
//case EDIRTY: return "EDIRTY";
case EDOM:
return "EDOM";
//case EDOTDOT: return "EDOTDOT";
case EDQUOT:
return "EDQUOT";
//case EDUPPKG: return "EDUPPKG";
case EEXIST:
return "EEXIST";
case EFAULT:
return "EFAULT";
case EFBIG:
return "EFBIG";
case EHOSTDOWN:
return "EHOSTDOWN";
case EHOSTUNREACH:
return "EHOSTUNREACH";
//case EIDRM: return "EIDRM";
//case EINIT: return "EINIT";
case EINPROGRESS:
return "EINPROGRESS";
case EINTR:
return "EINTR";
case EINVAL:
return "EINVAL";
case EIO:
return "EIO";
case EISCONN:
return "EISCONN";
case EISDIR:
return "EISDIR";
//case EISNAM: return "EISNAM";
//case ELBIN: return "ELBIN";
//case EL2HLT: return "EL2HLT";
//case EL2NSYNC: return "EL2NSYNC";
//case EL3HLT: return "EL3HLT";
//case EL3RST: return "EL3RST";
//case ELIBACC: return "ELIBACC";
//case ELIBBAD: return "ELIBBAD";
//case ELIBEXEC: return "ELIBEXEC";
//case ELIBMAX: return "ELIBMAX";
//case ELIBSCN: return "ELIBSCN";
//case ELNRNG: return "ELNRNG";
case ELOOP:
return "ELOOP";
case EMLINK:
return "EMLINK";
case EMSGSIZE:
return "EMSGSIZE";
//case EMULTIHOP: return "EMULTIHOP";
case ENAMETOOLONG:
return "ENAMETOOLONG";
//case ENAVAIL: return "ENAVAIL";
//case ENET: return "ENET";
case ENETDOWN:
return "ENETDOWN";
case ENETRESET:
return "ENETRESET";
case ENETUNREACH:
return "ENETUNREACH";
case ENFILE:
return "ENFILE";
//case ENOANO: return "ENOANO";
case ENOBUFS:
return "ENOBUFS";
//case ENOCSI: return "ENOCSI";
//case ENODATA: return "ENODATA";
case ENODEV:
return "ENODEV";
case ENOENT:
return "ENOENT";
case ENOEXEC:
return "ENOEXEC";
case ENOLCK:
return "ENOLCK";
//case ENOLINK: return "ENOLINK";
case ENOMEM:
return "ENOMEM";
//case ENOMSG: return "ENOMSG";
//case ENONET: return "ENONET";
//case ENOPKG: return "ENOPKG";
case ENOPROTOOPT:
return "ENOPROTOOPT";
case ENOSPC:
return "ENOSPC";
//case ENOSR: return "ENOSR";
//case ENOSTR: return "ENOSTR";
//case ENOSYM: return "ENOSYM";
case ENOSYS:
return "ENOSYS";
case ENOTBLK:
return "ENOTBLK";
case ENOTCONN:
return "ENOTCONN";
case ENOTDIR:
return "ENOTDIR";
case ENOTEMPTY:
return "ENOTEMPTY";
//case ENOTNAM: return "ENOTNAM";
case ENOTSOCK:
return "ENOTSOCK";
//case ENOTSUP: return "ENOTSUP";
case ENOTTY:
return "ENOTTY";
//case ENOTUNIQ: return "ENOTUNIQ";
case ENXIO:
return "ENXIO";
case EOPNOTSUPP:
return "EOPNOTSUPP";
case EPERM:
return "EPERM";
case EPFNOSUPPORT:
return "EPFNOSUPPORT";
case EPIPE:
return "EPIPE";
case EPROCLIM:
return "EPROCLIM";
case EPROCUNAVAIL:
return "EPROCUNAVAIL";
case EPROGMISMATCH:
return "EPROGMISMATCH";
case EPROGUNAVAIL:
return "EPROGUNAVAIL";
//case EPROTO: return "EPROTO";
case EPROTONOSUPPORT:
return "EPROTONOSUPPORT";
case EPROTOTYPE:
return "EPROTOTYPE";
case ERANGE:
return "ERANGE";
//case EREFUSED: return "EREFUSED";
//case EREMCHG: return "EREMCHG";
//case EREMDEV: return "EREMDEV";
case EREMOTE:
return "EREMOTE";
//case EREMOTEIO: return "EREMOTEIO";
//case EREMOTERELEASE: return "EREMOTERELEASE";
case EROFS:
return "EROFS";
case ERPCMISMATCH:
return "ERPCMISMATCH";
//case ERREMOTE: return "ERREMOTE";
case ESHUTDOWN:
return "ESHUTDOWN";
case ESOCKTNOSUPPORT:
return "ESOCKTNOSUPPORT";
case ESPIPE:
return "ESPIPE";
case ESRCH:
return "ESRCH";
//case ESRMNT: return "ESRMNT";
case ESTALE:
return "ESTALE";
//case ESUCCESS: return "ESUCCESS";
//case ETIME: return "ETIME";
case ETIMEDOUT:
return "ETIMEDOUT";
case ETOOMANYREFS:
return "ETOOMANYREFS";
case ETXTBSY:
return "ETXTBSY";
//case EUCLEAN: return "EUCLEAN";
//case EUNATCH: return "EUNATCH";
case EUSERS:
return "EUSERS";
//case EVERSION: return "EVERSION";
//case EWOULDBLOCK: return "EWOULDBLOCK";
case EXDEV:
return "EXDEV";
//case EXFULL: return "EXFULL";
}
return "unknown error";
}
internal static string getPosixMsg(int errno)
// Code of posix error.
{
switch (errno)
{
case E2BIG:
return "argument list too long";
case EACCES:
return "permission denied";
case EADDRINUSE:
return "address already in use";
case EADDRNOTAVAIL:
return "can't assign requested address";
//case EADV: return "advertise error";
case EAFNOSUPPORT:
return "address family not supported by protocol family";
case EAGAIN:
return "resource temporarily unavailable";
//case EALIGN: return "EALIGN";
case EALREADY:
return "operation already in progress";
//case EBADE: return "bad exchange descriptor";
case EBADF:
return "bad file number";
//case EBADFD: return "file descriptor in bad state";
//case EBADMSG: return "not a data message";
//case EBADR: return "bad request descriptor";
case EBADRPC:
return "RPC structure is bad";
//case EBADRQC: return "bad request code";
//case EBADSLT: return "invalid slot";
//case EBFONT: return "bad font file format";
case EBUSY:
return "file busy";
case ECHILD:
return "no children";
//case ECHRNG: return "channel number out of range";
//case ECOMM: return "communication error on send";
case ECONNABORTED:
return "software caused connection abort";
case ECONNREFUSED:
return "connection refused";
case ECONNRESET:
return "connection reset by peer";
case EDEADLK:
return "resource deadlock avoided";
//case EDEADLOCK: return "resource deadlock avoided";
case EDESTADDRREQ:
return "destination address required";
//case EDIRTY: return "mounting a dirty fs w/o force";
case EDOM:
return "math argument out of range";
//case EDOTDOT: return "cross mount point";
case EDQUOT:
return "disk quota exceeded";
//case EDUPPKG: return "duplicate package name";
case EEXIST:
return "file already exists";
case EFAULT:
return "bad address in system call argument";
case EFBIG:
return "file too large";
case EHOSTDOWN:
return "host is down";
case EHOSTUNREACH:
return "host is unreachable";
//case EIDRM: return "identifier removed";
//case EINIT: return "initialization error";
case EINPROGRESS:
return "operation now in progress";
case EINTR:
return "interrupted system call";
case EINVAL:
return "invalid argument";
case EIO:
return "I/O error";
case EISCONN:
return "socket is already connected";
case EISDIR:
return "illegal operation on a directory";
//case EISNAM: return "is a name file";
//case ELBIN: return "ELBIN";
//case EL2HLT: return "level 2 halted";
//case EL2NSYNC: return "level 2 not synchronized";
//case EL3HLT: return "level 3 halted";
//case EL3RST: return "level 3 reset";
//case ELIBACC: return "can not access a needed shared library";
//case ELIBBAD: return "accessing a corrupted shared library";
//case ELIBEXEC: return "can not exec a shared library directly";
//case ELIBMAX: return
//"attempting to link in more shared libraries than system limit";
//case ELIBSCN: return ".lib section in a.out corrupted";
//case ELNRNG: return "link number out of range";
case ELOOP:
return "too many levels of symbolic links";
case EMFILE:
return "too many open files";
case EMLINK:
return "too many links";
case EMSGSIZE:
return "message too long";
//case EMULTIHOP: return "multihop attempted";
case ENAMETOOLONG:
return "file name too long";
//case ENAVAIL: return "not available";
//case ENET: return "ENET";
case ENETDOWN:
return "network is down";
case ENETRESET:
return "network dropped connection on reset";
case ENETUNREACH:
return "network is unreachable";
case ENFILE:
return "file table overflow";
//case ENOANO: return "anode table overflow";
case ENOBUFS:
return "no buffer space available";
//case ENOCSI: return "no CSI structure available";
//case ENODATA: return "no data available";
case ENODEV:
return "no such device";
case ENOENT:
return "no such file or directory";
case ENOEXEC:
return "exec format error";
case ENOLCK:
return "no locks available";
//case ENOLINK: return "link has be severed";
case ENOMEM:
return "not enough memory";
//case ENOMSG: return "no message of desired type";
//case ENONET: return "machine is not on the network";
//case ENOPKG: return "package not installed";
case ENOPROTOOPT:
return "bad proocol option";
case ENOSPC:
return "no space left on device";
//case ENOSR: return "out of stream resources";
//case ENOSTR: return "not a stream device";
//case ENOSYM: return "unresolved symbol name";
case ENOSYS:
return "function not implemented";
case ENOTBLK:
return "block device required";
case ENOTCONN:
return "socket is not connected";
case ENOTDIR:
return "not a directory";
case ENOTEMPTY:
return "directory not empty";
//case ENOTNAM: return "not a name file";
case ENOTSOCK:
return "socket operation on non-socket";
//case ENOTSUP: return "operation not supported";
case ENOTTY:
return "inappropriate device for ioctl";
//case ENOTUNIQ: return "name not unique on network";
case ENXIO:
return "no such device or address";
case EOPNOTSUPP:
return "operation not supported on socket";
case EPERM:
return "not owner";
case EPFNOSUPPORT:
return "protocol family not supported";
case EPIPE:
return "broken pipe";
case EPROCLIM:
return "too many processes";
case EPROCUNAVAIL:
return "bad procedure for program";
case EPROGMISMATCH:
return "program version wrong";
case EPROGUNAVAIL:
return "RPC program not available";
//case EPROTO: return "protocol error";
case EPROTONOSUPPORT:
return "protocol not suppored";
case EPROTOTYPE:
return "protocol wrong type for socket";
case ERANGE:
return "math result unrepresentable";
//case EREFUSED: return "EREFUSED";
//case EREMCHG: return "remote address changed";
//case EREMDEV: return "remote device";
case EREMOTE:
return "pathname hit remote file system";
//case EREMOTEIO: return "remote i/o error";
//case EREMOTERELEASE: return "EREMOTERELEASE";
case EROFS:
return "read-only file system";
case ERPCMISMATCH:
return "RPC version is wrong";
//case ERREMOTE: return "object is remote";
case ESHUTDOWN:
return "can't send afer socket shutdown";
case ESOCKTNOSUPPORT:
return "socket type not supported";
case ESPIPE:
return "invalid seek";
case ESRCH:
return "no such process";
//case ESRMNT: return "srmount error";
case ESTALE:
return "stale remote file handle";
//case ESUCCESS: return "Error 0";
//case ETIME: return "timer expired";
case ETIMEDOUT:
return "connection timed out";
case ETOOMANYREFS:
return "too many references: can't splice";
case ETXTBSY:
return "text file or pseudo-device busy";
//case EUCLEAN: return "structure needs cleaning";
//case EUNATCH: return "protocol driver not attached";
case EUSERS:
return "too many users";
//case EVERSION: return "version mismatch";
//case EWOULDBLOCK: return "operation would block";
case EXDEV:
return "cross-domain link";
//case EXFULL: return "message tables full";
default:
return "unknown POSIX error";
}
}
} // end TclPosixException class
}
| |
namespace Trionic5Controls
{
partial class frmBoostBiasWizard
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmBoostBiasWizard));
this.wizardControl1 = new DevExpress.XtraWizard.WizardControl();
this.welcomeWizardPage1 = new DevExpress.XtraWizard.WelcomeWizardPage();
this.memoEdit1 = new DevExpress.XtraEditors.MemoEdit();
this.wizardPage1 = new DevExpress.XtraWizard.WizardPage();
this.spinEdit2 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl2 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit3 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl3 = new DevExpress.XtraEditors.LabelControl();
this.spinEdit1 = new DevExpress.XtraEditors.SpinEdit();
this.spinEdit4 = new DevExpress.XtraEditors.SpinEdit();
this.labelControl1 = new DevExpress.XtraEditors.LabelControl();
this.labelControl4 = new DevExpress.XtraEditors.LabelControl();
this.completionWizardPage1 = new DevExpress.XtraWizard.CompletionWizardPage();
this.memoEdit2 = new DevExpress.XtraEditors.MemoEdit();
((System.ComponentModel.ISupportInitialize)(this.wizardControl1)).BeginInit();
this.wizardControl1.SuspendLayout();
this.welcomeWizardPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.memoEdit1.Properties)).BeginInit();
this.wizardPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).BeginInit();
this.completionWizardPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.memoEdit2.Properties)).BeginInit();
this.SuspendLayout();
//
// wizardControl1
//
this.wizardControl1.Controls.Add(this.welcomeWizardPage1);
this.wizardControl1.Controls.Add(this.wizardPage1);
this.wizardControl1.Controls.Add(this.completionWizardPage1);
this.wizardControl1.Image = ((System.Drawing.Image)(resources.GetObject("wizardControl1.Image")));
this.wizardControl1.ImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.wizardControl1.Name = "wizardControl1";
this.wizardControl1.Pages.AddRange(new DevExpress.XtraWizard.BaseWizardPage[] {
this.welcomeWizardPage1,
this.wizardPage1,
this.completionWizardPage1});
//
// welcomeWizardPage1
//
this.welcomeWizardPage1.Controls.Add(this.memoEdit1);
this.welcomeWizardPage1.IntroductionText = "This wizard will guide you through the neccesary steps to adjust your boost bias " +
"RPM range";
this.welcomeWizardPage1.Name = "welcomeWizardPage1";
this.welcomeWizardPage1.Size = new System.Drawing.Size(567, 425);
this.welcomeWizardPage1.Text = "Welcome to the boost bias RPM range wizard";
//
// memoEdit1
//
this.memoEdit1.EditValue = "Please note that this wizard will adjust the actual code in your binary!";
this.memoEdit1.Location = new System.Drawing.Point(70, 146);
this.memoEdit1.Name = "memoEdit1";
this.memoEdit1.Properties.Appearance.BackColor = System.Drawing.Color.Transparent;
this.memoEdit1.Properties.Appearance.ForeColor = System.Drawing.Color.Firebrick;
this.memoEdit1.Properties.Appearance.Options.UseBackColor = true;
this.memoEdit1.Properties.Appearance.Options.UseForeColor = true;
this.memoEdit1.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.memoEdit1.Properties.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.memoEdit1.Size = new System.Drawing.Size(434, 172);
this.memoEdit1.TabIndex = 1;
//
// wizardPage1
//
this.wizardPage1.Controls.Add(this.spinEdit2);
this.wizardPage1.Controls.Add(this.labelControl2);
this.wizardPage1.Controls.Add(this.spinEdit3);
this.wizardPage1.Controls.Add(this.labelControl3);
this.wizardPage1.Controls.Add(this.spinEdit1);
this.wizardPage1.Controls.Add(this.spinEdit4);
this.wizardPage1.Controls.Add(this.labelControl1);
this.wizardPage1.Controls.Add(this.labelControl4);
this.wizardPage1.DescriptionText = "Please set the options below to match your desired RPM range";
this.wizardPage1.Name = "wizardPage1";
this.wizardPage1.Size = new System.Drawing.Size(752, 413);
this.wizardPage1.Text = "Boost bias RPM range options";
//
// spinEdit2
//
this.spinEdit2.EditValue = new decimal(new int[] {
7500,
0,
0,
0});
this.spinEdit2.Enabled = false;
this.spinEdit2.Location = new System.Drawing.Point(332, 210);
this.spinEdit2.Name = "spinEdit2";
this.spinEdit2.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit2.Properties.Increment = new decimal(new int[] {
100,
0,
0,
0});
this.spinEdit2.Properties.IsFloatValue = false;
this.spinEdit2.Properties.Mask.EditMask = "N00";
this.spinEdit2.Properties.MaxValue = new decimal(new int[] {
10000,
0,
0,
0});
this.spinEdit2.Properties.MinValue = new decimal(new int[] {
5000,
0,
0,
0});
this.spinEdit2.Size = new System.Drawing.Size(70, 20);
this.spinEdit2.TabIndex = 9;
this.spinEdit2.Visible = false;
//
// labelControl2
//
this.labelControl2.Location = new System.Drawing.Point(195, 213);
this.labelControl2.Name = "labelControl2";
this.labelControl2.Size = new System.Drawing.Size(97, 13);
this.labelControl2.TabIndex = 8;
this.labelControl2.Text = "Hardcoded RPM limit";
this.labelControl2.Visible = false;
//
// spinEdit3
//
this.spinEdit3.EditValue = new decimal(new int[] {
5500,
0,
0,
0});
this.spinEdit3.Enabled = false;
this.spinEdit3.Location = new System.Drawing.Point(493, 184);
this.spinEdit3.Name = "spinEdit3";
this.spinEdit3.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit3.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit3.Properties.IsFloatValue = false;
this.spinEdit3.Properties.Mask.EditMask = "N00";
this.spinEdit3.Size = new System.Drawing.Size(70, 20);
this.spinEdit3.TabIndex = 7;
//
// labelControl3
//
this.labelControl3.Location = new System.Drawing.Point(427, 187);
this.labelControl3.Name = "labelControl3";
this.labelControl3.Size = new System.Drawing.Size(46, 13);
this.labelControl3.TabIndex = 6;
this.labelControl3.Text = "rpm upto ";
//
// spinEdit1
//
this.spinEdit1.EditValue = new decimal(new int[] {
10,
0,
0,
0});
this.spinEdit1.Location = new System.Drawing.Point(332, 158);
this.spinEdit1.Name = "spinEdit1";
this.spinEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit1.Properties.IsFloatValue = false;
this.spinEdit1.Properties.Mask.EditMask = "N00";
this.spinEdit1.Properties.MaxValue = new decimal(new int[] {
20,
0,
0,
0});
this.spinEdit1.Properties.MinValue = new decimal(new int[] {
5,
0,
0,
0});
this.spinEdit1.Size = new System.Drawing.Size(70, 20);
this.spinEdit1.TabIndex = 1;
this.spinEdit1.ValueChanged += new System.EventHandler(this.spinEdit1_ValueChanged);
//
// spinEdit4
//
this.spinEdit4.EditValue = new decimal(new int[] {
2500,
0,
0,
0});
this.spinEdit4.Enabled = false;
this.spinEdit4.Location = new System.Drawing.Point(332, 184);
this.spinEdit4.Name = "spinEdit4";
this.spinEdit4.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
this.spinEdit4.Properties.Increment = new decimal(new int[] {
50,
0,
0,
0});
this.spinEdit4.Properties.IsFloatValue = false;
this.spinEdit4.Properties.Mask.EditMask = "N00";
this.spinEdit4.Size = new System.Drawing.Size(70, 20);
this.spinEdit4.TabIndex = 5;
//
// labelControl1
//
this.labelControl1.Location = new System.Drawing.Point(195, 161);
this.labelControl1.Name = "labelControl1";
this.labelControl1.Size = new System.Drawing.Size(75, 13);
this.labelControl1.TabIndex = 0;
this.labelControl1.Text = "Axis step range";
//
// labelControl4
//
this.labelControl4.Location = new System.Drawing.Point(195, 187);
this.labelControl4.Name = "labelControl4";
this.labelControl4.Size = new System.Drawing.Size(76, 13);
this.labelControl4.TabIndex = 4;
this.labelControl4.Text = "Result rpm from";
//
// completionWizardPage1
//
this.completionWizardPage1.Controls.Add(this.memoEdit2);
this.completionWizardPage1.Name = "completionWizardPage1";
this.completionWizardPage1.Size = new System.Drawing.Size(567, 425);
//
// memoEdit2
//
this.memoEdit2.EditValue = "Please note that the wizard makes changes to actual code in your binary. Be sure " +
"to verify correct operation after applying the wizard.";
this.memoEdit2.Location = new System.Drawing.Point(70, 146);
this.memoEdit2.Name = "memoEdit2";
this.memoEdit2.Properties.Appearance.BackColor = System.Drawing.Color.Transparent;
this.memoEdit2.Properties.Appearance.ForeColor = System.Drawing.Color.Firebrick;
this.memoEdit2.Properties.Appearance.Options.UseBackColor = true;
this.memoEdit2.Properties.Appearance.Options.UseForeColor = true;
this.memoEdit2.Properties.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
this.memoEdit2.Properties.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.memoEdit2.Size = new System.Drawing.Size(434, 140);
this.memoEdit2.TabIndex = 2;
//
// frmBoostBiasWizard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(784, 558);
this.ControlBox = false;
this.Controls.Add(this.wizardControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "frmBoostBiasWizard";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Boost bias RPM range wizard";
((System.ComponentModel.ISupportInitialize)(this.wizardControl1)).EndInit();
this.wizardControl1.ResumeLayout(false);
this.welcomeWizardPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.memoEdit1.Properties)).EndInit();
this.wizardPage1.ResumeLayout(false);
this.wizardPage1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.spinEdit2.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit3.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit1.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinEdit4.Properties)).EndInit();
this.completionWizardPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.memoEdit2.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraWizard.WizardControl wizardControl1;
private DevExpress.XtraWizard.WelcomeWizardPage welcomeWizardPage1;
private DevExpress.XtraEditors.MemoEdit memoEdit1;
private DevExpress.XtraWizard.WizardPage wizardPage1;
private DevExpress.XtraWizard.CompletionWizardPage completionWizardPage1;
private DevExpress.XtraEditors.MemoEdit memoEdit2;
private DevExpress.XtraEditors.SpinEdit spinEdit3;
private DevExpress.XtraEditors.LabelControl labelControl3;
private DevExpress.XtraEditors.SpinEdit spinEdit4;
private DevExpress.XtraEditors.LabelControl labelControl4;
private DevExpress.XtraEditors.SpinEdit spinEdit1;
private DevExpress.XtraEditors.LabelControl labelControl1;
private DevExpress.XtraEditors.SpinEdit spinEdit2;
private DevExpress.XtraEditors.LabelControl labelControl2;
}
}
| |
#if UNITY_EDITOR
#define NF_CLIENT_FRAME
#elif UNITY_IPHONE
#define NF_CLIENT_FRAME
#elif UNITY_ANDROID
#define NF_CLIENT_FRAME
#elif UNITY_STANDALONE_OSX
#define NF_CLIENT_FRAME
#elif UNITY_STANDALONE_WIN
#define NF_CLIENT_FRAME
#endif
//-----------------------------------------------------------------------
// <copyright file="NFCKernelModule.cs">
// Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFrame>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace NFrame
{
public class NFCKernelModule : NFIKernelModule
{
#if NF_CLIENT_FRAME
#region Instance
private static NFIKernelModule _Instance = null;
private static readonly object _syncLock = new object();
public static NFIKernelModule Instance
{
get
{
lock (_syncLock)
{
if (_Instance == null)
{
_Instance = new NFCKernelModule();
}
return _Instance;
}
}
}
#endregion
#endif
public NFCKernelModule()
{
mhtObject = new Dictionary<NFGUID, NFIObject>();
mhtClassHandleDel = new Dictionary<string, ClassHandleDel>();
#if NF_CLIENT_FRAME
mxLogicClassModule = new NFCLogicClassModule();
mxElementModule = new NFCElementModule();
#endif
}
~NFCKernelModule()
{
mhtObject = null;
#if NF_CLIENT_FRAME
mxElementModule = null;
mxLogicClassModule = null;
#endif
}
public override void Init()
{
#if NF_CLIENT_FRAME
mxLogicClassModule.Init();
mxElementModule.Init();
#endif
}
public override void AfterInit()
{
#if NF_CLIENT_FRAME
mxLogicClassModule.AfterInit();
mxElementModule.AfterInit();
#else
mxLogicClassModule = GetMng().GetModule<NFILogicClassModule>();
mxElementModule = GetMng().GetModule<NFIElementModule>();
#endif
}
public override void BeforeShut()
{
#if NF_CLIENT_FRAME
mxElementModule.BeforeShut();
mxLogicClassModule.BeforeShut();
#endif
}
public override void Shut()
{
#if NF_CLIENT_FRAME
mxElementModule.Shut();
mxLogicClassModule.Shut();
#endif
}
public override void Execute()
{
#if NF_CLIENT_FRAME
#endif
}
#if NF_CLIENT_FRAME
public override NFILogicClassModule GetLogicClassModule()
{
return mxLogicClassModule;
}
public override NFIElementModule GetElementModule()
{
return mxElementModule;
}
#endif
public override bool AddHeartBeat(NFGUID self, string strHeartBeatName, NFIHeartBeat.HeartBeatEventHandler handler, float fTime, int nCount)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetHeartBeatManager().AddHeartBeat(strHeartBeatName, fTime, nCount, handler);
}
return true;
}
public override void RegisterPropertyCallback(NFGUID self, string strPropertyName, NFIProperty.PropertyEventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetPropertyManager().RegisterCallback(strPropertyName, handler);
}
}
public override void RegisterRecordCallback(NFGUID self, string strRecordName, NFIRecord.RecordEventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetRecordManager().RegisterCallback(strRecordName, handler);
}
}
public override void RegisterClassCallBack(string strClassName, NFIObject.ClassEventHandler handler)
{
if(mhtClassHandleDel.ContainsKey(strClassName))
{
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
xHandleDel.AddDel(handler);
}
else
{
ClassHandleDel xHandleDel = new ClassHandleDel();
xHandleDel.AddDel(handler);
mhtClassHandleDel[strClassName] = xHandleDel;
}
}
public override void RegisterEventCallBack(NFGUID self, int nEventID, NFIEvent.EventHandler handler)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
//xGameObject.GetEventManager().RegisterCallback(nEventID, handler, valueList);
}
}
public override bool FindHeartBeat(NFGUID self, string strHeartBeatName)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
return xGameObject.GetHeartBeatManager().FindHeartBeat(strHeartBeatName);
}
return false;
}
public override bool RemoveHeartBeat(NFGUID self, string strHeartBeatName)
{
NFIObject xGameObject = GetObject(self);
if (null != xGameObject)
{
xGameObject.GetHeartBeatManager().RemoveHeartBeat(strHeartBeatName);
}
return true;
}
public override bool UpDate(float fTime)
{
foreach (NFGUID id in mhtObject.Keys)
{
NFIObject xGameObject = (NFIObject)mhtObject[id];
xGameObject.GetHeartBeatManager().Update(fTime);
}
return true;
}
/////////////////////////////////////////////////////////////
//public override bool AddRecordCallBack( NFGUID self, string strRecordName, RECORD_EVENT_FUNC cb );
//public override bool AddPropertyCallBack( NFGUID self, string strCriticalName, PROPERTY_EVENT_FUNC cb );
// public override bool AddClassCallBack( string strClassName, CLASS_EVENT_FUNC cb );
//
// public override bool RemoveClassCallBack( string strClassName, CLASS_EVENT_FUNC cb );
/////////////////////////////////////////////////////////////////
public override NFIObject GetObject(NFGUID ident)
{
if (null != ident && mhtObject.ContainsKey(ident))
{
return (NFIObject)mhtObject[ident];
}
return null;
}
public override NFIObject CreateObject(NFGUID self, int nContainerID, int nGroupID, string strClassName, string strConfigIndex, NFIDataList arg)
{
if (!mhtObject.ContainsKey(self))
{
NFIObject xNewObject = new NFCObject(self, nContainerID, nGroupID, strClassName, strConfigIndex);
mhtObject.Add(self, xNewObject);
NFCDataList varConfigID = new NFCDataList();
varConfigID.AddString(strConfigIndex);
xNewObject.GetPropertyManager().AddProperty("ConfigID", varConfigID);
NFCDataList varConfigClass = new NFCDataList();
varConfigClass.AddString(strClassName);
xNewObject.GetPropertyManager().AddProperty("ClassName", varConfigClass);
if (arg.Count() % 2 == 0)
{
for (int i = 0; i < arg.Count() - 1; i += 2)
{
string strPropertyName = arg.StringVal(i);
NFIDataList.VARIANT_TYPE eType = arg.GetType(i + 1);
switch (eType)
{
case NFIDataList.VARIANT_TYPE.VTYPE_INT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddInt(arg.IntVal(i+1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddFloat(arg.FloatVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddDouble(arg.DoubleVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_STRING:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddString(arg.StringVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT:
{
NFIDataList xDataList = new NFCDataList();
xDataList.AddObject(arg.ObjectVal(i + 1));
xNewObject.GetPropertyManager().AddProperty(strPropertyName, xDataList);
}
break;
default:
break;
}
}
}
InitProperty(self, strClassName);
InitRecord(self, strClassName);
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
if (null != xHandleDel && null != xHandleDel.GetHandler())
{
NFIObject.ClassEventHandler xHandlerList = xHandleDel.GetHandler();
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_CREATE, strClassName, strConfigIndex);
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_LOADDATA, strClassName, strConfigIndex);
xHandlerList(self, nContainerID, nGroupID, NFIObject.CLASS_EVENT_TYPE.OBJECT_CREATE_FINISH, strClassName, strConfigIndex);
}
//NFCLog.Instance.Log(NFCLog.LOG_LEVEL.DEBUG, "Create object: " + self.ToString() + " ClassName: " + strClassName + " SceneID: " + nContainerID + " GroupID: " + nGroupID);
return xNewObject;
}
return null;
}
public override bool DestroyObject(NFGUID self)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
string strClassName = xGameObject.ClassName();
ClassHandleDel xHandleDel = (ClassHandleDel)mhtClassHandleDel[strClassName];
if (null != xHandleDel && null != xHandleDel.GetHandler())
{
NFIObject.ClassEventHandler xHandlerList = xHandleDel.GetHandler();
xHandlerList(self, xGameObject.ContainerID(), xGameObject.GroupID(), NFIObject.CLASS_EVENT_TYPE.OBJECT_DESTROY, xGameObject.ClassName(), xGameObject.ConfigIndex());
}
mhtObject.Remove(self);
//NFCLog.Instance.Log(NFCLog.LOG_LEVEL.DEBUG, "Destroy object: " + self.ToString() + " ClassName: " + strClassName + " SceneID: " + xGameObject.ContainerID() + " GroupID: " + xGameObject.GroupID());
return true;
}
return false;
}
public override bool FindProperty(NFGUID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.FindProperty(strPropertyName);
}
return false;
}
public override bool SetPropertyInt(NFGUID self, string strPropertyName, Int64 nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyInt(strPropertyName, nValue);
}
return false;
}
public override bool SetPropertyFloat(NFGUID self, string strPropertyName, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyFloat(strPropertyName, fValue);
}
return false;
}
public override bool SetPropertyDouble(NFGUID self, string strPropertyName, double dValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyDouble(strPropertyName, dValue);
}
return false;
}
public override bool SetPropertyString(NFGUID self, string strPropertyName, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyString(strPropertyName, strValue);
}
return false;
}
public override bool SetPropertyObject(NFGUID self, string strPropertyName, NFGUID objectValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetPropertyObject(strPropertyName, objectValue);
}
return false;
}
public override Int64 QueryPropertyInt(NFGUID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyInt(strPropertyName);
}
return 0;
}
public override float QueryPropertyFloat(NFGUID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyFloat(strPropertyName);
}
return 0.0f;
}
public override double QueryPropertyDouble(NFGUID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyDouble(strPropertyName);
}
return 0.0;
}
public override string QueryPropertyString(NFGUID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyString(strPropertyName);
}
return "";
}
public override NFGUID QueryPropertyObject(NFGUID self, string strPropertyName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryPropertyObject(strPropertyName);
}
return new NFGUID();
}
public override NFIRecord FindRecord(NFGUID self, string strRecordName)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.GetRecordManager().GetRecord(strRecordName);
}
return null;
}
public override bool SetRecordInt(NFGUID self, string strRecordName, int nRow, int nCol, Int64 nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordInt(strRecordName, nRow, nCol, nValue);
}
return false;
}
public override bool SetRecordFloat(NFGUID self, string strRecordName, int nRow, int nCol, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordFloat(strRecordName, nRow, nCol, fValue);
}
return false;
}
public override bool SetRecordDouble(NFGUID self, string strRecordName, int nRow, int nCol, double dwValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordDouble(strRecordName, nRow, nCol, dwValue);
}
return false;
}
public override bool SetRecordString(NFGUID self, string strRecordName, int nRow, int nCol, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordString(strRecordName, nRow, nCol, strValue);
}
return false;
}
public override bool SetRecordObject(NFGUID self, string strRecordName, int nRow, int nCol, NFGUID objectValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.SetRecordObject(strRecordName, nRow, nCol, objectValue);
}
return false;
}
public override Int64 QueryRecordInt(NFGUID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordInt(strRecordName, nRow, nCol);
}
return 0;
}
public override float QueryRecordFloat(NFGUID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordFloat(strRecordName, nRow, nCol);
}
return 0.0f;
}
public override double QueryRecordDouble(NFGUID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordDouble(strRecordName, nRow, nCol);
}
return 0.0;
}
public override string QueryRecordString(NFGUID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordString(strRecordName, nRow, nCol);
}
return "";
}
public override NFGUID QueryRecordObject(NFGUID self, string strRecordName, int nRow, int nCol)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
return xGameObject.QueryRecordObject(strRecordName, nRow, nCol);
}
return new NFGUID();
}
public override NFIDataList GetObjectList()
{
NFIDataList varData = new NFCDataList();
foreach (KeyValuePair<NFGUID, NFIObject> kv in mhtObject)
{
varData.AddObject(kv.Key);
}
return varData;
}
public override int FindRecordRow(NFGUID self, string strRecordName, int nCol, int nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFrame.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindInt(nCol, nValue);
}
}
return -1;
}
public override int FindRecordRow(NFGUID self, string strRecordName, int nCol, float fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFrame.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindFloat(nCol, fValue);
}
}
return -1;
}
public override int FindRecordRow(NFGUID self, string strRecordName, int nCol, double fValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFrame.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindDouble(nCol, fValue);
}
}
return -1;
}
public override int FindRecordRow(NFGUID self, string strRecordName, int nCol, string strValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFrame.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindString(nCol, strValue);
}
}
return -1;
}
public override int FindRecordRow(NFGUID self, string strRecordName, int nCol, NFGUID nValue)
{
if (mhtObject.ContainsKey(self))
{
NFIObject xGameObject = (NFIObject)mhtObject[self];
NFrame.NFIRecord xRecord = xGameObject.GetRecordManager().GetRecord(strRecordName);
if (null != xRecord)
{
return xRecord.FindObject(nCol, nValue);
}
}
return -1;
}
void InitProperty(NFGUID self, string strClassName)
{
NFILogicClass xLogicClass = mxLogicClassModule.GetElement(strClassName);
NFIDataList xDataList = xLogicClass.GetPropertyManager().GetPropertyList();
for (int i = 0; i < xDataList.Count(); ++i )
{
string strPropertyName = xDataList.StringVal(i);
NFIProperty xProperty = xLogicClass.GetPropertyManager().GetProperty(strPropertyName);
NFIObject xObject = GetObject(self);
NFIPropertyManager xPropertyManager = xObject.GetPropertyManager();
xPropertyManager.AddProperty(strPropertyName, xProperty.GetData());
}
}
void InitRecord(NFGUID self, string strClassName)
{
NFILogicClass xLogicClass = mxLogicClassModule.GetElement(strClassName);
NFIDataList xDataList = xLogicClass.GetRecordManager().GetRecordList();
for (int i = 0; i < xDataList.Count(); ++i)
{
string strRecordyName = xDataList.StringVal(i);
NFIRecord xRecord = xLogicClass.GetRecordManager().GetRecord(strRecordyName);
NFIObject xObject = GetObject(self);
NFIRecordManager xRecordManager = xObject.GetRecordManager();
xRecordManager.AddRecord(strRecordyName, xRecord.GetRows(), xRecord.GetColsData());
}
}
private Dictionary<NFGUID, NFIObject> mhtObject;
private Dictionary<string, ClassHandleDel> mhtClassHandleDel;
private NFIElementModule mxElementModule;
private NFILogicClassModule mxLogicClassModule;
class ClassHandleDel
{
public ClassHandleDel()
{
mhtHandleDelList = new Dictionary<NFIObject.ClassEventHandler, string>();
}
public void AddDel(NFIObject.ClassEventHandler handler)
{
if (!mhtHandleDelList.ContainsKey(handler))
{
mhtHandleDelList.Add(handler, handler.ToString());
mHandleDel += handler;
}
}
public NFIObject.ClassEventHandler GetHandler()
{
return mHandleDel;
}
private NFIObject.ClassEventHandler mHandleDel;
private Dictionary<NFIObject.ClassEventHandler, string> mhtHandleDelList;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Versioning;
namespace System.Xml
{
// Specifies formatting options for XmlTextWriter.
internal enum Formatting
{
// No special formatting is done (this is the default).
None,
//This option causes child elements to be indented using the Indentation and IndentChar properties.
// It only indents Element Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-element-content)
// and not Mixed Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-mixed-content)
// according to the XML 1.0 definitions of these terms.
Indented,
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams
// containing XML documents that conform to the W3CExtensible Markup Language (XML) 1.0 specification
// and the Namespaces in XML specification.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal class XmlTextWriter : XmlWriter
{
//
// Private types
//
enum NamespaceState
{
Uninitialized,
NotDeclaredButInScope,
DeclaredButNotWrittenOut,
DeclaredAndWrittenOut
}
struct TagInfo
{
internal string name;
internal string prefix;
internal string defaultNs;
internal NamespaceState defaultNsState;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal int prevNsTop;
internal int prefixCount;
internal bool mixed; // whether to pretty print the contents of this element.
internal void Init(int nsTop)
{
name = null;
defaultNs = String.Empty;
defaultNsState = NamespaceState.Uninitialized;
xmlSpace = XmlSpace.None;
xmlLang = null;
prevNsTop = nsTop;
prefixCount = 0;
mixed = false;
}
}
struct Namespace
{
internal string prefix;
internal string ns;
internal bool declared;
internal int prevNsIndex;
internal void Set(string prefix, string ns, bool declared)
{
this.prefix = prefix;
this.ns = ns;
this.declared = declared;
this.prevNsIndex = -1;
}
}
enum SpecialAttr
{
None,
XmlSpace,
XmlLang,
XmlNs
};
// State machine is working through autocomplete
private enum State
{
Start,
Prolog,
PostDTD,
Element,
Attribute,
Content,
AttrOnly,
Epilog,
Error,
Closed,
}
private enum Token
{
PI,
Doctype,
Comment,
CData,
StartElement,
EndElement,
LongEndElement,
StartAttribute,
EndAttribute,
Content,
Base64,
RawData,
Whitespace,
Empty
}
//
// Fields
//
// output
TextWriter textWriter;
XmlTextEncoder xmlEncoder;
Encoding encoding;
// formatting
Formatting formatting;
bool indented; // perf - faster to check a boolean.
int indentation;
char indentChar;
// element stack
TagInfo[] stack;
int top;
// state machine for AutoComplete
State[] stateTable;
State currentState;
Token lastToken;
// Base64 content
XmlTextWriterBase64Encoder base64Encoder;
// misc
char quoteChar;
char curQuoteChar;
bool namespaces;
SpecialAttr specialAttr;
string prefixForXmlNs;
bool flush;
// namespaces
Namespace[] nsStack;
int nsTop;
Dictionary<string, int> nsHashtable;
bool useNsHashtable;
// char types
XmlCharType xmlCharType = XmlCharType.Instance;
//
// Constants and constant tables
//
const int NamespaceStackInitialSize = 8;
#if DEBUG
const int MaxNamespacesWalkCount = 3;
#else
const int MaxNamespacesWalkCount = 16;
#endif
static string[] stateName = {
"Start",
"Prolog",
"PostDTD",
"Element",
"Attribute",
"Content",
"AttrOnly",
"Epilog",
"Error",
"Closed",
};
static string[] tokenName = {
"PI",
"Doctype",
"Comment",
"CData",
"StartElement",
"EndElement",
"LongEndElement",
"StartAttribute",
"EndAttribute",
"Content",
"Base64",
"RawData",
"Whitespace",
"Empty"
};
static readonly State[] stateTableDefault = {
// State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.PI */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.Doctype */ State.PostDTD, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error,
/* Token.Comment */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.CData */ State.Content, State.Content, State.Error, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.StartElement */ State.Element, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Element,
/* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartAttribute */ State.AttrOnly, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Epilog, State.Error,
/* Token.Content */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.Base64 */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.RawData */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.Whitespace */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
};
static readonly State[] stateTableDocument = {
// State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.PI */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.Doctype */ State.Error, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error,
/* Token.Comment */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.CData */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartElement */ State.Error, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Error,
/* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartAttribute */ State.Error, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Error, State.Error,
/* Token.Content */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error,
/* Token.Base64 */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error,
/* Token.RawData */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog,
/* Token.Whitespace */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog,
};
//
// Constructors
//
internal XmlTextWriter()
{
namespaces = true;
formatting = Formatting.None;
indentation = 2;
indentChar = ' ';
// namespaces
nsStack = new Namespace[NamespaceStackInitialSize];
nsTop = -1;
// element stack
stack = new TagInfo[10];
top = 0;// 0 is an empty sentanial element
stack[top].Init(-1);
quoteChar = '"';
stateTable = stateTableDefault;
currentState = State.Start;
lastToken = Token.Empty;
}
// Creates an instance of the XmlTextWriter class using the specified stream.
public XmlTextWriter(Stream w, Encoding encoding) : this()
{
this.encoding = encoding;
if (encoding != null)
textWriter = new StreamWriter(w, encoding);
else
textWriter = new StreamWriter(w);
xmlEncoder = new XmlTextEncoder(textWriter);
xmlEncoder.QuoteChar = this.quoteChar;
}
// Creates an instance of the XmlTextWriter class using the specified TextWriter.
public XmlTextWriter(TextWriter w) : this()
{
textWriter = w;
encoding = w.Encoding;
xmlEncoder = new XmlTextEncoder(w);
xmlEncoder.QuoteChar = this.quoteChar;
}
//
// XmlTextWriter properties
//
// Gets the XmlTextWriter base stream.
public Stream BaseStream
{
get
{
StreamWriter streamWriter = textWriter as StreamWriter;
return (streamWriter == null ? null : streamWriter.BaseStream);
}
}
// Gets or sets a value indicating whether to do namespace support.
public bool Namespaces
{
get { return this.namespaces; }
set
{
if (this.currentState != State.Start)
throw new InvalidOperationException(SR.Xml_NotInWriteState);
this.namespaces = value;
}
}
// Indicates how the output is formatted.
public Formatting Formatting
{
get { return this.formatting; }
set { this.formatting = value; this.indented = value == Formatting.Indented; }
}
// Gets or sets how many IndentChars to write for each level in the hierarchy when Formatting is set to "Indented".
public int Indentation
{
get { return this.indentation; }
set
{
if (value < 0)
throw new ArgumentException(SR.Xml_InvalidIndentation);
this.indentation = value;
}
}
// Gets or sets which character to use for indenting when Formatting is set to "Indented".
public char IndentChar
{
get { return this.indentChar; }
set { this.indentChar = value; }
}
// Gets or sets which character to use to quote attribute values.
public char QuoteChar
{
get { return this.quoteChar; }
set
{
if (value != '"' && value != '\'')
{
throw new ArgumentException(SR.Xml_InvalidQuote);
}
this.quoteChar = value;
this.xmlEncoder.QuoteChar = value;
}
}
//
// XmlWriter implementation
//
// Writes out the XML declaration with the version "1.0".
public override void WriteStartDocument()
{
StartDocument(-1);
}
// Writes out the XML declaration with the version "1.0" and the standalone attribute.
public override void WriteStartDocument(bool standalone)
{
StartDocument(standalone ? 1 : 0);
}
// Closes any open elements or attributes and puts the writer back in the Start state.
public override void WriteEndDocument()
{
try
{
AutoCompleteAll();
if (this.currentState != State.Epilog)
{
if (this.currentState == State.Closed)
{
throw new ArgumentException(SR.Xml_ClosedOrError);
}
else
{
throw new ArgumentException(SR.Xml_NoRoot);
}
}
this.stateTable = stateTableDefault;
this.currentState = State.Start;
this.lastToken = Token.Empty;
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
try
{
ValidateName(name, false);
AutoComplete(Token.Doctype);
textWriter.Write("<!DOCTYPE ");
textWriter.Write(name);
if (pubid != null)
{
textWriter.Write(" PUBLIC " + quoteChar);
textWriter.Write(pubid);
textWriter.Write(quoteChar + " " + quoteChar);
textWriter.Write(sysid);
textWriter.Write(quoteChar);
}
else if (sysid != null)
{
textWriter.Write(" SYSTEM " + quoteChar);
textWriter.Write(sysid);
textWriter.Write(quoteChar);
}
if (subset != null)
{
textWriter.Write("[");
textWriter.Write(subset);
textWriter.Write("]");
}
textWriter.Write('>');
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public override void WriteStartElement(string prefix, string localName, string ns)
{
try
{
AutoComplete(Token.StartElement);
PushStack();
textWriter.Write('<');
if (this.namespaces)
{
// Propagate default namespace and mix model down the stack.
stack[top].defaultNs = stack[top - 1].defaultNs;
if (stack[top - 1].defaultNsState != NamespaceState.Uninitialized)
stack[top].defaultNsState = NamespaceState.NotDeclaredButInScope;
stack[top].mixed = stack[top - 1].mixed;
if (ns == null)
{
// use defined prefix
if (prefix != null && prefix.Length != 0 && (LookupNamespace(prefix) == -1))
{
throw new ArgumentException(SR.Xml_UndefPrefix);
}
}
else
{
if (prefix == null)
{
string definedPrefix = FindPrefix(ns);
if (definedPrefix != null)
{
prefix = definedPrefix;
}
else
{
PushNamespace(null, ns, false); // new default
}
}
else if (prefix.Length == 0)
{
PushNamespace(null, ns, false); // new default
}
else
{
if (ns.Length == 0)
{
prefix = null;
}
VerifyPrefixXml(prefix, ns);
PushNamespace(prefix, ns, false); // define
}
}
stack[top].prefix = null;
if (prefix != null && prefix.Length != 0)
{
stack[top].prefix = prefix;
textWriter.Write(prefix);
textWriter.Write(':');
}
}
else
{
if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0))
{
throw new ArgumentException(SR.Xml_NoNamespaces);
}
}
stack[top].name = localName;
textWriter.Write(localName);
}
catch
{
currentState = State.Error;
throw;
}
}
// Closes one element and pops the corresponding namespace scope.
public override void WriteEndElement()
{
InternalWriteEndElement(false);
}
// Closes one element and pops the corresponding namespace scope.
public override void WriteFullEndElement()
{
InternalWriteEndElement(true);
}
// Writes the start of an attribute.
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
try
{
AutoComplete(Token.StartAttribute);
this.specialAttr = SpecialAttr.None;
if (this.namespaces)
{
if (prefix != null && prefix.Length == 0)
{
prefix = null;
}
if (ns == XmlConst.ReservedNsXmlNs && prefix == null && localName != "xmlns")
{
prefix = "xmlns";
}
if (prefix == "xml")
{
if (localName == "lang")
{
this.specialAttr = SpecialAttr.XmlLang;
}
else if (localName == "space")
{
this.specialAttr = SpecialAttr.XmlSpace;
}
}
else if (prefix == "xmlns")
{
if (XmlConst.ReservedNsXmlNs != ns && ns != null)
{
throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs);
}
if (localName == null || localName.Length == 0)
{
localName = prefix;
prefix = null;
this.prefixForXmlNs = null;
}
else
{
this.prefixForXmlNs = localName;
}
this.specialAttr = SpecialAttr.XmlNs;
}
else if (prefix == null && localName == "xmlns")
{
if (XmlConst.ReservedNsXmlNs != ns && ns != null)
{
// add the below line back in when DOM is fixed
throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs);
}
this.specialAttr = SpecialAttr.XmlNs;
this.prefixForXmlNs = null;
}
else
{
if (ns == null)
{
// use defined prefix
if (prefix != null && (LookupNamespace(prefix) == -1))
{
throw new ArgumentException(SR.Xml_UndefPrefix);
}
}
else if (ns.Length == 0)
{
// empty namespace require null prefix
prefix = string.Empty;
}
else
{ // ns.Length != 0
VerifyPrefixXml(prefix, ns);
if (prefix != null && LookupNamespaceInCurrentScope(prefix) != -1)
{
prefix = null;
}
// Now verify prefix validity
string definedPrefix = FindPrefix(ns);
if (definedPrefix != null && (prefix == null || prefix == definedPrefix))
{
prefix = definedPrefix;
}
else
{
if (prefix == null)
{
prefix = GeneratePrefix(); // need a prefix if
}
PushNamespace(prefix, ns, false);
}
}
}
if (prefix != null && prefix.Length != 0)
{
textWriter.Write(prefix);
textWriter.Write(':');
}
}
else
{
if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0))
{
throw new ArgumentException(SR.Xml_NoNamespaces);
}
if (localName == "xml:lang")
{
this.specialAttr = SpecialAttr.XmlLang;
}
else if (localName == "xml:space")
{
this.specialAttr = SpecialAttr.XmlSpace;
}
}
xmlEncoder.StartAttribute(this.specialAttr != SpecialAttr.None);
textWriter.Write(localName);
textWriter.Write('=');
if (this.curQuoteChar != this.quoteChar)
{
this.curQuoteChar = this.quoteChar;
xmlEncoder.QuoteChar = this.quoteChar;
}
textWriter.Write(this.curQuoteChar);
}
catch
{
currentState = State.Error;
throw;
}
}
// Closes the attribute opened by WriteStartAttribute.
public override void WriteEndAttribute()
{
try
{
AutoComplete(Token.EndAttribute);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out a <![CDATA[...]]> block containing the specified text.
public override void WriteCData(string text)
{
try
{
AutoComplete(Token.CData);
if (null != text && text.IndexOf("]]>", StringComparison.Ordinal) >= 0)
{
throw new ArgumentException(SR.Xml_InvalidCDataChars);
}
textWriter.Write("<![CDATA[");
if (null != text)
{
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("]]>");
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out a comment <!--...--> containing the specified text.
public override void WriteComment(string text)
{
try
{
if (null != text && (text.IndexOf("--", StringComparison.Ordinal) >= 0 || (text.Length != 0 && text[text.Length - 1] == '-')))
{
throw new ArgumentException(SR.Xml_InvalidCommentChars);
}
AutoComplete(Token.Comment);
textWriter.Write("<!--");
if (null != text)
{
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("-->");
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public override void WriteProcessingInstruction(string name, string text)
{
try
{
if (null != text && text.IndexOf("?>", StringComparison.Ordinal) >= 0)
{
throw new ArgumentException(SR.Xml_InvalidPiChars);
}
if (0 == String.Compare(name, "xml", StringComparison.OrdinalIgnoreCase) && this.stateTable == stateTableDocument)
{
throw new ArgumentException(SR.Xml_DupXmlDecl);
}
AutoComplete(Token.PI);
InternalWriteProcessingInstruction(name, text);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out an entity reference as follows: "&"+name+";".
public override void WriteEntityRef(string name)
{
try
{
ValidateName(name, false);
AutoComplete(Token.Content);
xmlEncoder.WriteEntityRef(name);
}
catch
{
currentState = State.Error;
throw;
}
}
// Forces the generation of a character entity for the specified Unicode character value.
public override void WriteCharEntity(char ch)
{
try
{
AutoComplete(Token.Content);
xmlEncoder.WriteCharEntity(ch);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the given whitespace.
public override void WriteWhitespace(string ws)
{
try
{
if (null == ws)
{
ws = String.Empty;
}
if (!xmlCharType.IsOnlyWhitespace(ws))
{
throw new ArgumentException(SR.Xml_NonWhitespace);
}
AutoComplete(Token.Whitespace);
xmlEncoder.Write(ws);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified text content.
public override void WriteString(string text)
{
try
{
if (null != text && text.Length != 0)
{
AutoComplete(Token.Content);
xmlEncoder.Write(text);
}
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified surrogate pair as a character entity.
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
try
{
AutoComplete(Token.Content);
xmlEncoder.WriteSurrogateCharEntity(lowChar, highChar);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified text content.
public override void WriteChars(Char[] buffer, int index, int count)
{
try
{
AutoComplete(Token.Content);
xmlEncoder.Write(buffer, index, count);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes raw markup from the specified character buffer.
public override void WriteRaw(Char[] buffer, int index, int count)
{
try
{
AutoComplete(Token.RawData);
xmlEncoder.WriteRaw(buffer, index, count);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes raw markup from the specified character string.
public override void WriteRaw(String data)
{
try
{
AutoComplete(Token.RawData);
xmlEncoder.WriteRawWithSurrogateChecking(data);
}
catch
{
currentState = State.Error;
throw;
}
}
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public override void WriteBase64(byte[] buffer, int index, int count)
{
try
{
if (!this.flush)
{
AutoComplete(Token.Base64);
}
this.flush = true;
// No need for us to explicitly validate the args. The StreamWriter will do
// it for us.
if (null == this.base64Encoder)
{
this.base64Encoder = new XmlTextWriterBase64Encoder(xmlEncoder);
}
// Encode will call WriteRaw to write out the encoded characters
this.base64Encoder.Encode(buffer, index, count);
}
catch
{
currentState = State.Error;
throw;
}
}
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public override void WriteBinHex(byte[] buffer, int index, int count)
{
try
{
AutoComplete(Token.Content);
BinHexEncoder.Encode(buffer, index, count, this);
}
catch
{
currentState = State.Error;
throw;
}
}
// Returns the state of the XmlWriter.
public override WriteState WriteState
{
get
{
switch (this.currentState)
{
case State.Start:
return WriteState.Start;
case State.Prolog:
case State.PostDTD:
return WriteState.Prolog;
case State.Element:
return WriteState.Element;
case State.Attribute:
case State.AttrOnly:
return WriteState.Attribute;
case State.Content:
case State.Epilog:
return WriteState.Content;
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
default:
Debug.Assert(false);
return WriteState.Error;
}
}
}
// Disposes the XmlWriter and the underlying stream/TextWriter.
protected override void Dispose(bool disposing)
{
if (disposing && this.currentState != State.Closed)
{
try
{
AutoCompleteAll();
}
catch
{ // never fail
}
finally
{
this.currentState = State.Closed;
textWriter.Dispose();
}
}
base.Dispose(disposing);
}
// Flushes whatever is in the buffer to the underlying stream/TextWriter and flushes the underlying stream/TextWriter.
public override void Flush()
{
textWriter.Flush();
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name
public override void WriteName(string name)
{
try
{
AutoComplete(Token.Content);
InternalWriteName(name, false);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public override void WriteQualifiedName(string localName, string ns)
{
try
{
AutoComplete(Token.Content);
if (this.namespaces)
{
if (ns != null && ns.Length != 0 && ns != stack[top].defaultNs)
{
string prefix = FindPrefix(ns);
if (prefix == null)
{
if (this.currentState != State.Attribute)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
prefix = GeneratePrefix(); // need a prefix if
PushNamespace(prefix, ns, false);
}
if (prefix.Length != 0)
{
InternalWriteName(prefix, true);
textWriter.Write(':');
}
}
}
else if (ns != null && ns.Length != 0)
{
throw new ArgumentException(SR.Xml_NoNamespaces);
}
InternalWriteName(localName, true);
}
catch
{
currentState = State.Error;
throw;
}
}
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public override string LookupPrefix(string ns)
{
if (ns == null || ns.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
string s = FindPrefix(ns);
if (s == null && ns == stack[top].defaultNs)
{
s = string.Empty;
}
return s;
}
// Gets an XmlSpace representing the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
for (int i = top; i > 0; i--)
{
XmlSpace xs = stack[i].xmlSpace;
if (xs != XmlSpace.None)
return xs;
}
return XmlSpace.None;
}
}
// Gets the current xml:lang scope.
public override string XmlLang
{
get
{
for (int i = top; i > 0; i--)
{
String xlang = stack[i].xmlLang;
if (xlang != null)
return xlang;
}
return null;
}
}
// Writes out the specified name, ensuring it is a valid NmToken
// according to the XML specification (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public override void WriteNmToken(string name)
{
try
{
AutoComplete(Token.Content);
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
if (!ValidateNames.IsNmtokenNoNamespaces(name))
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name));
}
textWriter.Write(name);
}
catch
{
currentState = State.Error;
throw;
}
}
//
// Private implementation methods
//
void StartDocument(int standalone)
{
try
{
if (this.currentState != State.Start)
{
throw new InvalidOperationException(SR.Xml_NotTheFirst);
}
this.stateTable = stateTableDocument;
this.currentState = State.Prolog;
StringBuilder bufBld = new StringBuilder(128);
bufBld.Append("version=" + quoteChar + "1.0" + quoteChar);
if (this.encoding != null)
{
bufBld.Append(" encoding=");
bufBld.Append(quoteChar);
bufBld.Append(this.encoding.WebName);
bufBld.Append(quoteChar);
}
if (standalone >= 0)
{
bufBld.Append(" standalone=");
bufBld.Append(quoteChar);
bufBld.Append(standalone == 0 ? "no" : "yes");
bufBld.Append(quoteChar);
}
InternalWriteProcessingInstruction("xml", bufBld.ToString());
}
catch
{
currentState = State.Error;
throw;
}
}
void AutoComplete(Token token)
{
if (this.currentState == State.Closed)
{
throw new InvalidOperationException(SR.Xml_Closed);
}
else if (this.currentState == State.Error)
{
throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], stateName[(int)State.Error]));
}
State newState = this.stateTable[(int)token * 8 + (int)this.currentState];
if (newState == State.Error)
{
throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], stateName[(int)this.currentState]));
}
switch (token)
{
case Token.Doctype:
if (this.indented && this.currentState != State.Start)
{
Indent(false);
}
break;
case Token.StartElement:
case Token.Comment:
case Token.PI:
case Token.CData:
if (this.currentState == State.Attribute)
{
WriteEndAttributeQuote();
WriteEndStartTag(false);
}
else if (this.currentState == State.Element)
{
WriteEndStartTag(false);
}
if (token == Token.CData)
{
stack[top].mixed = true;
}
else if (this.indented && this.currentState != State.Start)
{
Indent(false);
}
break;
case Token.EndElement:
case Token.LongEndElement:
if (this.flush)
{
FlushEncoders();
}
if (this.currentState == State.Attribute)
{
WriteEndAttributeQuote();
}
if (this.currentState == State.Content)
{
token = Token.LongEndElement;
}
else
{
WriteEndStartTag(token == Token.EndElement);
}
if (stateTableDocument == this.stateTable && top == 1)
{
newState = State.Epilog;
}
break;
case Token.StartAttribute:
if (this.flush)
{
FlushEncoders();
}
if (this.currentState == State.Attribute)
{
WriteEndAttributeQuote();
textWriter.Write(' ');
}
else if (this.currentState == State.Element)
{
textWriter.Write(' ');
}
break;
case Token.EndAttribute:
if (this.flush)
{
FlushEncoders();
}
WriteEndAttributeQuote();
break;
case Token.Whitespace:
case Token.Content:
case Token.RawData:
case Token.Base64:
if (token != Token.Base64 && this.flush)
{
FlushEncoders();
}
if (this.currentState == State.Element && this.lastToken != Token.Content)
{
WriteEndStartTag(false);
}
if (newState == State.Content)
{
stack[top].mixed = true;
}
break;
default:
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
this.currentState = newState;
this.lastToken = token;
}
void AutoCompleteAll()
{
if (this.flush)
{
FlushEncoders();
}
while (top > 0)
{
WriteEndElement();
}
}
void InternalWriteEndElement(bool longFormat)
{
try
{
if (top <= 0)
{
throw new InvalidOperationException(SR.Xml_NoStartTag);
}
// if we are in the element, we need to close it.
AutoComplete(longFormat ? Token.LongEndElement : Token.EndElement);
if (this.lastToken == Token.LongEndElement)
{
if (this.indented)
{
Indent(true);
}
textWriter.Write('<');
textWriter.Write('/');
if (this.namespaces && stack[top].prefix != null)
{
textWriter.Write(stack[top].prefix);
textWriter.Write(':');
}
textWriter.Write(stack[top].name);
textWriter.Write('>');
}
// pop namespaces
int prevNsTop = stack[top].prevNsTop;
if (useNsHashtable && prevNsTop < nsTop)
{
PopNamespaces(prevNsTop + 1, nsTop);
}
nsTop = prevNsTop;
top--;
}
catch
{
currentState = State.Error;
throw;
}
}
void WriteEndStartTag(bool empty)
{
xmlEncoder.StartAttribute(false);
for (int i = nsTop; i > stack[top].prevNsTop; i--)
{
if (!nsStack[i].declared)
{
textWriter.Write(" xmlns");
textWriter.Write(':');
textWriter.Write(nsStack[i].prefix);
textWriter.Write('=');
textWriter.Write(this.quoteChar);
xmlEncoder.Write(nsStack[i].ns);
textWriter.Write(this.quoteChar);
}
}
// Default
if ((stack[top].defaultNs != stack[top - 1].defaultNs) &&
(stack[top].defaultNsState == NamespaceState.DeclaredButNotWrittenOut))
{
textWriter.Write(" xmlns");
textWriter.Write('=');
textWriter.Write(this.quoteChar);
xmlEncoder.Write(stack[top].defaultNs);
textWriter.Write(this.quoteChar);
stack[top].defaultNsState = NamespaceState.DeclaredAndWrittenOut;
}
xmlEncoder.EndAttribute();
if (empty)
{
textWriter.Write(" /");
}
textWriter.Write('>');
}
void WriteEndAttributeQuote()
{
if (this.specialAttr != SpecialAttr.None)
{
// Ok, now to handle xmlspace, etc.
HandleSpecialAttribute();
}
xmlEncoder.EndAttribute();
textWriter.Write(this.curQuoteChar);
}
void Indent(bool beforeEndElement)
{
// pretty printing.
if (top == 0)
{
textWriter.WriteLine();
}
else if (!stack[top].mixed)
{
textWriter.WriteLine();
int i = beforeEndElement ? top - 1 : top;
for (i *= this.indentation; i > 0; i--)
{
textWriter.Write(this.indentChar);
}
}
}
// pushes new namespace scope, and returns generated prefix, if one
// was needed to resolve conflicts.
void PushNamespace(string prefix, string ns, bool declared)
{
if (XmlConst.ReservedNsXmlNs == ns)
{
throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace);
}
if (prefix == null)
{
switch (stack[top].defaultNsState)
{
case NamespaceState.DeclaredButNotWrittenOut:
Debug.Assert(declared == true, "Unexpected situation!!");
// the first namespace that the user gave us is what we
// like to keep.
break;
case NamespaceState.Uninitialized:
case NamespaceState.NotDeclaredButInScope:
// we now got a brand new namespace that we need to remember
stack[top].defaultNs = ns;
break;
default:
Debug.Assert(false, "Should have never come here");
return;
}
stack[top].defaultNsState = (declared ? NamespaceState.DeclaredAndWrittenOut : NamespaceState.DeclaredButNotWrittenOut);
}
else
{
if (prefix.Length != 0 && ns.Length == 0)
{
throw new ArgumentException(SR.Xml_PrefixForEmptyNs);
}
int existingNsIndex = LookupNamespace(prefix);
if (existingNsIndex != -1 && nsStack[existingNsIndex].ns == ns)
{
// it is already in scope.
if (declared)
{
nsStack[existingNsIndex].declared = true;
}
}
else
{
// see if prefix conflicts for the current element
if (declared)
{
if (existingNsIndex != -1 && existingNsIndex > stack[top].prevNsTop)
{
nsStack[existingNsIndex].declared = true; // old one is silenced now
}
}
AddNamespace(prefix, ns, declared);
}
}
}
void AddNamespace(string prefix, string ns, bool declared)
{
int nsIndex = ++nsTop;
if (nsIndex == nsStack.Length)
{
Namespace[] newStack = new Namespace[nsIndex * 2];
Array.Copy(nsStack, newStack, nsIndex);
nsStack = newStack;
}
nsStack[nsIndex].Set(prefix, ns, declared);
if (useNsHashtable)
{
AddToNamespaceHashtable(nsIndex);
}
else if (nsIndex == MaxNamespacesWalkCount)
{
// add all
nsHashtable = new Dictionary<string, int>(new SecureStringHasher());
for (int i = 0; i <= nsIndex; i++)
{
AddToNamespaceHashtable(i);
}
useNsHashtable = true;
}
}
void AddToNamespaceHashtable(int namespaceIndex)
{
string prefix = nsStack[namespaceIndex].prefix;
int existingNsIndex;
if (nsHashtable.TryGetValue(prefix, out existingNsIndex))
{
nsStack[namespaceIndex].prevNsIndex = existingNsIndex;
}
nsHashtable[prefix] = namespaceIndex;
}
private void PopNamespaces(int indexFrom, int indexTo)
{
Debug.Assert(useNsHashtable);
for (int i = indexTo; i >= indexFrom; i--)
{
Debug.Assert(nsHashtable.ContainsKey(nsStack[i].prefix));
if (nsStack[i].prevNsIndex == -1)
{
nsHashtable.Remove(nsStack[i].prefix);
}
else
{
nsHashtable[nsStack[i].prefix] = nsStack[i].prevNsIndex;
}
}
}
string GeneratePrefix()
{
int temp = stack[top].prefixCount++ + 1;
return "d" + top.ToString("d", CultureInfo.InvariantCulture)
+ "p" + temp.ToString("d", CultureInfo.InvariantCulture);
}
void InternalWriteProcessingInstruction(string name, string text)
{
textWriter.Write("<?");
ValidateName(name, false);
textWriter.Write(name);
textWriter.Write(' ');
if (null != text)
{
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("?>");
}
int LookupNamespace(string prefix)
{
if (useNsHashtable)
{
int nsIndex;
if (nsHashtable.TryGetValue(prefix, out nsIndex))
{
return nsIndex;
}
}
else
{
for (int i = nsTop; i >= 0; i--)
{
if (nsStack[i].prefix == prefix)
{
return i;
}
}
}
return -1;
}
int LookupNamespaceInCurrentScope(string prefix)
{
if (useNsHashtable)
{
int nsIndex;
if (nsHashtable.TryGetValue(prefix, out nsIndex))
{
if (nsIndex > stack[top].prevNsTop)
{
return nsIndex;
}
}
}
else
{
for (int i = nsTop; i > stack[top].prevNsTop; i--)
{
if (nsStack[i].prefix == prefix)
{
return i;
}
}
}
return -1;
}
string FindPrefix(string ns)
{
for (int i = nsTop; i >= 0; i--)
{
if (nsStack[i].ns == ns)
{
if (LookupNamespace(nsStack[i].prefix) == i)
{
return nsStack[i].prefix;
}
}
}
return null;
}
// There are three kind of strings we write out - Name, LocalName and Prefix.
// Both LocalName and Prefix can be represented with NCName == false and Name
// can be represented as NCName == true
void InternalWriteName(string name, bool isNCName)
{
ValidateName(name, isNCName);
textWriter.Write(name);
}
// This method is used for validation of the DOCTYPE, processing instruction and entity names plus names
// written out by the user via WriteName and WriteQualifiedName.
// Unfortunatelly the names of elements and attributes are not validated by the XmlTextWriter.
// Also this method does not check wheather the character after ':' is a valid start name character. It accepts
// all valid name characters at that position. This can't be changed because of backwards compatibility.
private unsafe void ValidateName(string name, bool isNCName)
{
if (name == null || name.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyName);
}
int nameLength = name.Length;
// Namespaces supported
if (namespaces)
{
// We can't use ValidateNames.ParseQName here because of backwards compatibility bug we need to preserve.
// The bug is that the character after ':' is validated only as a NCName characters instead of NCStartName.
int colonPosition = -1;
// Parse NCName (may be prefix, may be local name)
int position = ValidateNames.ParseNCName(name);
Continue:
if (position == nameLength)
{
return;
}
// we have prefix:localName
if (name[position] == ':')
{
if (!isNCName)
{
// first colon in qname
if (colonPosition == -1)
{
// make sure it is not the first or last characters
if (position > 0 && position + 1 < nameLength)
{
colonPosition = position;
// Because of the back-compat bug (described above) parse the rest as Nmtoken
position++;
position += ValidateNames.ParseNmtoken(name, position);
goto Continue;
}
}
}
}
}
// Namespaces not supported
else
{
if (ValidateNames.IsNameNoNamespaces(name))
{
return;
}
}
throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name));
}
void HandleSpecialAttribute()
{
string value = xmlEncoder.AttributeValue;
switch (this.specialAttr)
{
case SpecialAttr.XmlLang:
stack[top].xmlLang = value;
break;
case SpecialAttr.XmlSpace:
// validate XmlSpace attribute
value = XmlConvertEx.TrimString(value);
if (value == "default")
{
stack[top].xmlSpace = XmlSpace.Default;
}
else if (value == "preserve")
{
stack[top].xmlSpace = XmlSpace.Preserve;
}
else
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidXmlSpace, value));
}
break;
case SpecialAttr.XmlNs:
VerifyPrefixXml(this.prefixForXmlNs, value);
PushNamespace(this.prefixForXmlNs, value, true);
break;
}
}
void VerifyPrefixXml(string prefix, string ns)
{
if (prefix != null && prefix.Length == 3)
{
if (
(prefix[0] == 'x' || prefix[0] == 'X') &&
(prefix[1] == 'm' || prefix[1] == 'M') &&
(prefix[2] == 'l' || prefix[2] == 'L')
)
{
if (XmlConst.ReservedNsXml != ns)
{
throw new ArgumentException(SR.Xml_InvalidPrefix);
}
}
}
}
void PushStack()
{
if (top == stack.Length - 1)
{
TagInfo[] na = new TagInfo[stack.Length + 10];
if (top > 0) Array.Copy(stack, na, top + 1);
stack = na;
}
top++; // Move up stack
stack[top].Init(nsTop);
}
void FlushEncoders()
{
if (null != this.base64Encoder)
{
// The Flush will call WriteRaw to write out the rest of the encoded characters
this.base64Encoder.Flush();
}
this.flush = false;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UMA;
namespace UMA.Examples
{
public class UMACrowdRandomSet : ScriptableObject
{
public CrowdRaceData data;
[System.Serializable]
public class CrowdRaceData
{
public string raceID;
public CrowdSlotElement[] slotElements;
}
[System.Serializable]
public class CrowdSlotElement
{
public string Info;
public CrowdSlotData[] possibleSlots;
public string requirement;
public string condition;
}
[System.Serializable]
public class CrowdSlotData
{
public string slotID;
public bool useSharedOverlayList;
public int overlayListSource;
public CrowdOverlayElement[] overlayElements;
}
[System.Serializable]
public class CrowdOverlayElement
{
public CrowdOverlayData[] possibleOverlays;
}
public enum OverlayType
{
Unknown,
Random,
Texture,
Color,
Skin,
Hair,
}
public enum ChannelUse
{
None,
Color,
InverseColor
}
[System.Serializable]
public class CrowdOverlayData
{
public string overlayID;
public Color maxRGB;
public Color minRGB;
public bool useSkinColor;
public bool useHairColor;
public float hairColorMultiplier;
public ChannelUse colorChannelUse;
public int colorChannel;
public OverlayType overlayType;
public void UpdateVersion()
{
if (overlayType == UMACrowdRandomSet.OverlayType.Unknown)
{
if (useSkinColor)
{
overlayType = UMACrowdRandomSet.OverlayType.Skin;
}
else if (useHairColor)
{
overlayType = UMACrowdRandomSet.OverlayType.Hair;
}
else
{
if (minRGB == maxRGB)
{
if (minRGB == Color.white)
{
overlayType = UMACrowdRandomSet.OverlayType.Texture;
}
else
{
overlayType = UMACrowdRandomSet.OverlayType.Color;
}
}
else
{
overlayType = UMACrowdRandomSet.OverlayType.Random;
}
}
}
}
}
public static void Apply(UMA.UMAData umaData, CrowdRaceData race, Color skinColor, Color HairColor, Color Shine, HashSet<string> Keywords, UMAContext context)
{
Apply(umaData, race, skinColor, HairColor, Shine, Keywords, context.slotLibrary, context.overlayLibrary);
}
public static void Apply(UMA.UMAData umaData, CrowdRaceData race, Color skinColor, Color HairColor, Color Shine, HashSet<string> Keywords, SlotLibraryBase slotLibrary, OverlayLibraryBase overlayLibrary)
{
var slotParts = new HashSet<string>();
umaData.umaRecipe.slotDataList = new SlotData[race.slotElements.Length];
for (int i = 0; i < race.slotElements.Length; i++)
{
var currentElement = race.slotElements[i];
if (!string.IsNullOrEmpty(currentElement.requirement) && !slotParts.Contains(currentElement.requirement)) continue;
if (!string.IsNullOrEmpty(currentElement.condition))
{
if (currentElement.condition.StartsWith("!"))
{
if (Keywords.Contains(currentElement.condition.Substring(1))) continue;
}
else
{
if (!Keywords.Contains(currentElement.condition)) continue;
}
}
if (currentElement.possibleSlots.Length == 0) continue;
int randomResult = Random.Range(0, currentElement.possibleSlots.Length);
var slot = currentElement.possibleSlots[randomResult];
if (string.IsNullOrEmpty(slot.slotID)) continue;
slotParts.Add(slot.slotID);
SlotData slotData;
if (slot.useSharedOverlayList && slot.overlayListSource >= 0 && slot.overlayListSource < i)
{
slotData = slotLibrary.InstantiateSlot(slot.slotID, umaData.umaRecipe.slotDataList[slot.overlayListSource].GetOverlayList());
}
else
{
if (slot.useSharedOverlayList)
{
Debug.LogError("UMA Crowd: Invalid overlayListSource for " + slot.slotID);
}
slotData = slotLibrary.InstantiateSlot(slot.slotID);
}
umaData.umaRecipe.slotDataList[i] = slotData;
for (int overlayIdx = 0; overlayIdx < slot.overlayElements.Length; overlayIdx++)
{
var currentOverlayElement = slot.overlayElements[overlayIdx];
randomResult = Random.Range(0, currentOverlayElement.possibleOverlays.Length);
var overlay = currentOverlayElement.possibleOverlays[randomResult];
if (string.IsNullOrEmpty(overlay.overlayID)) continue;
overlay.UpdateVersion();
slotParts.Add(overlay.overlayID);
Color overlayColor = Color.black;
var overlayData = overlayLibrary.InstantiateOverlay(overlay.overlayID, overlayColor);
switch (overlay.overlayType)
{
case UMACrowdRandomSet.OverlayType.Color:
overlayColor = overlay.minRGB;
overlayData.colorData.color = overlayColor;
break;
case UMACrowdRandomSet.OverlayType.Texture:
overlayColor = Color.white;
overlayData.colorData.color = overlayColor;
break;
case UMACrowdRandomSet.OverlayType.Hair:
overlayColor = HairColor * overlay.hairColorMultiplier;
overlayColor.a = 1.0f;
overlayData.colorData.color = overlayColor;
break;
case UMACrowdRandomSet.OverlayType.Skin:
overlayColor = skinColor;// + new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), 1);
overlayData.colorData.color = overlayColor;
if (overlayData.colorData.channelAdditiveMask.Length > 2)
{
overlayData.colorData.channelAdditiveMask[2] = Shine;
}
else
{
break;
}
break;
case UMACrowdRandomSet.OverlayType.Random:
{
float randomShine = Random.Range(0.05f, 0.25f);
float randomMetal = Random.Range(0.1f, 0.3f);
overlayColor = new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), Random.Range(overlay.minRGB.a, overlay.maxRGB.a));
overlayData.colorData.color = overlayColor;
if (overlayData.colorData.channelAdditiveMask.Length > 2)
{
overlayData.colorData.channelAdditiveMask[2] = new Color(randomMetal, randomMetal, randomMetal, randomShine);
}
}
break;
default:
Debug.LogError("Unknown RandomSet overlayType: "+((int)overlay.overlayType));
overlayColor = overlay.minRGB;
overlayData.colorData.color = overlayColor;
break;
}
slotData.AddOverlay(overlayData);
if (overlay.colorChannelUse != ChannelUse.None)
{
overlayColor.a *= overlay.minRGB.a;
if (overlay.colorChannelUse == ChannelUse.InverseColor)
{
Vector3 color = new Vector3(overlayColor.r, overlayColor.g, overlayColor.b);
var len = color.magnitude;
if (len < 1f) len = 1f;
color = new Vector3(1.001f, 1.001f, 1.001f) - color;
color = color.normalized* len;
overlayColor = new Color(color.x, color.y, color.z, overlayColor.a);
}
overlayData.SetColor(overlay.colorChannel, overlayColor);
}
}
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
[CustomEditor (typeof(PlatformSpecifics))]
public class PlatformSpecificsEditor : Editor {
public Texture2D addTextureUp;
public Texture2D addTextureDown;
public Texture2D removeTextureUp;
public Texture2D removeTextureDown;
public Texture2D moveItemAboveUp;
public Texture2D moveItemAboveDown;
public Texture2D moveItemBelowUp;
public Texture2D moveItemBelowDown;
[SerializeField] GUIStyle addButtonStyle;
[SerializeField] GUIStyle removeButtonStyle;
[SerializeField] GUIStyle moveItemAboveStyle;
[SerializeField] GUIStyle moveItemBelowStyle;
[SerializeField] GUIStyle enumPopupStyle;
delegate void DrawArray<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection);
delegate T Constructor<T>();
PlatformSpecifics specifics;
bool showRestrictPlatforms = false;
bool showMaterials = false;
bool showLocalScalePerPlatform = false;
bool showLocalScalePerAspectRatio = false;
bool showLocalPositionPerPlatform = false;
bool showLocalPositionPerAspectRatio = false;
bool showAnchorPositions = false;
bool showFonts = false;
bool showTextMeshText = false;
void OnEnable() {
GetAssetPaths();
specifics = target as PlatformSpecifics;
specifics.Init();
addButtonStyle = new GUIStyle();
addButtonStyle.normal.background = addTextureUp;
addButtonStyle.active.background = addTextureDown;
addButtonStyle.fixedWidth = addTextureUp.width;
addButtonStyle.fixedHeight = addTextureUp.height;
addButtonStyle.margin = new RectOffset(4,4,4,4);
removeButtonStyle = new GUIStyle(addButtonStyle); //Inherit margin and fixedWidth/Height from addButtonStyle
removeButtonStyle.normal.background = removeTextureUp;
removeButtonStyle.active.background = removeTextureDown;
moveItemAboveStyle = new GUIStyle(addButtonStyle); //Inherit margin and fixedWidth/Height from addButtonStyle
moveItemAboveStyle.normal.background = moveItemAboveUp;
moveItemAboveStyle.active.background = moveItemAboveDown;
moveItemBelowStyle = new GUIStyle(addButtonStyle); //Inherit margin and fixedWidth/Height from addButtonStyle
moveItemBelowStyle.normal.background = moveItemBelowUp;
moveItemBelowStyle.active.background = moveItemBelowDown;
showRestrictPlatforms = (specifics.restrictPlatform != null && specifics.restrictPlatform.Length > 0);
showMaterials = (specifics.materialPerPlatform != null && specifics.materialPerPlatform.Length > 0);
showLocalScalePerPlatform = (specifics.localScalePerPlatform != null && specifics.localScalePerPlatform.Length > 0);
showLocalScalePerAspectRatio = (specifics.localScalePerAspectRatio != null && specifics.localScalePerAspectRatio.Length > 0);
showLocalPositionPerPlatform = (specifics.localPositionPerPlatform != null && specifics.localPositionPerPlatform.Length > 0);
showLocalPositionPerAspectRatio = (specifics.localPositionPerAspectRatio != null && specifics.localPositionPerAspectRatio.Length > 0);
showAnchorPositions = (specifics.anchorPositions != null && specifics.anchorPositions.Length > 0);
showFonts = (specifics.fontPerPlatform != null && specifics.fontPerPlatform.Length > 0);
showTextMeshText = (specifics.textMeshTextPerPlatform != null && specifics.textMeshTextPerPlatform.Length > 0);
}
void GetAssetPaths()
{
string path = string.Empty;
int index;
foreach(string assetPath in AssetDatabase.GetAllAssetPaths())
{
index = assetPath.IndexOf("MultiPlatformToolSuite");
if(index >= 0)
{
path = assetPath.Substring(0, index);
break;
}
}
string editorPath = path + "MultiPlatformToolSuite" + Path.DirectorySeparatorChar + "Editor" + Path.DirectorySeparatorChar;
path = editorPath + "Textures" + Path.DirectorySeparatorChar;
addTextureUp = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "editorAddButtonUp.tga", typeof(Texture2D));
addTextureDown = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "editorAddButtonDown.tga", typeof(Texture2D));
removeTextureUp = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "editorRemoveButtonUp.tga", typeof(Texture2D));
removeTextureDown = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "editorRemoveButtonDown.tga", typeof(Texture2D));
moveItemAboveUp = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "moveItemAboveUp.tga", typeof(Texture2D));
moveItemAboveDown = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "moveItemAboveDown.tga", typeof(Texture2D));
moveItemBelowUp = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "moveItemBelowUp.tga", typeof(Texture2D));
moveItemBelowDown = (Texture2D) AssetDatabase.LoadAssetAtPath(path + "moveItemBelowDown.tga", typeof(Texture2D));
}
void GatherStyles() {
if(enumPopupStyle == null) {
enumPopupStyle = new GUIStyle(EditorStyles.popup);
enumPopupStyle.fontStyle = FontStyle.Bold;
enumPopupStyle.fontSize = 10;
enumPopupStyle.fixedHeight = 18;
}
}
public override void OnInspectorGUI() {
//Styles that we derive from EditorStyles can't be initialized in OnEnable (causes null-ref)
GatherStyles();
GUILayout.Space(4f);
//Draw restrict to platforms
DrawSection<Platform>
(ref showRestrictPlatforms,
"Restrict to Platforms",
ref specifics.restrictPlatform,
DrawRestrictToPlatforms<Platform>,
() => {return Platform.Standalone;}, true);
//Draw materials per platform
DrawSection<PlatformSpecifics.MaterialPerPlatform>
(ref showMaterials,
"Materials",
ref specifics.materialPerPlatform,
DrawMaterials<PlatformSpecifics.MaterialPerPlatform>,
() => {return new PlatformSpecifics.MaterialPerPlatform(Platform.Standalone, null);}, true);
//Draw local scale per platform
DrawSection<PlatformSpecifics.LocalScalePerPlatform>
(ref showLocalScalePerPlatform,
"Local Scale per Platform",
ref specifics.localScalePerPlatform,
DrawLocalScalePerPlatform<PlatformSpecifics.LocalScalePerPlatform>,
() => {return new PlatformSpecifics.LocalScalePerPlatform(Platform.Standalone, Vector3.zero);}, true);
//Draw local scale per aspect ratio
DrawSection<PlatformSpecifics.LocalScalePerAspectRatio>
(ref showLocalScalePerAspectRatio,
"Local Scale per Aspect Ratio",
ref specifics.localScalePerAspectRatio,
DrawLocalScalePerAspectRatio<PlatformSpecifics.LocalScalePerAspectRatio>,
() => {return new PlatformSpecifics.LocalScalePerAspectRatio(AspectRatio.Aspect4by3, Vector3.zero);}, true);
//Draw local position per platform
DrawSection<PlatformSpecifics.LocalPositionPerPlatform>
(ref showLocalPositionPerPlatform,
"Local Position per Platform",
ref specifics.localPositionPerPlatform,
DrawLocalPositionPerPlatform<PlatformSpecifics.LocalPositionPerPlatform>,
() => {return new PlatformSpecifics.LocalPositionPerPlatform(Platform.Standalone, Vector3.zero);}, true);
//Draw local position per aspect ratio
DrawSection<PlatformSpecifics.LocalPositionPerAspectRatio>
(ref showLocalPositionPerAspectRatio,
"Local Position per Aspect Ratio",
ref specifics.localPositionPerAspectRatio,
DrawLocalPositionPerAspectRatio<PlatformSpecifics.LocalPositionPerAspectRatio>,
() => {return new PlatformSpecifics.LocalPositionPerAspectRatio(AspectRatio.Aspect4by3, Vector3.zero);}, true);
//Draw anchor positions
#if UNITY_4_6
if (specifics.GetComponent<RectTransform>() == null)
{
DrawSection<PlatformSpecifics.AnchorPosition>
(ref showAnchorPositions,
"Anchor Position",
ref specifics.anchorPositions,
DrawAnchorPositions<PlatformSpecifics.AnchorPosition>,
() => {return new PlatformSpecifics.AnchorPosition(HorizontalAlignments.Left, VerticalAlignments.Top, false, false, false, false, Vector3.zero);}, false);
}
#else
DrawSection<PlatformSpecifics.AnchorPosition>
(ref showAnchorPositions,
"Anchor Position",
ref specifics.anchorPositions,
DrawAnchorPositions<PlatformSpecifics.AnchorPosition>,
() => {return new PlatformSpecifics.AnchorPosition(HorizontalAlignments.Left, VerticalAlignments.Top, false, false, false, false, Vector3.zero);}, false);
#endif
//Draw font per platform
DrawSection<PlatformSpecifics.FontPerPlatform>
(ref showFonts,
"Fonts",
ref specifics.fontPerPlatform,
DrawFonts<PlatformSpecifics.FontPerPlatform>,
() => {return new PlatformSpecifics.FontPerPlatform(Platform.Standalone, null, null);}, true);
//Draw text mesh text per platform
DrawSection<PlatformSpecifics.TextMeshTextPerPlatform>
(ref showTextMeshText,
"Text mesh text",
ref specifics.textMeshTextPerPlatform,
DrawTextMeshText<PlatformSpecifics.TextMeshTextPerPlatform>,
() => {return new PlatformSpecifics.TextMeshTextPerPlatform(Platform.Standalone, string.Empty);}, true);
}
void DrawRestrictToPlatforms<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
Platform[] restrictPlatform = array as Platform[];
DrawPlatformEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref restrictPlatform[index]);
}
void DrawMaterials<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.MaterialPerPlatform[] materialsPerPlatform = array as PlatformSpecifics.MaterialPerPlatform[];
DrawPlatformEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref materialsPerPlatform[index].platform);
GUILayout.Space(10f);
materialsPerPlatform[index].mat = EditorGUILayout.ObjectField(materialsPerPlatform[index].mat, typeof(Material), false) as Material;
GUILayout.BeginHorizontal();
if(GUILayout.Button("Get")) {
if(specifics.renderer != null) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get material");
#else
Undo.RecordObject(specifics, "get material");
#endif
materialsPerPlatform[index].mat = specifics.renderer.sharedMaterial;
} else {
Debug.Log("There is no Renderer component on this game object.");
}
}
if(GUILayout.Button("Set")) {
if(specifics.renderer != null) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics.renderer, "set material");
#else
Undo.RecordObject(specifics.renderer, "set material");
#endif
specifics.renderer.sharedMaterial = materialsPerPlatform[index].mat;
} else {
Debug.Log("There is no Renderer component on this game object.");
}
}
GUILayout.EndHorizontal();
}
void DrawLocalScalePerPlatform<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.LocalScalePerPlatform[] localScalePerPlatform = array as PlatformSpecifics.LocalScalePerPlatform[];
DrawPlatformEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref localScalePerPlatform[index].platform);
localScalePerPlatform[index].localScale = EditorGUILayout.Vector3Field("Local scale", localScalePerPlatform[index].localScale);
GUILayout.BeginHorizontal();
//GUILayout.Space(20f);
GUILayout.BeginVertical();
//GUILayout.Space(18f);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Get")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get local scale");
#else
Undo.RecordObject(specifics, "get local scale");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) localScalePerPlatform[index].localScale = rectTransform.localScale;
else localScalePerPlatform[index].localScale = specifics.transform.localScale;
#else
localScalePerPlatform[index].localScale = specifics.transform.localScale;
#endif
}
if(GUILayout.Button("Set")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics.transform, "set local scale");
#else
Undo.RecordObject(specifics.transform, "set local scale");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) rectTransform.localScale = localScalePerPlatform[index].localScale;
else specifics.transform.localScale = localScalePerPlatform[index].localScale;
#else
specifics.transform.localScale = localScalePerPlatform[index].localScale;
#endif
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
void DrawLocalScalePerAspectRatio<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.LocalScalePerAspectRatio[] localScalePerAspectRatio = array as PlatformSpecifics.LocalScalePerAspectRatio[];
DrawAspectRatiosEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref localScalePerAspectRatio[index].aspectRatio);
localScalePerAspectRatio[index].localScale = EditorGUILayout.Vector3Field("Local scale", localScalePerAspectRatio[index].localScale);
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
//GUILayout.Space(18f);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Get")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get local scale");
#else
Undo.RecordObject(specifics, "get local scale");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) localScalePerAspectRatio[index].localScale = rectTransform.localScale;
else localScalePerAspectRatio[index].localScale = specifics.transform.localScale;
#else
localScalePerAspectRatio[index].localScale = specifics.transform.localScale;
#endif
}
if(GUILayout.Button("Set")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics.transform, "set local scale");
#else
Undo.RecordObject(specifics.transform, "set local scale");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) rectTransform.localScale = localScalePerAspectRatio[index].localScale;
else specifics.transform.localScale = localScalePerAspectRatio[index].localScale;
#else
specifics.transform.localScale = localScalePerAspectRatio[index].localScale;
#endif
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
void DrawLocalPositionPerPlatform<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.LocalPositionPerPlatform[] localPositionPerPlatform = array as PlatformSpecifics.LocalPositionPerPlatform[];
DrawPlatformEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref localPositionPerPlatform[index].platform);
localPositionPerPlatform[index].localPosition = EditorGUILayout.Vector3Field("Local position", localPositionPerPlatform[index].localPosition);
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
//GUILayout.Space(18f);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Get")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get local position");
#else
Undo.RecordObject(specifics, "get local position");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) localPositionPerPlatform[index].localPosition = rectTransform.localPosition;
else localPositionPerPlatform[index].localPosition = specifics.transform.localPosition;
#else
localPositionPerPlatform[index].localPosition = specifics.transform.localPosition;
#endif
}
if(GUILayout.Button("Set")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics.transform, "set local position");
#else
Undo.RecordObject(specifics.transform, "set local position");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) rectTransform.localPosition = localPositionPerPlatform[index].localPosition;
else specifics.transform.localPosition = localPositionPerPlatform[index].localPosition;
#else
specifics.transform.localPosition = localPositionPerPlatform[index].localPosition;
#endif
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
void DrawLocalPositionPerAspectRatio<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.LocalPositionPerAspectRatio[] localPositionPerAspectRatio = array as PlatformSpecifics.LocalPositionPerAspectRatio[];
DrawAspectRatiosEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref localPositionPerAspectRatio[index].aspectRatio);
localPositionPerAspectRatio[index].localPosition = EditorGUILayout.Vector3Field("Local position", localPositionPerAspectRatio[index].localPosition);
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
//GUILayout.Space(18f);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Get")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get local position");
#else
Undo.RecordObject(specifics, "get local position");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) localPositionPerAspectRatio[index].localPosition = rectTransform.localPosition;
else localPositionPerAspectRatio[index].localPosition = specifics.transform.localPosition;
#else
localPositionPerAspectRatio[index].localPosition = specifics.transform.localPosition;
#endif
}
if(GUILayout.Button("Set")) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics.transform, "set local position");
#else
Undo.RecordObject(specifics.transform, "set local position");
#endif
#if UNITY_4_6
var rectTransform = specifics.GetComponent<RectTransform>();
if (rectTransform != null) rectTransform.localPosition = localPositionPerAspectRatio[index].localPosition;
else specifics.transform.localPosition = localPositionPerAspectRatio[index].localPosition;
#else
specifics.transform.localPosition = localPositionPerAspectRatio[index].localPosition;
#endif
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
void DrawAnchorPositions<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.AnchorPosition[] anchorPositions = array as PlatformSpecifics.AnchorPosition[];
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
anchorPositions[index].alignmentCamera = (Camera)EditorGUILayout.ObjectField(anchorPositions[index].alignmentCamera, typeof(Camera), true);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
anchorPositions[index].screenPosition = EditorGUILayout.Vector2Field("Position Offset", anchorPositions[index].screenPosition);
EditorGUILayout.Space();
DrawRemoveButton(index, ref itemToDelete);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(28f);
int value = anchorPositions[index].positionXAsPercent ? 0 : 1;
value = GUILayout.SelectionGrid(value, new GUIContent[]{new GUIContent("X As Percent", "For example, enter 0.5 for 50%"), new GUIContent("X As Pixels")}, 1, EditorStyles.radioButton);
anchorPositions[index].positionXAsPercent = value == 0;
value = anchorPositions[index].positionYAsPercent ? 0 : 1;
value = GUILayout.SelectionGrid(value, new GUIContent[]{new GUIContent("Y As Percent", "For example, enter 0.5 for 50%"), new GUIContent("Y As Pixels")}, 1, EditorStyles.radioButton);
anchorPositions[index].positionYAsPercent = value == 0;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
EditorGUILayout.LabelField("CenterX:", GUILayout.Width(75));
anchorPositions[index].centerX = EditorGUILayout.Toggle(anchorPositions[index].centerX, GUILayout.Width(20));
EditorGUILayout.LabelField("CenterY:", GUILayout.Width(75));
anchorPositions[index].centerY = EditorGUILayout.Toggle(anchorPositions[index].centerY, GUILayout.Width(20));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
EditorGUILayout.LabelField("Alignments:", GUILayout.Width(70));
anchorPositions[index].horizontalAlignment = (HorizontalAlignments)EditorGUILayout.EnumPopup((System.Enum)anchorPositions[index].horizontalAlignment, enumPopupStyle, GUILayout.Width(70));
anchorPositions[index].verticalAlignment = (VerticalAlignments)EditorGUILayout.EnumPopup((System.Enum)anchorPositions[index].verticalAlignment, enumPopupStyle, GUILayout.Width(70));
EditorGUILayout.Space();
DrawMoveButtons(index, ref moveItemIdx, ref moveItemDirection);
GUILayout.EndHorizontal();
}
void DrawFonts<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.FontPerPlatform[] fontsPerPlatform = array as PlatformSpecifics.FontPerPlatform[];
DrawPlatformEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref fontsPerPlatform[index].platform);
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
fontsPerPlatform[index].font = EditorGUILayout.ObjectField(fontsPerPlatform[index].font, typeof(Font), false) as Font;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
fontsPerPlatform[index].mat = EditorGUILayout.ObjectField(fontsPerPlatform[index].mat, typeof(Material), false) as Material;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
if(GUILayout.Button("Get")) {
TextMesh textMesh = specifics.GetComponent<TextMesh>();
if(textMesh != null && specifics.renderer != null) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get font and material");
#else
Undo.RecordObject(specifics, "get font and material");
#endif
fontsPerPlatform[index].font = textMesh.font;
fontsPerPlatform[index].mat = specifics.renderer.sharedMaterial;
} else {
Debug.Log("There is no TextMesh or Renderer component on this game object.");
}
}
if(GUILayout.Button("Set")) {
TextMesh textMesh = specifics.GetComponent<TextMesh>();
if(textMesh != null && specifics.renderer != null) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(textMesh, "set font");
Undo.RegisterUndo(specifics.renderer, "set material");
#else
Undo.RecordObject(textMesh, "set font");
Undo.RecordObject(specifics.renderer, "set material");
#endif
textMesh.font = fontsPerPlatform[index].font;
specifics.renderer.sharedMaterial = fontsPerPlatform[index].mat;
} else {
Debug.Log("There is no TextMesh or Renderer component on this game object.");
}
}
GUILayout.EndHorizontal();
}
void DrawTextMeshText<T>(int index, ref T[] array, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection) {
PlatformSpecifics.TextMeshTextPerPlatform[] textMeshTextPerPlatform = array as PlatformSpecifics.TextMeshTextPerPlatform[];
DrawPlatformEnum(index, ref itemToDelete, ref moveItemIdx, ref moveItemDirection, ref textMeshTextPerPlatform[index].platform);
GUILayout.Space(10f);
textMeshTextPerPlatform[index].text = EditorGUILayout.TextField(textMeshTextPerPlatform[index].text);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Get")) {
TextMesh textMesh = specifics.GetComponent<TextMesh>();
if(textMesh != null) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "get TextMesh text");
#else
Undo.RecordObject(specifics, "get TextMesh text");
#endif
textMeshTextPerPlatform[index].text = textMesh.text;
} else {
Debug.Log("There is no TextMesh component on this game object.");
}
}
if(GUILayout.Button("Set")) {
TextMesh textMesh = specifics.GetComponent<TextMesh>();
if(textMesh != null) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(textMesh, "set TextMesh text");
#else
Undo.RecordObject(textMesh, "set TextMesh text");
#endif
textMesh.text = textMeshTextPerPlatform[index].text;
} else {
Debug.Log("There is no TextMesh component on this game object.");
}
}
GUILayout.EndHorizontal();
}
void DrawSection<T>(ref bool show, string header, ref T[] array, DrawArray<T> drawArray, Constructor<T> construct, bool drawAddButton) {
show = EditorGUILayout.Foldout(show, header);
if(!show) return;
int itemToDelete = -1;
int moveItemIdx = -1;
int moveItemDirection = 0;
for(int i=0; i < array.Length; i++) {
drawArray(i, ref array, ref itemToDelete, ref moveItemIdx, ref moveItemDirection);
GUILayout.Space(5f);
}
if(itemToDelete != -1) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "delete array item");
#else
Undo.RecordObject(specifics, "delete array item");
#endif
List<T> list = new List<T>(array as IEnumerable<T>);
list.RemoveAt(itemToDelete);
array = list.ToArray();
EditorUtility.SetDirty(specifics);
}
if(moveItemIdx != -1) {
int newIdx = moveItemIdx + moveItemDirection;
if(newIdx > -1 && newIdx < array.Length) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "move array item");
#else
Undo.RecordObject(specifics, "move array item");
#endif
List<T> list = new List<T>(array as IEnumerable<T>);
T item = list[moveItemIdx];
list.RemoveAt(moveItemIdx);
list.Insert(newIdx, item);
array = list.ToArray();
EditorUtility.SetDirty(specifics);
}
}
if (drawAddButton || array == null || array.Length == 0) {
GUILayout.BeginHorizontal();
GUILayout.Space(18f);
if(GUILayout.Button(string.Empty, addButtonStyle)) {
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(specifics, "add array item");
#else
Undo.RecordObject(specifics, "add array item");
#endif
List<T> list = new List<T>(array as IEnumerable<T>);
list.Add(construct());
array = list.ToArray();
EditorUtility.SetDirty(specifics);
}
GUILayout.EndHorizontal();
}
}
void DrawMoveButtons(int index, ref int moveItemIdx, ref int moveItemDirection) {
if(GUILayout.Button(string.Empty, moveItemAboveStyle)) {
moveItemIdx = index;
moveItemDirection = -1;
}
if(GUILayout.Button(string.Empty, moveItemBelowStyle)) {
moveItemIdx = index;
moveItemDirection = 1;
}
}
void DrawRemoveButton(int index, ref int itemToDelete) {
if(GUILayout.Button(string.Empty, removeButtonStyle))
itemToDelete = index;
}
void DrawAspectRatiosEnum(int index, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection, ref AspectRatio _enum) {
GUILayout.BeginHorizontal();
//GUILayout.Space(20f);
_enum = (AspectRatio) EditorGUILayout.EnumPopup((System.Enum)_enum, enumPopupStyle, GUILayout.Width(100f));
EditorGUILayout.Space();
DrawMoveButtons(index, ref moveItemIdx, ref moveItemDirection);
EditorGUILayout.Space();
DrawRemoveButton(index, ref itemToDelete);
GUILayout.EndHorizontal();
}
void DrawPlatformEnum(int index, ref int itemToDelete, ref int moveItemIdx, ref int moveItemDirection, ref Platform _enum) {
GUILayout.BeginHorizontal();
//GUILayout.Space(20f);
_enum = (Platform) EditorGUILayout.EnumPopup((System.Enum)_enum, enumPopupStyle, GUILayout.Width(100f));
EditorGUILayout.Space();
DrawMoveButtons(index, ref moveItemIdx, ref moveItemDirection);
EditorGUILayout.Space();
DrawRemoveButton(index, ref itemToDelete);
GUILayout.EndHorizontal();
}
void OnDisable() {
specifics = null;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Spart;
using Spart.Actions;
using Spart.Parsers;
using Spart.Parsers.NonTerminal;
using Spart.Scanners;
using Debugger = Spart.Debug.Debugger;
namespace Palaso.WritingSystems.Collation
{
public class IcuRulesParser
{
private XmlWriter _writer;
private Debugger _debugger;
private bool _useDebugger;
// You will notice that the xml tags used don't always match my parser/rule variable name.
// Collation in ldml is based off of icu and is pretty
// much a straight conversion of icu operators into xml tags. Unfortunately, ICU refers to some constructs
// with one name (which I used for my variable names), but ldml uses a different name for the actual
// xml tag.
// http://unicode.org/reports/tr35/#Collation_Elements - LDML collation element spec
// http://icu-project.org/userguide/Collate_Customization.html - ICU collation spec
// http://www.unicode.org/reports/tr10/ - UCA (Unicode Collation Algorithm) spec
public IcuRulesParser() : this(false) {}
public IcuRulesParser(bool useDebugger)
{
_useDebugger = useDebugger;
}
public void WriteIcuRules(XmlWriter writer, string icuRules)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (icuRules == null)
{
throw new ArgumentNullException("icuRules");
}
_writer = writer;
DefineParsingRules();
AssignSemanticActions();
InitializeDataObjects();
StringScanner sc = new StringScanner(icuRules);
try
{
ParserMatch match = _icuRules.Parse(sc);
if (!match.Success || !sc.AtEnd)
{
throw new ApplicationException("Invalid ICU rules.");
}
}
catch (ApplicationException e)
{
throw new ApplicationException("Invalid ICU rules: " + e.Message, e);
}
catch (ParserErrorException e)
{
throw new ApplicationException("Invalid ICU rules: " + e.Message, e);
}
finally
{
ClearDataObjects();
_writer = null;
}
}
public bool ValidateIcuRules(string icuRules, out string message)
{
// I was going to run with no semantic actions and therefore no dom needed,
// but some actions can throw (OnOptionVariableTop for one),
// so we need to run the actions as well for full validation.
_writer = null;
DefineParsingRules();
AssignSemanticActions();
InitializeDataObjects();
StringScanner sc = new StringScanner(icuRules);
ParserMatch match;
try
{
match = _icuRules.Parse(sc);
}
catch (ParserErrorException e)
{
string errString = sc.InputString.Split(new char[] {'\n'})[e.ParserError.Line - 1];
int startingPos = Math.Max((int) e.ParserError.Column - 2, 0);
errString = errString.Substring(startingPos, Math.Min(10, errString.Length - startingPos));
message = String.Format("{0}: '{1}'", e.ParserError.ErrorText, errString);
return false;
}
catch (Exception e)
{
message = e.Message;
return false;
}
finally
{
ClearDataObjects();
}
if (!match.Success || !sc.AtEnd)
{
message = "Invalid ICU rules.";
return false;
}
message = string.Empty;
return true;
}
private Parser _someWhiteSpace;
private Parser _optionalWhiteSpace;
private Parser _escapeSequence;
private Parser _singleQuoteLiteral;
private Parser _quotedStringCharacter;
private Parser _quotedString;
private Parser _normalCharacter;
private Parser _dataCharacter;
private Rule _dataString;
private Parser _firstOrLast;
private Parser _primarySecondaryTertiary;
private Parser _indirectOption;
private Rule _indirectPosition;
private Parser _top;
private Rule _simpleElement;
private Rule _expansion;
private Rule _prefix;
private Parser _extendedElement;
private Parser _beforeOption;
private Parser _beforeSpecifier;
private Parser _differenceOperator;
private Rule _simpleDifference;
private Rule _extendedDifference;
private Parser _difference;
private Rule _reset;
private Rule _oneRule;
private Parser _optionAlternate;
private Parser _optionBackwards;
private Parser _optionNormalization;
private Parser _optionOnOff;
private Parser _optionCaseLevel;
private Parser _optionCaseFirst;
private Parser _optionStrength;
private Parser _optionHiraganaQ;
private Parser _optionNumeric;
private Parser _optionVariableTop;
private Parser _optionSuppressContractions;
private Parser _optionOptimize;
private Parser _characterSet;
private Rule _option;
private Rule _icuRules;
private void DefineParsingRules()
{
// someWhiteSpace ::= WS+
// optionalWhiteSpace ::= WS*
_someWhiteSpace = Ops.OneOrMore(Prims.WhiteSpace);
_optionalWhiteSpace = Ops.ZeroOrMore(Prims.WhiteSpace);
// Valid escaping formats (from http://www.icu-project.org/userguide/Collate_Customization.html )
//
// Most of the characters can be used as parts of rules.
// However, whitespace characters will be skipped over,
// and all ASCII characters that are not digits or letters
// are considered to be part of syntax. In order to use
// these characters in rules, they need to be escaped.
// Escaping can be done in several ways:
// * Single characters can be escaped using backslash \ (U+005C).
// * Strings can be escaped by putting them between single quotes 'like this'.
// * Single quote can be quoted using two single quotes ''.
// because Unicode escape sequences are allowed in LDML we need to handle those also,
// escapeSequence ::= '\' U[A-F0-9]{8} | u[A-F0-9]{4} | anyChar
_escapeSequence = Ops.Choice(new Parser[] {
Ops.Sequence('\\', Ops.Sequence('U', Prims.HexDigit, Prims.HexDigit, Prims.HexDigit,
Prims.HexDigit, Prims.HexDigit, Prims.HexDigit, Prims.HexDigit,
Prims.HexDigit)),
Ops.Sequence('\\', Ops.Sequence('u', Prims.HexDigit, Prims.HexDigit, Prims.HexDigit,
Prims.HexDigit)),
Ops.Sequence('\\', Ops.Expect("icu0002", "Invalid escape sequence.", Prims.AnyChar))
});
// singleQuoteLiteral ::= "''"
// quotedStringCharacter ::= AllChars - "'"
// quotedString ::= "'" (singleQuoteLiteral | quotedStringCharacter)+ "'"
_singleQuoteLiteral = Prims.Str("''");
_quotedStringCharacter = Prims.AnyChar - '\'';
_quotedString = Ops.Sequence('\'', Ops.OneOrMore(_singleQuoteLiteral | _quotedStringCharacter),
Ops.Expect("icu0003", "Quoted string without matching end-quote.", '\''));
// Any alphanumeric ASCII character and all characters above the ASCII range are valid data characters
// normalCharacter ::= [A-Za-z0-9] | [U+0080-U+1FFFFF]
// dataCharacter ::= normalCharacter | singleQuoteLiteral | escapeSequence
// dataString ::= (dataCharacter | quotedString) (WS? (dataCharacter | quotedString))*
_normalCharacter = Prims.LetterOrDigit | Prims.Range('\u0080', char.MaxValue);
_dataCharacter = _normalCharacter | _singleQuoteLiteral | _escapeSequence;
_dataString = new Rule(Ops.List(_dataCharacter | _quotedString, _optionalWhiteSpace));
// firstOrLast ::= 'first' | 'last'
// primarySecondaryTertiary ::= 'primary' | 'secondary' | 'tertiary'
// indirectOption ::= (primarySecondaryTertiary WS 'ignorable') | 'variable' | 'regular' | 'implicit' | 'trailing'
// indirectPosition ::= '[' WS? firstOrLast WS indirectOption WS? ']'
// According to the LDML spec, "implicit" should not be allowed in a reset element, but we're not going to check that
_firstOrLast = Ops.Choice("first", "last");
_primarySecondaryTertiary = Ops.Choice("primary", "secondary", "tertiary");
_indirectOption = Ops.Choice(Ops.Sequence(_primarySecondaryTertiary, _someWhiteSpace, "ignorable"),
"variable", "regular", "implicit", "trailing");
_indirectPosition = new Rule(Ops.Sequence('[', _optionalWhiteSpace,
Ops.Expect("icu0004", "Invalid indirect position specifier: unknown option",
Ops.Sequence(_firstOrLast, _someWhiteSpace, _indirectOption)), _optionalWhiteSpace,
Ops.Expect("icu0005", "Indirect position specifier missing closing ']'", ']')));
// top ::= '[' WS? 'top' WS? ']'
// [top] is a deprecated element in ICU and should be replaced by indirect positioning.
_top = Ops.Sequence('[', _optionalWhiteSpace, "top", _optionalWhiteSpace, ']');
// simpleElement ::= indirectPosition | dataString
_simpleElement = new Rule("simpleElement", _indirectPosition | _dataString);
// expansion ::= WS? '/' WS? simpleElement
_expansion = new Rule("extend", Ops.Sequence(_optionalWhiteSpace, '/', _optionalWhiteSpace,
Ops.Expect("icu0007", "Invalid expansion: Data missing after '/'", _simpleElement)));
// prefix ::= simpleElement WS? '|' WS?
_prefix = new Rule("context", Ops.Sequence(_simpleElement, _optionalWhiteSpace, '|', _optionalWhiteSpace));
// extendedElement ::= (prefix simpleElement expansion?) | (prefix? simpleElement expansion)
_extendedElement = Ops.Sequence(_prefix, _simpleElement, !_expansion) |
Ops.Sequence(!_prefix, _simpleElement, _expansion);
// beforeOption ::= '1' | '2' | '3'
// beforeSpecifier ::= '[' WS? 'before' WS beforeOption WS? ']'
_beforeOption = Ops.Choice('1', '2', '3');
_beforeSpecifier = Ops.Sequence('[', _optionalWhiteSpace, "before", _someWhiteSpace,
Ops.Expect("icu0010", "Invalid 'before' specifier: Invalid or missing option", _beforeOption), _optionalWhiteSpace,
Ops.Expect("icu0011", "Invalid 'before' specifier: Missing closing ']'", ']'));
// The difference operator initially caused some problems with parsing. The spart library doesn't
// handle situations where the first choice is the beginning of the second choice.
// Ex: differenceOperator = "<" | "<<" | "<<<" | "=" DOES NOT WORK!
// That will fail to parse bothe the << and <<< operators because it always thinks it should match <.
// However, differenceOperator = "<<<" | "<<" | "<" | "=" will work because it tries to match <<< first.
// I'm using this strange production with the option '<' characters because it also works and doesn't
// depend on order. It is less likely for someone to change it and unknowingly mess it up.
// differenceOperator ::= ('<' '<'? '<'?) | '='
_differenceOperator = Ops.Sequence('<', !Prims.Ch('<'), !Prims.Ch('<')) | Prims.Ch('=');
// simpleDifference ::= differenceOperator WS? simpleElement
// extendedDifference ::= differenceOperator WS? extendedElement
// difference ::= simpleDifference | extendedDifference
// NOTE: Due to the implementation of the parser, extendedDifference MUST COME BEFORE simpleDifference in the difference definition
_simpleDifference = new Rule("simpleDifference", Ops.Sequence(_differenceOperator,
_optionalWhiteSpace, _simpleElement));
_extendedDifference = new Rule("x", Ops.Sequence(_differenceOperator,
_optionalWhiteSpace, _extendedElement));
_difference = _extendedDifference | _simpleDifference;
// reset ::= '&' WS? ((beforeSpecifier? WS? simpleElement) | top)
_reset = new Rule("reset", Ops.Sequence('&', _optionalWhiteSpace,
_top | Ops.Sequence(!_beforeSpecifier, _optionalWhiteSpace, _simpleElement)));
// This option is a weird one, as it can come at any place in a rule and sets the preceding
// dataString as the variable top option in the settings element. So, it has to look at the
// data for the preceding element to know its own value, but leaves the preceding and any
// succeeding elements as if the variable top option wasn't there. Go figure.
// Also, it's really probably only valid following a simpleDifference or reset with a dataString
// and not an indirect position, but checking for all that in the grammar would be very convoluted, so
// we'll do it in the semantic action and throw. Yuck.
// optionVariableTop ::= '<' WS? '[' WS? 'variable' WS? 'top' WS? ']'
_optionVariableTop = Ops.Sequence('<', _optionalWhiteSpace, '[', _optionalWhiteSpace, "variable",
_optionalWhiteSpace, "top", _optionalWhiteSpace, ']');
// oneRule ::= reset (WS? (optionVariableTop | difference))*
_oneRule = new Rule("oneRule", Ops.Sequence(_reset, Ops.ZeroOrMore(Ops.Sequence(_optionalWhiteSpace,
_optionVariableTop | _difference))));
// Option notes:
// * The 'strength' option is specified in ICU as having valid values 1-4 and 'I'. In the LDML spec, it
// seems to indicate that valid values in ICU are 1-5, so I am accepting both and treating 'I' and '5'
// as the same. I'm also accepting 'I' and 'i', although my approach is, in general, to be case-sensitive.
// * The 'numeric' option is not mentioned on the ICU website, but it is implied as being acceptable ICU
// in the LDML spec, so I am supporting it here.
// * There are LDML options 'match-boundaries' and 'match-style' that are not in ICU, so they are not listed here.
// * The UCA spec seems to indicate that there is a 'locale' option which is not mentioned in either the
// LDML or ICU specs, so I am not supporting it here. It could be referring to the 'base' element that
// is an optional part of the 'collation' element in LDML.
// optionOnOff ::= 'on' | 'off'
// optionAlternate ::= 'alternate' WS ('non-ignorable' | 'shifted')
// optionBackwards ::= 'backwards' WS ('1' | '2')
// optionNormalization ::= 'normalization' WS optionOnOff
// optionCaseLevel ::= 'caseLevel' WS optionOnOff
// optionCaseFirst ::= 'caseFirst' WS ('off' | 'upper' | 'lower')
// optionStrength ::= 'strength' WS ('1' | '2' | '3' | '4' | 'I' | 'i' | '5')
// optionHiraganaQ ::= 'hiraganaQ' WS optionOnOff
// optionNumeric ::= 'numeric' WS optionOnOff
// characterSet ::= '[' (AnyChar - ']')* ']'
// optionSuppressContractions ::= 'suppress' WS 'contractions' WS characterSet
// optionOptimize ::= 'optimize' WS characterSet
// option ::= '[' WS? (optionAlternate | optionBackwards | optionNormalization | optionCaseLevel
// | optionCaseFirst | optionStrength | optionHiraganaQ | optionNumeric
// | optionSuppressContractions | optionOptimize) WS? ']'
_optionOnOff = Ops.Choice("on", "off");
_optionAlternate = Ops.Sequence("alternate", _someWhiteSpace, Ops.Choice("non-ignorable", "shifted"));
_optionBackwards = Ops.Sequence("backwards", _someWhiteSpace, Ops.Choice('1', '2'));
_optionNormalization = Ops.Sequence("normalization", _someWhiteSpace, _optionOnOff);
_optionCaseLevel = Ops.Sequence("caseLevel", _someWhiteSpace, _optionOnOff);
_optionCaseFirst = Ops.Sequence("caseFirst", _someWhiteSpace, Ops.Choice("off", "upper", "lower"));
_optionStrength = Ops.Sequence("strength", _someWhiteSpace, Ops.Choice('1', '2', '3', '4', 'I', 'i', '5'));
_optionHiraganaQ = Ops.Sequence("hiraganaQ", _someWhiteSpace, _optionOnOff);
_optionNumeric = Ops.Sequence("numeric", _someWhiteSpace, _optionOnOff);
_characterSet = Ops.Sequence('[', Ops.ZeroOrMore(Prims.AnyChar - ']'), ']');
_optionSuppressContractions = Ops.Sequence("suppress", _someWhiteSpace, "contractions", _someWhiteSpace,
_characterSet);
_optionOptimize = Ops.Sequence("optimize", _someWhiteSpace, _characterSet);
_option = new Rule("option", Ops.Sequence('[', _optionalWhiteSpace, _optionAlternate |
_optionBackwards | _optionNormalization | _optionCaseLevel | _optionCaseFirst |
_optionStrength | _optionHiraganaQ | _optionNumeric | _optionSuppressContractions |
_optionOptimize, _optionalWhiteSpace, ']'));
// I don't know if ICU requires all options first (it's unclear), but I am. :)
// icuRules ::= WS? (option WS?)* (oneRule WS?)* EOF
_icuRules = new Rule("icuRules", Ops.Sequence(_optionalWhiteSpace,
Ops.ZeroOrMore(Ops.Sequence(_option, _optionalWhiteSpace)),
Ops.ZeroOrMore(Ops.Sequence(_oneRule, _optionalWhiteSpace)), Ops.Expect("icu0015", "Invalid ICU rules.", Prims.End)));
if (_useDebugger)
{
_debugger = new Debugger(Console.Out);
_debugger += _option;
_debugger += _oneRule;
_debugger += _reset;
_debugger += _simpleElement;
_debugger += _simpleDifference;
_debugger += _extendedDifference;
_debugger += _dataString;
}
}
private void AssignSemanticActions()
{
_escapeSequence.Act += OnEscapeSequence;
_singleQuoteLiteral.Act += OnSingleQuoteLiteral;
_quotedStringCharacter.Act += OnDataCharacter;
_normalCharacter.Act += OnDataCharacter;
_dataString.Act += OnDataString;
_firstOrLast.Act += OnIndirectPiece;
_indirectOption.Act += OnIndirectPiece;
_indirectPosition.Act += OnIndirectPosition;
_top.Act += OnTop;
_expansion.Act += OnElementWithData;
_prefix.Act += OnElementWithData;
_differenceOperator.Act += OnDifferenceOperator;
_simpleDifference.Act += OnSimpleDifference;
_extendedDifference.Act += OnExtendedDifference;
_beforeOption.Act += OnBeforeOption;
_reset.Act += OnReset;
_optionAlternate.Act += OnOptionNormal;
_optionBackwards.Act += OnOptionBackwards;
_optionNormalization.Act += OnOptionNormal;
_optionCaseLevel.Act += OnOptionNormal;
_optionCaseFirst.Act += OnOptionNormal;
_optionStrength.Act += OnOptionStrength;
_optionHiraganaQ.Act += OnOptionHiraganaQ;
_optionNumeric.Act += OnOptionNormal;
_optionVariableTop.Act += OnOptionVariableTop;
_characterSet.Act += OnCharacterSet;
_optionSuppressContractions.Act += OnOptionSuppressContractions;
_optionOptimize.Act += OnOptionOptimize;
_icuRules.Act += OnIcuRules;
}
private class IcuDataObject : IComparable<IcuDataObject>
{
private XmlNodeType _nodeType;
private string _name;
private string _value;
private List<IcuDataObject> _children;
private IcuDataObject(XmlNodeType nodeType, string name, string value)
{
_nodeType = nodeType;
_name = name;
_value = value;
if (_nodeType == XmlNodeType.Element)
{
_children = new List<IcuDataObject>();
}
}
public static IcuDataObject CreateAttribute(string name, string value)
{
return new IcuDataObject(XmlNodeType.Attribute, name, value);
}
public static IcuDataObject CreateAttribute(string name)
{
return new IcuDataObject(XmlNodeType.Attribute, name, string.Empty);
}
public static IcuDataObject CreateElement(string name)
{
return new IcuDataObject(XmlNodeType.Element, name, null);
}
public static IcuDataObject CreateText(string text)
{
return new IcuDataObject(XmlNodeType.Text, null, text);
}
public string Name
{
get { return _name; }
}
public string Value
{
set { _value = value; }
}
public string InnerText
{
get
{
if (_nodeType == XmlNodeType.Attribute || _nodeType == XmlNodeType.Text)
{
return _value;
}
StringBuilder sb = new StringBuilder();
foreach (IcuDataObject child in _children)
{
if (child._nodeType == XmlNodeType.Attribute)
{
continue;
}
sb.Append(child.InnerText);
}
return sb.ToString();
}
}
// adds node at end of children
public void AppendChild(IcuDataObject ido)
{
Debug.Assert(_nodeType == XmlNodeType.Element);
Debug.Assert(ido != null);
_children.Add(ido);
}
// inserts child node in correct sort order
public void InsertChild(IcuDataObject ido)
{
Debug.Assert(_nodeType == XmlNodeType.Element);
Debug.Assert(ido != null);
int i;
for (i=0; i < _children.Count; ++i)
{
if (ido.CompareTo(_children[i]) < 0)
{
break;
}
}
_children.Insert(i, ido);
}
public void Write(XmlWriter writer)
{
switch (_nodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(_name);
foreach (IcuDataObject ido in _children)
{
ido.Write(writer);
}
writer.WriteEndElement();
break;
case XmlNodeType.Attribute:
writer.WriteAttributeString(_name, _value);
break;
case XmlNodeType.Text:
LdmlDataMapper.WriteLdmlText(writer, _value);
break;
default:
Debug.Assert(false, "Unhandled Icu Data Object type");
break;
}
}
#region IComparable<IcuDataObject> Members
public int CompareTo(IcuDataObject other)
{
var _nodeTypeStrength = new Dictionary<XmlNodeType, int>
{{XmlNodeType.Attribute, 1}, {XmlNodeType.Element, 2}, {XmlNodeType.Text, 3}};
int result = _nodeTypeStrength[_nodeType].CompareTo(_nodeTypeStrength[other._nodeType]);
if (result != 0)
{
return result;
}
switch (_nodeType)
{
case XmlNodeType.Attribute:
return LdmlNodeComparer.CompareAttributeNames(_name, other._name);
case XmlNodeType.Element:
return LdmlNodeComparer.CompareElementNames(_name, other._name);
}
return 0;
}
#endregion
}
private StringBuilder _currentDataString;
private Stack<IcuDataObject> _currentDataObjects;
private List<IcuDataObject> _currentNodes;
private Stack<string> _currentOperators;
private StringBuilder _currentIndirectPosition;
private Queue<IcuDataObject> _attributesForReset;
private List<IcuDataObject> _optionElements;
private string _currentCharacterSet;
private void InitializeDataObjects()
{
_currentDataString = new StringBuilder();
_currentDataObjects = new Stack<IcuDataObject>();
_currentNodes = new List<IcuDataObject>();
_currentOperators = new Stack<string>();
_currentIndirectPosition = new StringBuilder();
_attributesForReset = new Queue<IcuDataObject>();
_optionElements = new List<IcuDataObject>();
_currentCharacterSet = null;
}
private void ClearDataObjects()
{
_currentDataString = null;
_currentDataObjects = null;
_currentNodes = null;
_currentOperators = null;
_currentIndirectPosition = null;
_attributesForReset = null;
_optionElements = null;
_currentCharacterSet = null;
}
private void AddXmlNodeWithData(string name)
{
IcuDataObject ido = IcuDataObject.CreateElement(name);
ido.AppendChild(_currentDataObjects.Pop());
_currentNodes.Add(ido);
}
private void OnReset(object sender, ActionEventArgs args)
{
IcuDataObject ido = IcuDataObject.CreateElement(((Rule)sender).ID);
foreach (IcuDataObject attr in _attributesForReset)
{
ido.AppendChild(attr);
}
ido.AppendChild(_currentDataObjects.Pop());
_currentNodes.Add(ido);
_attributesForReset = new Queue<IcuDataObject>();
}
private void OnSimpleDifference(object sender, ActionEventArgs args)
{
AddXmlNodeWithData(_currentOperators.Pop());
}
// The extended element is the trickiest one becuase the operator gets nested in an extended tag, and
// can be preceded by another element as well. Here's a simple rule:
// &a < b => <reset>a</reset><p>b</p>
// And the extended one for comparison:
// &a < b | c / d => <reset>a</reset><x><context>b</context><p>c</p><extend>d</extend></x>
// The operator tag is inserted inside the "x" tag, and comes after the "context" tag (represented by '|')
private void OnExtendedDifference(object sender, ActionEventArgs args)
{
// There should always at least be 2 nodes by this point - reset and either prefix or expansion
Debug.Assert(_currentNodes.Count >= 2);
IcuDataObject differenceNode = IcuDataObject.CreateElement("x");
IcuDataObject dataNode = IcuDataObject.CreateElement(_currentOperators.Pop());
dataNode.AppendChild(_currentDataObjects.Pop());
IcuDataObject prefixNode = _currentNodes[_currentNodes.Count - 2];
IcuDataObject expansionNode = _currentNodes[_currentNodes.Count - 1];
int deleteCount = 0;
if (expansionNode.Name != "extend")
{
prefixNode = expansionNode;
expansionNode = null;
}
if (prefixNode.Name == "context")
{
differenceNode.AppendChild(prefixNode);
deleteCount++;
}
differenceNode.AppendChild(dataNode);
if (expansionNode != null)
{
differenceNode.AppendChild(expansionNode);
deleteCount++;
}
_currentNodes.RemoveRange(_currentNodes.Count - deleteCount, deleteCount);
_currentNodes.Add(differenceNode);
}
private void OnElementWithData(object sender, ActionEventArgs args)
{
Debug.Assert(sender is Rule);
AddXmlNodeWithData(((Rule) sender).ID);
}
private void OnDifferenceOperator(object sender, ActionEventArgs args)
{
switch (args.Value)
{
case "<":
_currentOperators.Push("p");
break;
case "<<":
_currentOperators.Push("s");
break;
case "<<<":
_currentOperators.Push("t");
break;
case "=":
_currentOperators.Push("i");
break;
default:
Debug.Assert(false, "Unhandled operator");
break;
}
}
private void AddAttributeForReset(string name, string value)
{
IcuDataObject attr = IcuDataObject.CreateAttribute(name, value);
_attributesForReset.Enqueue(attr);
}
private void OnEscapeSequence(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value[0] == '\\');
if(args.Value.Length == 2)
{
_currentDataString.Append(args.Value[1]); //drop the backslash and just insert the escaped character
}
else if (args.Value.Length == 6 || args.Value.Length == 10)//put unicode escapes into text unmolested
{
_currentDataString.Append(args.Value);
}
}
private void OnSingleQuoteLiteral(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value == "''");
_currentDataString.Append("\'");
}
private void OnDataCharacter(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value.Length == 1);
_currentDataString.Append(args.Value);
}
private void OnDataString(object sender, ActionEventArgs args)
{
_currentDataObjects.Push(IcuDataObject.CreateText(_currentDataString.ToString()));
_currentDataString = new StringBuilder();
}
private void OnIndirectPiece(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value.Length > 0);
if (_currentIndirectPosition.Length > 0)
{
_currentIndirectPosition.Append('_');
}
// due to slight differences between ICU and LDML, regular becomes non_ignorable
_currentIndirectPosition.Append(args.Value.Replace("regular", "non_ignorable").Replace(' ', '_'));
}
private void OnIndirectPosition(object sender, ActionEventArgs args)
{
_currentDataObjects.Push(IcuDataObject.CreateElement(_currentIndirectPosition.ToString()));
_currentIndirectPosition = new StringBuilder();
}
private void OnBeforeOption(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value.Length == 1);
Dictionary<string, string> optionMap = new Dictionary<string, string>(3);
optionMap["1"] = "primary";
optionMap["2"] = "secondary";
optionMap["3"] = "tertiary";
Debug.Assert(optionMap.ContainsKey(args.Value));
AddAttributeForReset("before", optionMap[args.Value]);
}
private void OnTop(object sender, ActionEventArgs args)
{
// [top] is deprecated in ICU and not directly allowed in LDML
// [top] is probably best rendered the same as [last regular]
_currentDataObjects.Push(IcuDataObject.CreateElement("last_non_ignorable"));
}
private void OnOptionNormal(object sender, ActionEventArgs args)
{
Regex regex = new Regex("(\\S+)\\s+(\\S+)");
Match match = regex.Match(args.Value);
Debug.Assert(match.Success);
IcuDataObject attr = IcuDataObject.CreateAttribute(match.Groups[1].Value, match.Groups[2].Value);
AddSettingsAttribute(attr);
}
private void OnOptionBackwards(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("backwards");
switch (args.Value[args.Value.Length - 1])
{
case '1':
attr.Value = "off";
break;
case '2':
attr.Value = "on";
break;
default:
Debug.Assert(false, "Unhandled backwards option.");
break;
}
AddSettingsAttribute(attr);
}
private void OnOptionStrength(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("strength");
switch (args.Value[args.Value.Length - 1])
{
case '1':
attr.Value = "primary";
break;
case '2':
attr.Value = "secondary";
break;
case '3':
attr.Value = "tertiary";
break;
case '4':
attr.Value = "quaternary";
break;
case '5':
case 'I':
case 'i':
attr.Value = "identical";
break;
default:
Debug.Assert(false, "Unhandled strength option.");
break;
}
AddSettingsAttribute(attr);
}
private void OnOptionHiraganaQ(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("hiraganaQuaternary");
attr.Value = args.Value.EndsWith("on") ? "on" : "off";
AddSettingsAttribute(attr);
}
private void OnOptionVariableTop(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("variableTop");
IcuDataObject previousNode = _currentNodes[_currentNodes.Count - 1];
if (previousNode.Name == "x")
{
throw new ApplicationException("[variable top] cannot follow an extended node (prefix, expasion, or both).");
}
if (previousNode.InnerText.Length == 0)
{
throw new ApplicationException("[variable top] cannot follow an indirect position");
}
string unescapedValue = previousNode.InnerText;
string escapedValue = string.Empty;
for (int i=0; i < unescapedValue.Length; i++)
{
escapedValue += String.Format("u{0:X}", Char.ConvertToUtf32(unescapedValue, i));
// if we had a surogate, that means that two "char"s were encoding one code point,
// so skip the next "char" as it was already handled in this iteration
if (Char.IsSurrogate(unescapedValue, i))
{
i++;
}
}
attr.Value = escapedValue;
AddSettingsAttribute(attr);
}
private void OnCharacterSet(object sender, ActionEventArgs args)
{
Debug.Assert(_currentCharacterSet == null);
_currentCharacterSet = args.Value;
}
private void OnOptionSuppressContractions(object sender, ActionEventArgs args)
{
Debug.Assert(_currentCharacterSet != null);
var element = IcuDataObject.CreateElement("suppress_contractions");
element.AppendChild(IcuDataObject.CreateText(_currentCharacterSet));
_optionElements.Add(element);
_currentCharacterSet = null;
}
private void OnOptionOptimize(object sender, ActionEventArgs args)
{
Debug.Assert(_currentCharacterSet != null);
var element = IcuDataObject.CreateElement("optimize");
element.AppendChild(IcuDataObject.CreateText(_currentCharacterSet));
_optionElements.Add(element);
_currentCharacterSet = null;
}
// Use this to optimize successive difference elements into one element
private void OptimizeNodes()
{
// we can optimize primary, secondary, tertiary, and identity elements
List<string> optimizableElementNames = new List<string>(new string[] { "p", "s", "t", "i" });
List<IcuDataObject> currentOptimizableNodeGroup = null;
List<IcuDataObject> optimizedNodeList = new List<IcuDataObject>();
// first, build a list of lists of nodes we can optimize
foreach (IcuDataObject node in _currentNodes)
{
// Current node can be part of an optimized group if it is an allowed element
// AND it only contains one unicode code point.
bool nodeOptimizable = (optimizableElementNames.Contains(node.Name) &&
(node.InnerText.Length == 1 ||
(node.InnerText.Length == 2 && Char.IsSurrogatePair(node.InnerText, 0))));
// If we have a group of optimizable nodes, but we can't add the current node to that group
if (currentOptimizableNodeGroup != null && (!nodeOptimizable || currentOptimizableNodeGroup[0].Name != node.Name))
{
// optimize the current list and add it, then reset the list
optimizedNodeList.Add(CreateOptimizedNode(currentOptimizableNodeGroup));
currentOptimizableNodeGroup = null;
}
if (!nodeOptimizable)
{
optimizedNodeList.Add(node);
continue;
}
// start a new optimizable group if we're not in one already
if (currentOptimizableNodeGroup == null)
{
currentOptimizableNodeGroup = new List<IcuDataObject>();
}
currentOptimizableNodeGroup.Add(node);
}
// add the last group, if any
if (currentOptimizableNodeGroup != null)
{
optimizedNodeList.Add(CreateOptimizedNode(currentOptimizableNodeGroup));
}
_currentNodes = optimizedNodeList;
}
private IcuDataObject CreateOptimizedNode(List<IcuDataObject> nodeGroup)
{
Debug.Assert(nodeGroup != null);
Debug.Assert(nodeGroup.Count > 0);
// one node is already optimized
if (nodeGroup.Count == 1)
{
return nodeGroup[0];
}
// luckily the optimized names are the same as the unoptimized with 'c' appended
// so <p> becomes <pc>, <s> to <sc>, et al.
IcuDataObject optimizedNode = IcuDataObject.CreateElement(nodeGroup[0].Name + "c");
foreach (IcuDataObject node in nodeGroup)
{
optimizedNode.AppendChild(IcuDataObject.CreateText(node.InnerText));
}
return optimizedNode;
}
private void PreserveNonIcuSettings()
{
//XmlNode oldSettings = _parentNode.SelectSingleNode("settings", _nameSpaceManager);
//if (oldSettings == null)
//{
// return;
//}
//List<string> icuSettings = new List<string>(new string[] {"strength", "alternate", "backwards",
// "normalization", "caseLevel", "caseFirst", "hiraganaQuaternary", "numeric", "variableTop"});
//foreach (XmlAttribute attr in oldSettings.Attributes)
//{
// if (!icuSettings.Contains(attr.Name))
// {
// _optionAttributes.Add(attr.CloneNode(true));
// }
//}
}
private void AddSettingsAttribute(IcuDataObject attr)
{
IcuDataObject settings = null;
foreach (var option in _optionElements)
{
if (option.Name == "settings")
{
settings = option;
break;
}
}
if (settings == null)
{
settings = IcuDataObject.CreateElement("settings");
_optionElements.Insert(0, settings);
}
settings.InsertChild(attr);
}
private void OnIcuRules(object sender, ActionEventArgs args)
{
OptimizeNodes();
if (_writer == null)
{
// we are in validate only mode
return;
}
PreserveNonIcuSettings();
// add any the option elements, if needed.
if (_optionElements.Count > 0)
{
_optionElements.Sort();
_optionElements.ForEach(e => e.Write(_writer));
}
if (_currentNodes.Count == 0)
{
return;
}
_writer.WriteStartElement("rules");
_currentNodes.ForEach(n => n.Write(_writer));
_writer.WriteEndElement();
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#if DEBUG
#define TRACK_REPRESENTATION_IDENTITY
#else
//#define TRACK_REPRESENTATION_IDENTITY
#endif
namespace Microsoft.Zelig.Runtime.TypeSystem
{
using System;
using System.Collections.Generic;
public abstract class BaseRepresentation
{
//
// State
//
#if TRACK_REPRESENTATION_IDENTITY
protected static int s_identity;
#endif
public int m_identity;
//--//
protected CustomAttributeAssociationRepresentation[] m_customAttributes;
//--//
//
// Constructor Methods
//
protected BaseRepresentation()
{
#if TRACK_REPRESENTATION_IDENTITY
m_identity = s_identity++;
#endif
m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray;
}
//
// MetaDataEquality Methods
//
public abstract bool EqualsThroughEquivalence( object obj ,
EquivalenceSet set );
public static bool EqualsThroughEquivalence( BaseRepresentation left ,
BaseRepresentation right ,
EquivalenceSet set )
{
if(Object.ReferenceEquals( left, right ))
{
return true;
}
if(left != null && right != null)
{
return left.EqualsThroughEquivalence( right, set );
}
return false;
}
public static bool ArrayEqualsThroughEquivalence<T>( T[] s ,
T[] d ,
EquivalenceSet set ) where T : BaseRepresentation
{
return ArrayEqualsThroughEquivalence( s, d, 0, -1, set );
}
public static bool ArrayEqualsThroughEquivalence<T>( T[] s ,
T[] d ,
int offset ,
int count ,
EquivalenceSet set ) where T : BaseRepresentation
{
int sLen = s != null ? s.Length : 0;
int dLen = d != null ? d.Length : 0;
if(count < 0)
{
if(sLen != dLen)
{
return false;
}
count = sLen - offset;
}
else
{
if(sLen < count + offset ||
dLen < count + offset )
{
return false;
}
}
while(count > 0)
{
if(EqualsThroughEquivalence( s[offset], d[offset], set ) == false)
{
return false;
}
offset++;
count--;
}
return true;
}
//--//
//
// Helper Methods
//
public virtual void ApplyTransformation( TransformationContext context )
{
context.Push( this );
context.Transform( ref m_customAttributes );
context.Pop();
}
//--//
public void AddCustomAttribute( CustomAttributeAssociationRepresentation cca )
{
m_customAttributes = ArrayUtility.AddUniqueToNotNullArray( m_customAttributes, cca );
}
public void CopyCustomAttribute( CustomAttributeAssociationRepresentation caa )
{
AddCustomAttribute( new CustomAttributeAssociationRepresentation( caa.CustomAttribute, this, caa.ParameterIndex ) );
}
public void RemoveCustomAttribute( CustomAttributeAssociationRepresentation cca )
{
m_customAttributes = ArrayUtility.RemoveUniqueFromNotNullArray( m_customAttributes, cca );
}
public void RemoveCustomAttribute( CustomAttributeRepresentation ca )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute == ca)
{
RemoveCustomAttribute( caa );
}
}
}
public bool HasCustomAttribute( TypeRepresentation target )
{
return FindCustomAttribute( target, -1 ) != null;
}
public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target )
{
return FindCustomAttribute( target, -1 );
}
public List<CustomAttributeRepresentation> FindCustomAttributes( TypeRepresentation target )
{
var lst = new List<CustomAttributeRepresentation>();
FindCustomAttributes( target, lst );
return lst;
}
public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ,
int index )
{
return FindCustomAttribute( target, -1, index );
}
public virtual void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
callback( caa );
}
}
//--//
protected CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ,
int paramIndex ,
int index )
{
int pos = index >= 0 ? 0 : index; // So we don't have the double check in the loop.
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute.Constructor.OwnerType == target &&
caa.ParameterIndex == paramIndex )
{
if(index == pos)
{
return caa.CustomAttribute;
}
pos++;
}
}
return null;
}
protected void FindCustomAttributes( TypeRepresentation target, List<CustomAttributeRepresentation> lst )
{
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
if(caa.CustomAttribute.Constructor.OwnerType == target)
{
lst.Add( caa.CustomAttribute );
}
}
}
//--//
internal virtual void ProhibitUse( TypeSystem.Reachability reachability ,
bool fApply )
{
reachability.ExpandProhibition( this );
foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes)
{
reachability.ExpandProhibition( caa );
}
}
internal virtual void Reduce( TypeSystem.Reachability reachability ,
bool fApply )
{
for(int i = m_customAttributes.Length; --i >= 0; )
{
CustomAttributeAssociationRepresentation caa = m_customAttributes[i];
CHECKS.ASSERT( reachability.Contains( caa.Target ) == true, "{0} cannot be reachable since its owner is not in the Reachability set", caa );
if(reachability.Contains( caa.CustomAttribute.Constructor ) == false)
{
CHECKS.ASSERT( reachability.Contains( caa ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa );
CHECKS.ASSERT( reachability.Contains( caa.CustomAttribute ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa.CustomAttribute );
reachability.ExpandProhibition( caa );
reachability.ExpandProhibition( caa.CustomAttribute );
if(fApply)
{
if(m_customAttributes.Length == 1)
{
m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray;
return;
}
m_customAttributes = ArrayUtility.RemoveAtPositionFromNotNullArray( m_customAttributes, i );
}
}
}
}
//--//
//
// Access Methods
//
public CustomAttributeAssociationRepresentation[] CustomAttributes
{
get
{
return m_customAttributes;
}
}
//--//
//
// Debug Methods
//
}
}
| |
/*
* Copyright (c) 2007-2016, Cameron Rich
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the axTLS 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 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.
*/
/**
* A wrapper around the unmanaged interface to give a semi-decent C# API
*/
using System;
using System.Runtime.InteropServices;
using System.Net.Sockets;
/**
* @defgroup csharp_api C# API.
*
* Ensure that the appropriate Dispose() methods are called when finished with
* various objects - otherwise memory leaks will result.
* @{
*/
namespace axTLS
{
/**
* @class SSL
* @ingroup csharp_api
* @brief A representation of an SSL connection.
*/
public class SSL
{
public IntPtr m_ssl; /**< A pointer to the real SSL type */
/**
* @brief Store the reference to an SSL context.
* @param ip [in] A reference to an SSL object.
*/
public SSL(IntPtr ip)
{
m_ssl = ip;
}
/**
* @brief Free any used resources on this connection.
*
* A "Close Notify" message is sent on this connection (if possible).
* It is up to the application to close the socket.
*/
public void Dispose()
{
axtls.ssl_free(m_ssl);
}
/**
* @brief Return the result of a handshake.
* @return SSL_OK if the handshake is complete and ok.
* @see ssl.h for the error code list.
*/
public int HandshakeStatus()
{
return axtls.ssl_handshake_status(m_ssl);
}
/**
* @brief Return the SSL cipher id.
* @return The cipher id which is one of:
* - SSL_AES128_SHA (0x2f)
* - SSL_AES256_SHA (0x35)
* - SSL_AES128_SHA256 (0x3c)
* - SSL_AES256_SHA256 (0x3d)
*/
public byte GetCipherId()
{
return axtls.ssl_get_cipher_id(m_ssl);
}
/**
* @brief Get the session id for a handshake.
*
* This will be a 32 byte sequence and is available after the first
* handshaking messages are sent.
* @return The session id as a 32 byte sequence.
* @note A SSLv23 handshake may have only 16 valid bytes.
*/
public byte[] GetSessionId()
{
IntPtr ptr = axtls.ssl_get_session_id(m_ssl);
byte sess_id_size = axtls.ssl_get_session_id_size(m_ssl);
byte[] result = new byte[sess_id_size];
Marshal.Copy(ptr, result, 0, sess_id_size);
return result;
}
/**
* @brief Retrieve an X.509 distinguished name component.
*
* When a handshake is complete and a certificate has been exchanged,
* then the details of the remote certificate can be retrieved.
*
* This will usually be used by a client to check that the server's
* common name matches the URL.
*
* A full handshake needs to occur for this call to work.
*
* @param component [in] one of:
* - SSL_X509_CERT_COMMON_NAME
* - SSL_X509_CERT_ORGANIZATION
* - SSL_X509_CERT_ORGANIZATIONAL_NAME
* - SSL_X509_CA_CERT_COMMON_NAME
* - SSL_X509_CA_CERT_ORGANIZATION
* - SSL_X509_CA_CERT_ORGANIZATIONAL_NAME
* @return The appropriate string (or null if not defined)
*/
public string GetCertificateDN(int component)
{
return axtls.ssl_get_cert_dn(m_ssl, component);
}
}
/**
* @class SSLUtil
* @ingroup csharp_api
* @brief Some global helper functions.
*/
public class SSLUtil
{
/**
* @brief Return the build mode of the axTLS project.
* @return The build mode is one of:
* - SSL_BUILD_SERVER_ONLY
* - SSL_BUILD_ENABLE_VERIFICATION
* - SSL_BUILD_ENABLE_CLIENT
* - SSL_BUILD_FULL_MODE
*/
public static int BuildMode()
{
return axtls.ssl_get_config(axtls.SSL_BUILD_MODE);
}
/**
* @brief Return the number of chained certificates that the
* client/server supports.
* @return The number of supported server certificates.
*/
public static int MaxCerts()
{
return axtls.ssl_get_config(axtls.SSL_MAX_CERT_CFG_OFFSET);
}
/**
* @brief Return the number of CA certificates that the client/server
* supports.
* @return The number of supported CA certificates.
*/
public static int MaxCACerts()
{
return axtls.ssl_get_config(axtls.SSL_MAX_CA_CERT_CFG_OFFSET);
}
/**
* @brief Indicate if PEM is supported.
* @return true if PEM supported.
*/
public static bool HasPEM()
{
return axtls.ssl_get_config(axtls.SSL_HAS_PEM) > 0 ? true : false;
}
/**
* @brief Display the text string of the error.
* @param error_code [in] The integer error code.
*/
public static void DisplayError(int error_code)
{
axtls.ssl_display_error(error_code);
}
/**
* @brief Return the version of the axTLS project.
*/
public static string Version()
{
return axtls.ssl_version();
}
}
/**
* @class SSLCTX
* @ingroup csharp_api
* @brief A base object for SSLServer/SSLClient.
*/
public class SSLCTX
{
/**
* @brief A reference to the real client/server context.
*/
protected IntPtr m_ctx;
/**
* @brief Establish a new client/server context.
*
* This function is called before any client/server SSL connections are
* made. If multiple threads are used, then each thread will have its
* own SSLCTX context. Any number of connections may be made with a
* single context.
*
* Each new connection will use the this context's private key and
* certificate chain. If a different certificate chain is required,
* then a different context needs to be be used.
*
* @param options [in] Any particular options. At present the options
* supported are:
* - SSL_SERVER_VERIFY_LATER (client only): Don't stop a handshake if
* the server authentication fails. The certificate can be
* authenticated later with a call to VerifyCert().
* - SSL_CLIENT_AUTHENTICATION (server only): Enforce client
* authentication i.e. each handshake will include a "certificate
* request" message from the server.
* - SSL_DISPLAY_BYTES (full mode build only): Display the byte
* sequences during the handshake.
* - SSL_DISPLAY_STATES (full mode build only): Display the state
* changes during the handshake.
* - SSL_DISPLAY_CERTS (full mode build only): Display the
* certificates that are passed during a handshake.
* - SSL_DISPLAY_RSA (full mode build only): Display the RSA key
* details that are passed during a handshake.
* @param num_sessions [in] The number of sessions to be used for
* session caching. If this value is 0, then there is no session
* caching.
* @return A client/server context.
*/
protected SSLCTX(uint options, int num_sessions)
{
m_ctx = axtls.ssl_ctx_new(options, num_sessions);
}
/**
* @brief Remove a client/server context.
*
* Frees any used resources used by this context. Each connection will
* be sent a "Close Notify" alert (if possible).
*/
public void Dispose()
{
axtls.ssl_ctx_free(m_ctx);
}
/**
* @brief Read the SSL data stream.
* @param ssl [in] An SSL object reference.
* @param in_data [out] After a successful read, the decrypted data
* will be here. It will be null otherwise.
* @return The number of decrypted bytes:
* - if > 0, then the handshaking is complete and we are returning the
* number of decrypted bytes.
* - SSL_OK if the handshaking stage is successful (but not yet
* complete).
* - < 0 if an error.
* @see ssl.h for the error code list.
* @note Use in_data before doing any successive ssl calls.
*/
public int Read(SSL ssl, out byte[] in_data)
{
IntPtr ptr = IntPtr.Zero;
int ret = axtls.ssl_read(ssl.m_ssl, ref ptr);
if (ret > axtls.SSL_OK)
{
in_data = new byte[ret];
Marshal.Copy(ptr, in_data, 0, ret);
}
else
{
in_data = null;
}
return ret;
}
/**
* @brief Write to the SSL data stream.
* @param ssl [in] An SSL obect reference.
* @param out_data [in] The data to be written
* @return The number of bytes sent, or if < 0 if an error.
* @see ssl.h for the error code list.
*/
public int Write(SSL ssl, byte[] out_data)
{
return axtls.ssl_write(ssl.m_ssl, out_data, out_data.Length);
}
/**
* @brief Write to the SSL data stream.
* @param ssl [in] An SSL obect reference.
* @param out_data [in] The data to be written
* @param out_len [in] The number of bytes to be written
* @return The number of bytes sent, or if < 0 if an error.
* @see ssl.h for the error code list.
*/
public int Write(SSL ssl, byte[] out_data, int out_len)
{
return axtls.ssl_write(ssl.m_ssl, out_data, out_len);
}
/**
* @brief Find an ssl object based on a Socket reference.
*
* Goes through the list of SSL objects maintained in a client/server
* context to look for a socket match.
* @param s [in] A reference to a <A HREF="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemnetsocketssocketclasstopic.asp">Socket</A> object.
* @return A reference to the SSL object. Returns null if the object
* could not be found.
*/
public SSL Find(Socket s)
{
int client_fd = s.Handle.ToInt32();
return new SSL(axtls. ssl_find(m_ctx, client_fd));
}
/**
* @brief Authenticate a received certificate.
*
* This call is usually made by a client after a handshake is complete
* and the context is in SSL_SERVER_VERIFY_LATER mode.
* @param ssl [in] An SSL object reference.
* @return SSL_OK if the certificate is verified.
*/
public int VerifyCert(SSL ssl)
{
return axtls.ssl_verify_cert(ssl.m_ssl);
}
/**
* @brief Force the client to perform its handshake again.
*
* For a client this involves sending another "client hello" message.
* For the server is means sending a "hello request" message.
*
* This is a blocking call on the client (until the handshake
* completes).
* @param ssl [in] An SSL object reference.
* @return SSL_OK if renegotiation instantiation was ok
*/
public int Renegotiate(SSL ssl)
{
return axtls.ssl_renegotiate(ssl.m_ssl);
}
/**
* @brief Load a file into memory that is in binary DER or ASCII PEM
* format.
*
* These are temporary objects that are used to load private keys,
* certificates etc into memory.
* @param obj_type [in] The format of the file. Can be one of:
* - SSL_OBJ_X509_CERT (no password required)
* - SSL_OBJ_X509_CACERT (no password required)
* - SSL_OBJ_RSA_KEY (AES128/AES256 PEM encryption supported)
* - SSL_OBJ_P8 (RC4-128 encrypted data supported)
* - SSL_OBJ_P12 (RC4-128 encrypted data supported)
*
* PEM files are automatically detected (if supported).
* @param filename [in] The location of a file in DER/PEM format.
* @param password [in] The password used. Can be null if not required.
* @return SSL_OK if all ok
*/
public int ObjLoad(int obj_type, string filename, string password)
{
return axtls.ssl_obj_load(m_ctx, obj_type, filename, password);
}
/**
* @brief Transfer binary data into the object loader.
*
* These are temporary objects that are used to load private keys,
* certificates etc into memory.
* @param obj_type [in] The format of the memory data.
* @param data [in] The binary data to be loaded.
* @param len [in] The amount of data to be loaded.
* @param password [in] The password used. Can be null if not required.
* @return SSL_OK if all ok
*/
public int ObjLoad(int obj_type, byte[] data, int len, string password)
{
return axtls.ssl_obj_memory_load(m_ctx, obj_type,
data, len, password);
}
}
/**
* @class SSLServer
* @ingroup csharp_api
* @brief The server context.
*
* All server connections are started within a server context.
*/
public class SSLServer : SSLCTX
{
/**
* @brief Start a new server context.
*
* @see SSLCTX for details.
*/
public SSLServer(uint options, int num_sessions) :
base(options, num_sessions) {}
/**
* @brief Establish a new SSL connection to an SSL client.
*
* It is up to the application to establish the initial socket
* connection.
*
* Call Dispose() when the connection is to be removed.
* @param s [in] A reference to a <A HREF="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemnetsocketssocketclasstopic.asp">Socket</A> object.
* @return An SSL object reference.
*/
public SSL Connect(Socket s)
{
int client_fd = s.Handle.ToInt32();
return new SSL(axtls.ssl_server_new(m_ctx, client_fd));
}
}
/**
* @class SSLClient
* @ingroup csharp_api
* @brief The client context.
*
* All client connections are started within a client context.
*/
public class SSLClient : SSLCTX
{
/**
* @brief Start a new client context.
*
* @see SSLCTX for details.
*/
public SSLClient(uint options, int num_sessions) :
base(options, num_sessions) {}
/**
* @brief Establish a new SSL connection to an SSL server.
*
* It is up to the application to establish the initial socket
* connection.
*
* This is a blocking call - it will finish when the handshake is
* complete (or has failed).
*
* Call Dispose() when the connection is to be removed.
* @param s [in] A reference to a <A HREF="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemnetsocketssocketclasstopic.asp">Socket</A> object.
* @param session_id [in] A 32 byte session id for session resumption.
* This can be null if no session resumption is not required.
* @return An SSL object reference. Use SSL.handshakeStatus() to check
* if a handshake succeeded.
*/
public SSL Connect(Socket s, byte[] session_id)
{
int client_fd = s.Handle.ToInt32();
byte sess_id_size = (byte)(session_id != null ?
session_id.Length : 0);
return new SSL(axtls.ssl_client_new(m_ctx, client_fd, session_id,
sess_id_size));
}
}
}
/** @} */
| |
/*
Copyright 2015-2018 Developer Express 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.
*/
using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using DevExpress.DataAccess.BigQuery.Native;
namespace DevExpress.DataAccess.BigQuery {
/// <summary>
/// A parameter to a BigQueryCommand.
/// </summary>
public sealed class BigQueryParameter : DbParameter, ICloneable {
const int maxStringSize = 2097152;
BigQueryDbType? bigQueryDbType;
DbType? dbType;
object value;
ParameterDirection direction;
int? size;
/// <summary>
/// Initializes a new instance of the BigQueryParameter class with default settings.
/// </summary>
public BigQueryParameter() {
ResetDbType();
}
/// <summary>
/// Initializes a new instance of the BigQueryParameter class with the specified settings.
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="value">The value of the parameter.</param>
public BigQueryParameter(string parameterName, object value) : this() {
ParameterName = parameterName;
Value = value;
}
/// <summary>
/// Initializes a new instance of the BigQueryParameter class with the specified settings.
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="dbType">A DBType enumeration value specifying the data type of the parameter.</param>
public BigQueryParameter(string parameterName, DbType dbType) : this() {
ParameterName = parameterName;
DbType = dbType;
}
/// <summary>
/// Initializes a new instance of the BigQueryParameter class with the specified settings.
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="bigQueryDbType">A BigQueryDbType enumeration value specifying the data type of the parameter.</param>
public BigQueryParameter(string parameterName, BigQueryDbType bigQueryDbType) : this() {
ParameterName = parameterName;
BigQueryDbType = bigQueryDbType;
}
/// <summary>
/// Specifies the type of the parameter specific to Big Query.
/// </summary>
/// <value>
/// A BigQueryDbType enumeration value.
/// </value>
public BigQueryDbType BigQueryDbType {
get {
if(bigQueryDbType.HasValue)
return bigQueryDbType.Value;
if(value != null)
return BigQueryTypeConverter.ToBigQueryDbType(value.GetType());
return BigQueryDbType.Unknown;
}
set {
bigQueryDbType = value;
dbType = BigQueryTypeConverter.ToDbType(value);
}
}
/// <summary>
/// Specifies the DbType of the parameter.
/// </summary>
/// <value>
/// A DBType enumeration value.
/// </value>
public override DbType DbType {
get {
if(dbType.HasValue)
return dbType.Value;
if(value != null)
return BigQueryTypeConverter.ToDbType(value.GetType());
return DbType.Object;
}
set {
dbType = value;
bigQueryDbType = BigQueryTypeConverter.ToBigQueryDbType(value);
}
}
/// <summary>
/// Specifies whether the parameter is read-only, write-only, bidirectional or a stored procedure return value. This implementation only supports ParameterDirrection.Input as its value.
/// </summary>
/// <value>
/// A ParameterDirrection enumeration value.
/// </value>
public override ParameterDirection Direction {
get => direction;
set {
if (value != ParameterDirection.Input)
throw new ArgumentOutOfRangeException(nameof(value), value, "Only input parameters are supported.");
}
}
/// <summary>
/// Specifies whether or not the parameter can receive DBNull as its value.
/// </summary>
/// <value>
/// true, if the parameter can receive DBNull as its value; otherwise false.
/// </value>
public override bool IsNullable {
get => false;
set {
if(value)
throw new ArgumentOutOfRangeException(nameof(value), value, "Nullable parameters are not supported");
}
}
/// <summary>
/// Specifies the name of the parameter.
/// </summary>
/// <value>
/// The name of the parameter.
/// </value>
public override string ParameterName {
get;
set;
}
/// <summary>
/// Specifies the name of the source column used for loading and returning the parameter's Value.
/// </summary>
/// <value>
/// The name of a source column.
/// </value>
public override string SourceColumn {
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
/// <summary>
/// Specifies the DataRowVersion of the source row to be used when obtaining the parameter's value.
/// </summary>
/// <value>
/// A DataRowVersion enumeration value.
/// </value>
public override DataRowVersion SourceVersion {
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
/// <summary>
/// Specifies whether the source column of the current parameter is nullable.
/// </summary>
/// <value>
/// true, if the source column is nullable; otherwise false.
/// </value>
public override bool SourceColumnNullMapping {
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
/// <summary>
/// Specifies the value of the parameter.
/// </summary>
/// <value>
/// an Object specifying the value of the parameter.
/// </value>
public override object Value {
get => value ?? (value = BigQueryTypeConverter.GetDefaultValueFor(DbType));
set => this.value = value;
}
/// <summary>
/// Specifies the maximum size of data in the source column.
/// </summary>
/// <value>
/// The size of data in the source column.
/// </value>
public override int Size {
get {
if(size.HasValue)
return size.Value;
if(DbType != DbType.String) return 0;
var invariantString = value.ToInvariantString();
return invariantString.Length;
}
set {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "The value can not be less than 0");
size = value;
}
}
/// <summary>
/// Resets the data type associated with the parameter.
/// </summary>
public override void ResetDbType() {
dbType = null;
value = null;
direction = ParameterDirection.Input;
ParameterName = null;
}
internal void Validate() {
if(string.IsNullOrEmpty(ParameterName))
throw new ArgumentException("Parameter's name is empty");
if(Value == null || Value == DBNull.Value)
throw new ArgumentException("Null parameter's values is not supported");
if(BigQueryDbType == BigQueryDbType.Unknown)
throw new NotSupportedException("Unsupported type for BigQuery: " + DbType);
if(Size > maxStringSize)
throw new ArgumentException("Value's length in " + Size + " greater than max length in " + maxStringSize);
try {
Convert.ChangeType(Value, BigQueryTypeConverter.ToType(DbType), CultureInfo.InvariantCulture);
}
catch(Exception) {
throw new ArgumentException("Can't convert Value " + Value + " to DbType " + DbType);
}
}
object ICloneable.Clone() {
return Clone();
}
/// <summary>
/// Creates a shallow copy of the current BigQueryParameter.
/// </summary>
/// <returns>a shallow copy of the current BigQueryParameter.</returns>
public BigQueryParameter Clone() {
BigQueryParameter parameter = new BigQueryParameter(ParameterName, Value) {
Direction = Direction,
IsNullable = IsNullable,
DbType = DbType,
BigQueryDbType = BigQueryDbType,
Size = Size
};
return parameter;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type DomainDnsSrvRecordRequest.
/// </summary>
public partial class DomainDnsSrvRecordRequest : BaseRequest, IDomainDnsSrvRecordRequest
{
/// <summary>
/// Constructs a new DomainDnsSrvRecordRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public DomainDnsSrvRecordRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified DomainDnsSrvRecord using POST.
/// </summary>
/// <param name="domainDnsSrvRecordToCreate">The DomainDnsSrvRecord to create.</param>
/// <returns>The created DomainDnsSrvRecord.</returns>
public System.Threading.Tasks.Task<DomainDnsSrvRecord> CreateAsync(DomainDnsSrvRecord domainDnsSrvRecordToCreate)
{
return this.CreateAsync(domainDnsSrvRecordToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified DomainDnsSrvRecord using POST.
/// </summary>
/// <param name="domainDnsSrvRecordToCreate">The DomainDnsSrvRecord to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created DomainDnsSrvRecord.</returns>
public async System.Threading.Tasks.Task<DomainDnsSrvRecord> CreateAsync(DomainDnsSrvRecord domainDnsSrvRecordToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<DomainDnsSrvRecord>(domainDnsSrvRecordToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified DomainDnsSrvRecord.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified DomainDnsSrvRecord.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<DomainDnsSrvRecord>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified DomainDnsSrvRecord.
/// </summary>
/// <returns>The DomainDnsSrvRecord.</returns>
public System.Threading.Tasks.Task<DomainDnsSrvRecord> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified DomainDnsSrvRecord.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The DomainDnsSrvRecord.</returns>
public async System.Threading.Tasks.Task<DomainDnsSrvRecord> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<DomainDnsSrvRecord>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified DomainDnsSrvRecord using PATCH.
/// </summary>
/// <param name="domainDnsSrvRecordToUpdate">The DomainDnsSrvRecord to update.</param>
/// <returns>The updated DomainDnsSrvRecord.</returns>
public System.Threading.Tasks.Task<DomainDnsSrvRecord> UpdateAsync(DomainDnsSrvRecord domainDnsSrvRecordToUpdate)
{
return this.UpdateAsync(domainDnsSrvRecordToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified DomainDnsSrvRecord using PATCH.
/// </summary>
/// <param name="domainDnsSrvRecordToUpdate">The DomainDnsSrvRecord to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated DomainDnsSrvRecord.</returns>
public async System.Threading.Tasks.Task<DomainDnsSrvRecord> UpdateAsync(DomainDnsSrvRecord domainDnsSrvRecordToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<DomainDnsSrvRecord>(domainDnsSrvRecordToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IDomainDnsSrvRecordRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IDomainDnsSrvRecordRequest Expand(Expression<Func<DomainDnsSrvRecord, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IDomainDnsSrvRecordRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IDomainDnsSrvRecordRequest Select(Expression<Func<DomainDnsSrvRecord, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="domainDnsSrvRecordToInitialize">The <see cref="DomainDnsSrvRecord"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(DomainDnsSrvRecord domainDnsSrvRecordToInitialize)
{
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using bv.common.Configuration;
using bv.common.Core;
using bv.common.Resources.TranslationTool;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.model.Model.Validators;
using DevExpress.Web.Mvc;
using EIDSS;
using eidss.avr.mweb.Utils;
using eidss.avr.mweb.Utils.Localization;
using eidss.gis.common;
using eidss.model.Core;
using eidss.model.Resources;
using MvcContrib;
using MvcContrib.UI.InputBuilder;
using eidss.web.common.Utils;
namespace eidss.avr.mweb
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.IgnoreRoute("Content/{*pathInfo}");
//routes.IgnoreRoute("Content/Images/{*pathInfo}");
routes.MapRoute(
"Statics",
"s/{staticResourceVersion}/{*path}",
new { controller = "Statics", action = "Index" }
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Start",
"",
new { controller = "Account", action = "Login" }
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Login",
"Account/Login",
new { controller = "Account", action = "Login" }
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Report",
"Account/Layout",
new { controller = "Account", action = "Layout" }
).RouteHandler = new SingleCultureMvcRouteHandler();
routes.MapRoute(
"Error",
"Error/HttpError",
new { controller = "Error", action = "HttpError" }
);
routes.MapRoute(
"Errors",
"Error/{page}",
new { controller = "Error", action = "Http404" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "Login", id = UrlParameter.Optional } // Parameter defaults
);
AreaRegistration.RegisterAllAreas();
foreach (Route r in routes)
{
if (r.RouteHandler is SingleCultureMvcRouteHandler || r.RouteHandler is StopRoutingHandler)
{
continue;
}
r.RouteHandler = new MultiCultureMvcRouteHandler();
r.Url = "{culture}/" + r.Url;
//Adding default culture
if (r.Defaults == null)
{
r.Defaults = new RouteValueDictionary();
}
//Adding constraint for culture param
if (r.Constraints == null)
{
r.Constraints = new RouteValueDictionary();
}
if (!r.Constraints.Contains(typeof(CultureConstraint)))
{
r.Constraints.Add("culture", new CultureConstraint(Cultures.Available));
}
}
}
public static void ExtractEmbeddedDll(string dllName)
{
// Get the byte[] of the DLL
byte[] ba;
var resource = "eidss.avr.mweb." + dllName;
var curAsm = Assembly.GetExecutingAssembly();
using (var stm = curAsm.GetManifestResourceStream(resource))
{
if (stm != null)
{
ba = new byte[(int)stm.Length];
stm.Read(ba, 0, (int)stm.Length);
}
else
{
return;
}
}
var fileOk = false;
string location;
using (var sha1 = new SHA1CryptoServiceProvider())
{
// Get the hash value of the Embedded DLL
var fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);
// The full path of the DLL that will be saved
var assembly = Assembly.GetExecutingAssembly();
location = Path.GetDirectoryName(assembly.Location);
// Check if the DLL is already existed or not?
if (File.Exists(location))
{
// Get the file hash value of the existed DLL
var bb = File.ReadAllBytes(location);
var fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty);
// Compare the existed DLL with the Embedded DLL
fileOk = fileHash == fileHash2;
}
}
// Create the file on disk
if (fileOk)
{
return;
}
if (location != null)
{
File.WriteAllBytes(location, ba);
}
}
protected void Application_Start()
{
var connectionCredentials = new ConnectionCredentials();
TranslationToolHelper.SetDefaultTranslationPath();
DbManagerFactory.SetSqlFactory(connectionCredentials.ConnectionString);
EidssUserContext.Init();
CustomCultureHelper.CurrentCountry = EidssSiteContext.Instance.CountryID;
EIDSS_LookupCacheHelper.Init();
LookupCacheListener.Cleanup();
LookupCacheListener.Listen();
Localizer.MenuMessages = EidssMenu.Instance;
ClassLoader.Init("eidss_db.dll", bv.common.Core.Utils.GetDesktopExecutingPath());
//AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
InputBuilder.BootStrap();
BaseFieldValidator.FieldCaptions = EidssFields.Instance;
ModelBinders.Binders.DefaultBinder = new DevExpressEditorsBinder();
SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
XtraWebLocalizer.Activate();
}
protected void Application_End()
{
bv.common.Core.Utils.SaveUsedXtraResource();
LookupCacheListener.Stop();
}
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Application[HttpContext.Current.Request.UserHostAddress] = ex;
LogErrorInternal(ex);
HttpContext.Current.ClearError();
ProcessError(ex);
}
private void ProcessError(Exception ex)
{
var error = ex as HttpException;
int statusCode = error == null ? 500 : error.GetHttpCode();
string culture = Cultures.GetCulture(ModelUserContext.CurrentLanguage);
switch (statusCode)
{
case 404:
Response.Redirect("~/" + culture + "/Error/Http404");
break;
default:
Response.Redirect("~/" + culture + "/Error/HttpError");
break;
}
}
private void LogErrorInternal(Exception ex)
{
LogError.Log("ErrorLog_avr_", ex);
}
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
DevExpressHelper.Theme = GeneralSettings.Theme;
}
#region session handlers
protected void Session_Start()
{
/*var ms = new ModelStorage(Session.SessionID);
Session["ModelStorage"] = ms;*/
}
protected void Session_End()
{
bv.common.Core.Utils.SaveUsedXtraResource();
/*var ms = Session["ModelStorage"] as ModelStorage;
if (ms != null)
{
Session.Remove("ModelStorage");
ms.Dispose();
}*/
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Security.Principal;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
public enum AccessControlType
{
Allow = 0,
Deny = 1,
}
public abstract class AuthorizationRule
{
#region Private Members
private readonly IdentityReference _identity;
private readonly int _accessMask;
private readonly bool _isInherited;
private readonly InheritanceFlags _inheritanceFlags;
private readonly PropagationFlags _propagationFlags;
#endregion
#region Constructors
internal protected AuthorizationRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags )
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
if ( accessMask == 0 )
{
throw new ArgumentException(
Environment.GetResourceString( "Argument_ArgumentZero" ),
"accessMask" );
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
"inheritanceFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "InheritanceFlags" ));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
"propagationFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "PropagationFlags" ));
}
Contract.EndContractBlock();
if (identity.IsValidTargetType(typeof(SecurityIdentifier)) == false)
{
throw new ArgumentException(
Environment.GetResourceString("Arg_MustBeIdentityReferenceType"),
"identity");
}
_identity = identity;
_accessMask = accessMask;
_isInherited = isInherited;
_inheritanceFlags = inheritanceFlags;
if ( inheritanceFlags != 0 )
{
_propagationFlags = propagationFlags;
}
else
{
_propagationFlags = 0;
}
}
#endregion
#region Properties
public IdentityReference IdentityReference
{
get { return _identity; }
}
internal protected int AccessMask
{
get { return _accessMask; }
}
public bool IsInherited
{
get { return _isInherited; }
}
public InheritanceFlags InheritanceFlags
{
get { return _inheritanceFlags; }
}
public PropagationFlags PropagationFlags
{
get { return _propagationFlags; }
}
#endregion
}
public abstract class AccessRule : AuthorizationRule
{
#region Private Methods
private readonly AccessControlType _type;
#endregion
#region Constructors
protected AccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( type != AccessControlType.Allow &&
type != AccessControlType.Deny )
{
throw new ArgumentOutOfRangeException(
"type",
Environment.GetResourceString( "ArgumentOutOfRange_Enum" ));
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
"inheritanceFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "InheritanceFlags" ));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
"propagationFlags",
Environment.GetResourceString( "Argument_InvalidEnumValue", inheritanceFlags, "PropagationFlags" ));
}
Contract.EndContractBlock();
_type = type;
}
#endregion
#region Properties
public AccessControlType AccessControlType
{
get { return _type; }
}
#endregion
}
public abstract class ObjectAccessRule: AccessRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public abstract class AuditRule : AuthorizationRule
{
#region Private Members
private readonly AuditFlags _flags;
#endregion
#region Constructors
protected AuditRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( auditFlags == AuditFlags.None )
{
throw new ArgumentException(
Environment.GetResourceString( "Arg_EnumAtLeastOneFlag" ),
"auditFlags" );
}
else if (( auditFlags & ~( AuditFlags.Success | AuditFlags.Failure )) != 0 )
{
throw new ArgumentOutOfRangeException(
"auditFlags",
Environment.GetResourceString( "ArgumentOutOfRange_Enum" ));
}
_flags = auditFlags;
}
#endregion
#region Public Properties
public AuditFlags AuditFlags
{
get { return _flags; }
}
#endregion
}
public abstract class ObjectAuditRule: AuditRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, auditFlags )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Public Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public sealed class AuthorizationRuleCollection : ReadOnlyCollectionBase
{
#region Constructors
public AuthorizationRuleCollection()
: base()
{
}
#endregion
#region Public methods
public void AddRule( AuthorizationRule rule )
{
InnerList.Add( rule );
}
#endregion
#region ICollection Members
public void CopyTo( AuthorizationRule[] rules, int index )
{
(( ICollection )this ).CopyTo( rules, index );
}
#endregion
#region Public properties
public AuthorizationRule this[int index]
{
get { return InnerList[index] as AuthorizationRule; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Schema;
namespace System.Xml
{
internal class XmlLoader
{
private XmlDocument _doc;
private XmlReader _reader;
private bool _preserveWhitespace;
public XmlLoader()
{
}
internal void Load(XmlDocument doc, XmlReader reader, bool preserveWhitespace)
{
_doc = doc;
// perf: unwrap XmlTextReader if no one derived from it
if (reader.GetType() == typeof(System.Xml.XmlTextReader))
{
_reader = ((XmlTextReader)reader).Impl;
}
else
{
_reader = reader;
}
_preserveWhitespace = preserveWhitespace;
if (doc == null)
throw new ArgumentException(SR.Xdom_Load_NoDocument);
if (reader == null)
throw new ArgumentException(SR.Xdom_Load_NoReader);
doc.SetBaseURI(reader.BaseURI);
if (reader.Settings != null
&& reader.Settings.ValidationType == ValidationType.Schema)
{
doc.Schemas = reader.Settings.Schemas;
}
if (_reader.ReadState != ReadState.Interactive)
{
if (!_reader.Read())
return;
}
LoadDocSequence(doc);
}
//The function will start loading the document from where current XmlReader is pointing at.
private void LoadDocSequence(XmlDocument parentDoc)
{
Debug.Assert(_reader != null);
Debug.Assert(parentDoc != null);
XmlNode node = null;
while ((node = LoadNode(true)) != null)
{
parentDoc.AppendChildForLoad(node, parentDoc);
if (!_reader.Read())
return;
}
}
internal XmlNode ReadCurrentNode(XmlDocument doc, XmlReader reader)
{
_doc = doc;
_reader = reader;
// WS are optional only for loading (see XmlDocument.PreserveWhitespace)
_preserveWhitespace = true;
if (doc == null)
throw new ArgumentException(SR.Xdom_Load_NoDocument);
if (reader == null)
throw new ArgumentException(SR.Xdom_Load_NoReader);
if (reader.ReadState == ReadState.Initial)
{
reader.Read();
}
if (reader.ReadState == ReadState.Interactive)
{
XmlNode n = LoadNode(true);
// Move to the next node
if (n.NodeType != XmlNodeType.Attribute)
reader.Read();
return n;
}
return null;
}
private XmlNode LoadNode(bool skipOverWhitespace)
{
XmlReader r = _reader;
XmlNode parent = null;
XmlElement element;
IXmlSchemaInfo schemaInfo;
do
{
XmlNode node = null;
switch (r.NodeType)
{
case XmlNodeType.Element:
bool fEmptyElement = r.IsEmptyElement;
element = _doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI);
element.IsEmpty = fEmptyElement;
if (r.MoveToFirstAttribute())
{
XmlAttributeCollection attributes = element.Attributes;
do
{
XmlAttribute attr = LoadAttributeNode();
attributes.Append(attr); // special case for load
}
while (r.MoveToNextAttribute());
r.MoveToElement();
}
// recursively load all children.
if (!fEmptyElement)
{
if (parent != null)
{
parent.AppendChildForLoad(element, _doc);
}
parent = element;
continue;
}
else
{
schemaInfo = r.SchemaInfo;
if (schemaInfo != null)
{
element.XmlName = _doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo);
}
node = element;
break;
}
case XmlNodeType.EndElement:
if (parent == null)
{
return null;
}
Debug.Assert(parent.NodeType == XmlNodeType.Element);
schemaInfo = r.SchemaInfo;
if (schemaInfo != null)
{
element = parent as XmlElement;
if (element != null)
{
element.XmlName = _doc.AddXmlName(element.Prefix, element.LocalName, element.NamespaceURI, schemaInfo);
}
}
if (parent.ParentNode == null)
{
return parent;
}
parent = parent.ParentNode;
continue;
case XmlNodeType.EntityReference:
node = LoadEntityReferenceNode(false);
break;
case XmlNodeType.EndEntity:
Debug.Assert(parent == null);
return null;
case XmlNodeType.Attribute:
node = LoadAttributeNode();
break;
case XmlNodeType.Text:
node = _doc.CreateTextNode(r.Value);
break;
case XmlNodeType.SignificantWhitespace:
node = _doc.CreateSignificantWhitespace(r.Value);
break;
case XmlNodeType.Whitespace:
if (_preserveWhitespace)
{
node = _doc.CreateWhitespace(r.Value);
break;
}
else if (parent == null && !skipOverWhitespace)
{
// if called from LoadEntityReferenceNode, just return null
return null;
}
else
{
continue;
}
case XmlNodeType.CDATA:
node = _doc.CreateCDataSection(r.Value);
break;
case XmlNodeType.XmlDeclaration:
node = LoadDeclarationNode();
break;
case XmlNodeType.ProcessingInstruction:
node = _doc.CreateProcessingInstruction(r.Name, r.Value);
break;
case XmlNodeType.Comment:
node = _doc.CreateComment(r.Value);
break;
case XmlNodeType.DocumentType:
node = LoadDocumentTypeNode();
break;
default:
throw UnexpectedNodeType(r.NodeType);
}
Debug.Assert(node != null);
if (parent != null)
{
parent.AppendChildForLoad(node, _doc);
}
else
{
return node;
}
}
while (r.Read());
// when the reader ended before full subtree is read, return whatever we have created so far
if (parent != null)
{
while (parent.ParentNode != null)
{
parent = parent.ParentNode;
}
}
return parent;
}
private XmlAttribute LoadAttributeNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.Attribute);
XmlReader r = _reader;
if (r.IsDefault)
{
return LoadDefaultAttribute();
}
XmlAttribute attr = _doc.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
IXmlSchemaInfo schemaInfo = r.SchemaInfo;
if (schemaInfo != null)
{
attr.XmlName = _doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo);
}
while (r.ReadAttributeValue())
{
XmlNode node;
switch (r.NodeType)
{
case XmlNodeType.Text:
node = _doc.CreateTextNode(r.Value);
break;
case XmlNodeType.EntityReference:
node = _doc.CreateEntityReference(r.LocalName);
if (r.CanResolveEntity)
{
r.ResolveEntity();
LoadAttributeValue(node, false);
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if (node.FirstChild == null)
{
node.AppendChildForLoad(_doc.CreateTextNode(string.Empty), _doc);
}
}
break;
default:
throw UnexpectedNodeType(r.NodeType);
}
Debug.Assert(node != null);
attr.AppendChildForLoad(node, _doc);
}
return attr;
}
private XmlAttribute LoadDefaultAttribute()
{
Debug.Assert(_reader.IsDefault);
XmlReader r = _reader;
XmlAttribute attr = _doc.CreateDefaultAttribute(r.Prefix, r.LocalName, r.NamespaceURI);
IXmlSchemaInfo schemaInfo = r.SchemaInfo;
if (schemaInfo != null)
{
attr.XmlName = _doc.AddAttrXmlName(attr.Prefix, attr.LocalName, attr.NamespaceURI, schemaInfo);
}
LoadAttributeValue(attr, false);
XmlUnspecifiedAttribute defAttr = attr as XmlUnspecifiedAttribute;
// If user overrides CreateDefaultAttribute, then attr will NOT be a XmlUnspecifiedAttribute instance.
if (defAttr != null)
defAttr.SetSpecified(false);
return attr;
}
private void LoadAttributeValue(XmlNode parent, bool direct)
{
XmlReader r = _reader;
while (r.ReadAttributeValue())
{
XmlNode node;
switch (r.NodeType)
{
case XmlNodeType.Text:
node = direct ? new XmlText(r.Value, _doc) : _doc.CreateTextNode(r.Value);
break;
case XmlNodeType.EndEntity:
return;
case XmlNodeType.EntityReference:
node = direct ? new XmlEntityReference(_reader.LocalName, _doc) : _doc.CreateEntityReference(_reader.LocalName);
if (r.CanResolveEntity)
{
r.ResolveEntity();
LoadAttributeValue(node, direct);
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if (node.FirstChild == null)
{
node.AppendChildForLoad(direct ? new XmlText(string.Empty) : _doc.CreateTextNode(string.Empty), _doc);
}
}
break;
default:
throw UnexpectedNodeType(r.NodeType);
}
Debug.Assert(node != null);
parent.AppendChildForLoad(node, _doc);
}
return;
}
private XmlEntityReference LoadEntityReferenceNode(bool direct)
{
Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference);
XmlEntityReference eref = direct ? new XmlEntityReference(_reader.Name, _doc) : _doc.CreateEntityReference(_reader.Name);
if (_reader.CanResolveEntity)
{
_reader.ResolveEntity();
while (_reader.Read() && _reader.NodeType != XmlNodeType.EndEntity)
{
XmlNode node = direct ? LoadNodeDirect() : LoadNode(false);
if (node != null)
{
eref.AppendChildForLoad(node, _doc);
}
}
// Code internally relies on the fact that an EntRef nodes has at least one child (even an empty text node). Ensure that this holds true,
// if the reader does not present any children for the ent-ref
if (eref.LastChild == null)
eref.AppendChildForLoad(_doc.CreateTextNode(string.Empty), _doc);
}
return eref;
}
private XmlDeclaration LoadDeclarationNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.XmlDeclaration);
//parse data
string version = null;
string encoding = null;
string standalone = null;
// Try first to use the reader to get the xml decl "attributes". Since not all readers are required to support this, it is possible to have
// implementations that do nothing
while (_reader.MoveToNextAttribute())
{
switch (_reader.Name)
{
case "version":
version = _reader.Value;
break;
case "encoding":
encoding = _reader.Value;
break;
case "standalone":
standalone = _reader.Value;
break;
default:
Debug.Fail("Unknown reader name");
break;
}
}
// For readers that do not break xml decl into attributes, we must parse the xml decl ourselves. We use version attr, b/c xml decl MUST contain
// at least version attr, so if the reader implements them as attr, then version must be present
if (version == null)
ParseXmlDeclarationValue(_reader.Value, out version, out encoding, out standalone);
return _doc.CreateXmlDeclaration(version, encoding, standalone);
}
private XmlDocumentType LoadDocumentTypeNode()
{
Debug.Assert(_reader.NodeType == XmlNodeType.DocumentType);
String publicId = null;
String systemId = null;
String internalSubset = _reader.Value;
String localName = _reader.LocalName;
while (_reader.MoveToNextAttribute())
{
switch (_reader.Name)
{
case "PUBLIC":
publicId = _reader.Value;
break;
case "SYSTEM":
systemId = _reader.Value;
break;
}
}
XmlDocumentType dtNode = _doc.CreateDocumentType(localName, publicId, systemId, internalSubset);
IDtdInfo dtdInfo = _reader.DtdInfo;
if (dtdInfo != null)
LoadDocumentType(dtdInfo, dtNode);
else
{
//construct our own XmlValidatingReader to parse the DocumentType node so we could get Entities and notations information
ParseDocumentType(dtNode);
}
return dtNode;
}
// LoadNodeDirect does not use creator functions on XmlDocument. It is used loading nodes that are children of entity nodes,
// because we do not want to let users extend these (if we would allow this, XmlDataDocument would have a problem, because
// they do not know that those nodes should not be mapped). It can be also used for an optimized load path when if the
// XmlDocument is not extended if XmlDocumentType and XmlDeclaration handling is added.
private XmlNode LoadNodeDirect()
{
XmlReader r = _reader;
XmlNode parent = null;
do
{
XmlNode node = null;
switch (r.NodeType)
{
case XmlNodeType.Element:
bool fEmptyElement = _reader.IsEmptyElement;
XmlElement element = new XmlElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _doc);
element.IsEmpty = fEmptyElement;
if (_reader.MoveToFirstAttribute())
{
XmlAttributeCollection attributes = element.Attributes;
do
{
XmlAttribute attr = LoadAttributeNodeDirect();
attributes.Append(attr); // special case for load
} while (r.MoveToNextAttribute());
}
// recursively load all children.
if (!fEmptyElement)
{
parent.AppendChildForLoad(element, _doc);
parent = element;
continue;
}
else
{
node = element;
break;
}
case XmlNodeType.EndElement:
Debug.Assert(parent.NodeType == XmlNodeType.Element);
if (parent.ParentNode == null)
{
return parent;
}
parent = parent.ParentNode;
continue;
case XmlNodeType.EntityReference:
node = LoadEntityReferenceNode(true);
break;
case XmlNodeType.EndEntity:
continue;
case XmlNodeType.Attribute:
node = LoadAttributeNodeDirect();
break;
case XmlNodeType.SignificantWhitespace:
node = new XmlSignificantWhitespace(_reader.Value, _doc);
break;
case XmlNodeType.Whitespace:
if (_preserveWhitespace)
{
node = new XmlWhitespace(_reader.Value, _doc);
}
else
{
continue;
}
break;
case XmlNodeType.Text:
node = new XmlText(_reader.Value, _doc);
break;
case XmlNodeType.CDATA:
node = new XmlCDataSection(_reader.Value, _doc);
break;
case XmlNodeType.ProcessingInstruction:
node = new XmlProcessingInstruction(_reader.Name, _reader.Value, _doc);
break;
case XmlNodeType.Comment:
node = new XmlComment(_reader.Value, _doc);
break;
default:
throw UnexpectedNodeType(_reader.NodeType);
}
Debug.Assert(node != null);
if (parent != null)
{
parent.AppendChildForLoad(node, _doc);
}
else
{
return node;
}
}
while (r.Read());
return null;
}
private XmlAttribute LoadAttributeNodeDirect()
{
XmlReader r = _reader;
XmlAttribute attr;
if (r.IsDefault)
{
XmlUnspecifiedAttribute defattr = new XmlUnspecifiedAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc);
LoadAttributeValue(defattr, true);
defattr.SetSpecified(false);
return defattr;
}
else
{
attr = new XmlAttribute(r.Prefix, r.LocalName, r.NamespaceURI, _doc);
LoadAttributeValue(attr, true);
return attr;
}
}
internal void ParseDocumentType(XmlDocumentType dtNode)
{
XmlDocument doc = dtNode.OwnerDocument;
//if xmlresolver is set on doc, use that one, otherwise use the default one being created by xmlvalidatingreader
if (doc.HasSetResolver)
ParseDocumentType(dtNode, true, doc.GetResolver());
else
ParseDocumentType(dtNode, false, null);
}
private void ParseDocumentType(XmlDocumentType dtNode, bool bUseResolver, XmlResolver resolver)
{
_doc = dtNode.OwnerDocument;
XmlParserContext pc = new XmlParserContext(null, new XmlNamespaceManager(_doc.NameTable), null, null, null, null, _doc.BaseURI, string.Empty, XmlSpace.None);
XmlTextReaderImpl tr = new XmlTextReaderImpl("", XmlNodeType.Element, pc);
tr.Namespaces = dtNode.ParseWithNamespaces;
if (bUseResolver)
{
tr.XmlResolver = resolver;
}
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(tr);
IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(_doc.BaseURI, dtNode.Name, dtNode.PublicId, dtNode.SystemId, dtNode.InternalSubset, proxy);
LoadDocumentType(dtdInfo, dtNode);
}
private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode)
{
SchemaInfo schInfo = dtdInfo as SchemaInfo;
if (schInfo == null)
{
throw new XmlException(SR.Xml_InternalError, string.Empty);
}
dtNode.DtdSchemaInfo = schInfo;
if (schInfo != null)
{
//set the schema information into the document
_doc.DtdSchemaInfo = schInfo;
// Notation hashtable
if (schInfo.Notations != null)
{
foreach (SchemaNotation scNot in schInfo.Notations.Values)
{
dtNode.Notations.SetNamedItem(new XmlNotation(scNot.Name.Name, scNot.Pubid, scNot.SystemLiteral, _doc));
}
}
// Entity hashtables
if (schInfo.GeneralEntities != null)
{
foreach (SchemaEntity scEnt in schInfo.GeneralEntities.Values)
{
XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc);
ent.SetBaseURI(scEnt.DeclaredURI);
dtNode.Entities.SetNamedItem(ent);
}
}
if (schInfo.ParameterEntities != null)
{
foreach (SchemaEntity scEnt in schInfo.ParameterEntities.Values)
{
XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc);
ent.SetBaseURI(scEnt.DeclaredURI);
dtNode.Entities.SetNamedItem(ent);
}
}
_doc.Entities = dtNode.Entities;
//extract the elements which has attribute defined as ID from the element declarations
IDictionaryEnumerator elementDecls = schInfo.ElementDecls.GetEnumerator();
if (elementDecls != null)
{
elementDecls.Reset();
while (elementDecls.MoveNext())
{
SchemaElementDecl elementDecl = (SchemaElementDecl)elementDecls.Value;
if (elementDecl.AttDefs != null)
{
IDictionaryEnumerator attDefs = elementDecl.AttDefs.GetEnumerator();
while (attDefs.MoveNext())
{
SchemaAttDef attdef = (SchemaAttDef)attDefs.Value;
if (attdef.Datatype.TokenizedType == XmlTokenizedType.ID)
{
//we only register the XmlElement based on their Prefix/LocalName and skip the namespace
_doc.AddIdInfo(
_doc.AddXmlName(elementDecl.Prefix, elementDecl.Name.Name, string.Empty, null),
_doc.AddAttrXmlName(attdef.Prefix, attdef.Name.Name, string.Empty, null));
break;
}
}
}
}
}
}
}
#pragma warning restore 618
private XmlParserContext GetContext(XmlNode node)
{
String lang = null;
XmlSpace spaceMode = XmlSpace.None;
XmlDocumentType docType = _doc.DocumentType;
String baseURI = _doc.BaseURI;
//constructing xmlnamespace
HashSet<string> prefixes = new HashSet<string>();
XmlNameTable nt = _doc.NameTable;
XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
bool bHasDefXmlnsAttr = false;
// Process all xmlns, xmlns:prefix, xml:space and xml:lang attributes
while (node != null && node != _doc)
{
XmlElement element = node as XmlElement;
if (element != null && element.HasAttributes)
{
mgr.PushScope();
foreach (XmlAttribute attr in element.Attributes)
{
if (attr.Prefix == _doc.strXmlns && !prefixes.Contains(attr.LocalName))
{
// Make sure the next time we will not add this prefix
prefixes.Add(attr.LocalName);
mgr.AddNamespace(attr.LocalName, attr.Value);
}
else if (!bHasDefXmlnsAttr && attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns)
{
// Save the case xmlns="..." where xmlns is the LocalName
mgr.AddNamespace(String.Empty, attr.Value);
bHasDefXmlnsAttr = true;
}
else if (spaceMode == XmlSpace.None && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strSpace)
{
// Save xml:space context
if (attr.Value == "default")
spaceMode = XmlSpace.Default;
else if (attr.Value == "preserve")
spaceMode = XmlSpace.Preserve;
}
else if (lang == null && attr.Prefix == _doc.strXml && attr.LocalName == _doc.strLang)
{
// Save xml:lag context
lang = attr.Value;
}
}
}
node = node.ParentNode;
}
return new XmlParserContext(
nt,
mgr,
(docType == null) ? null : docType.Name,
(docType == null) ? null : docType.PublicId,
(docType == null) ? null : docType.SystemId,
(docType == null) ? null : docType.InternalSubset,
baseURI,
lang,
spaceMode
);
}
internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string innerxmltext, XmlNodeType nt)
{
//the function shouldn't be used to set innerxml for XmlDocument node
Debug.Assert(parentNode.NodeType != XmlNodeType.Document);
_doc = parentNode.OwnerDocument;
Debug.Assert(_doc != null);
XmlParserContext pc = GetContext(parentNode);
_reader = CreateInnerXmlReader(innerxmltext, nt, pc, _doc);
try
{
_preserveWhitespace = true;
bool bOrigLoading = _doc.IsLoading;
_doc.IsLoading = true;
if (nt == XmlNodeType.Entity)
{
XmlNode node = null;
while (_reader.Read() && (node = LoadNodeDirect()) != null)
{
parentNode.AppendChildForLoad(node, _doc);
}
}
else
{
XmlNode node = null;
while (_reader.Read() && (node = LoadNode(true)) != null)
{
parentNode.AppendChildForLoad(node, _doc);
}
}
_doc.IsLoading = bOrigLoading;
}
finally
{
_reader.Close();
}
return pc.NamespaceManager;
}
internal void LoadInnerXmlElement(XmlElement node, string innerxmltext)
{
//construct a tree underneath the node
XmlNamespaceManager mgr = ParsePartialContent(node, innerxmltext, XmlNodeType.Element);
//remove the duplicate namespace
if (node.ChildNodes.Count > 0)
RemoveDuplicateNamespace((XmlElement)node, mgr, false);
}
internal void LoadInnerXmlAttribute(XmlAttribute node, string innerxmltext)
{
ParsePartialContent(node, innerxmltext, XmlNodeType.Attribute);
}
private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, bool fCheckElemAttrs)
{
//remove the duplicate attributes on current node first
mgr.PushScope();
XmlAttributeCollection attrs = elem.Attributes;
int cAttrs = attrs.Count;
if (fCheckElemAttrs && cAttrs > 0)
{
for (int i = cAttrs - 1; i >= 0; --i)
{
XmlAttribute attr = attrs[i];
if (attr.Prefix == _doc.strXmlns)
{
string nsUri = mgr.LookupNamespace(attr.LocalName);
if (nsUri != null)
{
if (attr.Value == nsUri)
elem.Attributes.RemoveNodeAt(i);
}
else
{
// Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
// InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
// If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
// the subsequent InnerXml_set or setting an EntRef inside.
mgr.AddNamespace(attr.LocalName, attr.Value);
}
}
else if (attr.Prefix.Length == 0 && attr.LocalName == _doc.strXmlns)
{
string nsUri = mgr.DefaultNamespace;
if (nsUri != null)
{
if (attr.Value == nsUri)
elem.Attributes.RemoveNodeAt(i);
}
else
{
// Add this namespace, so it we will behave correctly when setting "<bar xmlns:p="BAR"><foo2 xmlns:p="FOO"/></bar>" as
// InnerXml on this foo elem where foo is like this "<foo xmlns:p="FOO"></foo>"
// If do not do this, then we will remove the inner p prefix definition and will let the 1st p to be in scope for
// the subsequent InnerXml_set or setting an EntRef inside.
mgr.AddNamespace(attr.LocalName, attr.Value);
}
}
}
}
//now recursively remove the duplicate attributes on the children
XmlNode child = elem.FirstChild;
while (child != null)
{
XmlElement childElem = child as XmlElement;
if (childElem != null)
RemoveDuplicateNamespace(childElem, mgr, true);
child = child.NextSibling;
}
mgr.PopScope();
}
private String EntitizeName(String name)
{
return "&" + name + ";";
}
//The function is called when expanding the entity when its children being asked
internal void ExpandEntity(XmlEntity ent)
{
ParsePartialContent(ent, EntitizeName(ent.Name), XmlNodeType.Entity);
}
//The function is called when expanding the entity ref. ( inside XmlEntityReference.SetParent )
internal void ExpandEntityReference(XmlEntityReference eref)
{
//when the ent ref is not associated w/ an entity, append an empty string text node as child
_doc = eref.OwnerDocument;
bool bOrigLoadingState = _doc.IsLoading;
_doc.IsLoading = true;
switch (eref.Name)
{
case "lt":
eref.AppendChildForLoad(_doc.CreateTextNode("<"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "gt":
eref.AppendChildForLoad(_doc.CreateTextNode(">"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "amp":
eref.AppendChildForLoad(_doc.CreateTextNode("&"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "apos":
eref.AppendChildForLoad(_doc.CreateTextNode("'"), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
case "quot":
eref.AppendChildForLoad(_doc.CreateTextNode("\""), _doc);
_doc.IsLoading = bOrigLoadingState;
return;
}
XmlNamedNodeMap entities = _doc.Entities;
foreach (XmlEntity ent in entities)
{
if (Ref.Equal(ent.Name, eref.Name))
{
ParsePartialContent(eref, EntitizeName(eref.Name), XmlNodeType.EntityReference);
return;
}
}
//no fit so far
if (!(_doc.ActualLoadingStatus))
{
eref.AppendChildForLoad(_doc.CreateTextNode(""), _doc);
_doc.IsLoading = bOrigLoadingState;
}
else
{
_doc.IsLoading = bOrigLoadingState;
throw new XmlException(SR.Xml_UndeclaredParEntity, eref.Name);
}
}
#pragma warning disable 618
// Creates a XmlValidatingReader suitable for parsing InnerXml strings
private XmlReader CreateInnerXmlReader(String xmlFragment, XmlNodeType nt, XmlParserContext context, XmlDocument doc)
{
XmlNodeType contentNT = nt;
if (contentNT == XmlNodeType.Entity || contentNT == XmlNodeType.EntityReference)
contentNT = XmlNodeType.Element;
XmlTextReaderImpl tr = new XmlTextReaderImpl(xmlFragment, contentNT, context);
tr.XmlValidatingReaderCompatibilityMode = true;
if (doc.HasSetResolver)
{
tr.XmlResolver = doc.GetResolver();
}
if (!(doc.ActualLoadingStatus))
{
tr.DisableUndeclaredEntityCheck = true;
}
Debug.Assert(tr.EntityHandling == EntityHandling.ExpandCharEntities);
XmlDocumentType dtdNode = doc.DocumentType;
if (dtdNode != null)
{
tr.Namespaces = dtdNode.ParseWithNamespaces;
if (dtdNode.DtdSchemaInfo != null)
{
tr.SetDtdInfo(dtdNode.DtdSchemaInfo);
}
else
{
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(tr);
IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(context.BaseURI, context.DocTypeName, context.PublicId, context.SystemId, context.InternalSubset, proxy);
dtdNode.DtdSchemaInfo = dtdInfo as SchemaInfo;
tr.SetDtdInfo(dtdInfo);
}
}
if (nt == XmlNodeType.Entity || nt == XmlNodeType.EntityReference)
{
tr.Read(); //this will skip the first element "wrapper"
tr.ResolveEntity();
}
return tr;
}
#pragma warning restore 618
internal static void ParseXmlDeclarationValue(string strValue, out string version, out string encoding, out string standalone)
{
version = null;
encoding = null;
standalone = null;
XmlTextReaderImpl tempreader = new XmlTextReaderImpl(strValue, (XmlParserContext)null);
try
{
tempreader.Read();
//get version info.
if (tempreader.MoveToAttribute(nameof(version)))
version = tempreader.Value;
//get encoding info
if (tempreader.MoveToAttribute(nameof(encoding)))
encoding = tempreader.Value;
//get standalone info
if (tempreader.MoveToAttribute(nameof(standalone)))
standalone = tempreader.Value;
}
finally
{
tempreader.Close();
}
}
internal static Exception UnexpectedNodeType(XmlNodeType nodetype)
{
return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xml_UnexpectedNodeType, nodetype.ToString()));
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
#pragma warning disable 1591 // disable warning on missing comments
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.Tests.Generated
{
public class MDIncrementalRefreshSessionStatistics
{
public const ushort TemplateId = (ushort)22;
public const byte TemplateVersion = (byte)1;
public const ushort BlockLength = (ushort)9;
public const string SematicType = "X";
private readonly MDIncrementalRefreshSessionStatistics _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public MDIncrementalRefreshSessionStatistics()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = TemplateVersion;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset,
int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(_limit);
_limit = value;
}
}
public const int TransactTimeSchemaId = 60;
public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "UTCTimestamp";
}
return "";
}
public const ulong TransactTimeNullValue = 0x8000000000000000UL;
public const ulong TransactTimeMinValue = 0x0UL;
public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL;
public ulong TransactTime
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 0, value);
}
}
public const int MatchEventIndicatorSchemaId = 5799;
public static string MatchEventIndicatorMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "MultipleCharValue";
}
return "";
}
public MatchEventIndicator MatchEventIndicator
{
get
{
return (MatchEventIndicator)_buffer.Uint8Get(_offset + 8);
}
set
{
_buffer.Uint8Put(_offset + 8, (byte)value);
}
}
private readonly NoMDEntriesGroup _noMDEntries = new NoMDEntriesGroup();
public const long NoMDEntriesSchemaId = 268;
public NoMDEntriesGroup NoMDEntries
{
get
{
_noMDEntries.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _noMDEntries;
}
}
public NoMDEntriesGroup NoMDEntriesCount(int count)
{
_noMDEntries.WrapForEncode(_parentMessage, _buffer, count);
return _noMDEntries;
}
public class NoMDEntriesGroup
{
private readonly GroupSize _dimensions = new GroupSize();
private MDIncrementalRefreshSessionStatistics _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(MDIncrementalRefreshSessionStatistics parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + 3;
}
public void WrapForEncode(MDIncrementalRefreshSessionStatistics parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)19;
_index = -1;
_count = count;
_blockLength = 19;
parentMessage.Limit = parentMessage.Limit + 3;
}
public int Count { get { return _count; } }
public bool HasNext { get { return _index + 1 < _count; } }
public NoMDEntriesGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int MDUpdateActionSchemaId = 279;
public static string MDUpdateActionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public MDUpdateAction MDUpdateAction
{
get
{
return (MDUpdateAction)_buffer.Uint8Get(_offset + 0);
}
set
{
_buffer.Uint8Put(_offset + 0, (byte)value);
}
}
public const int MDEntryTypeSchemaId = 269;
public static string MDEntryTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "char";
}
return "";
}
public MDEntryTypeStatistics MDEntryType
{
get
{
return (MDEntryTypeStatistics)_buffer.CharGet(_offset + 1);
}
set
{
_buffer.CharPut(_offset + 1, (byte)value);
}
}
public const int SecurityIDSchemaId = 48;
public static string SecurityIDMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const int SecurityIDNullValue = -2147483648;
public const int SecurityIDMinValue = -2147483647;
public const int SecurityIDMaxValue = 2147483647;
public int SecurityID
{
get
{
return _buffer.Int32GetLittleEndian(_offset + 2);
}
set
{
_buffer.Int32PutLittleEndian(_offset + 2, value);
}
}
public const int RptSeqSchemaId = 83;
public static string RptSeqMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public const int RptSeqNullValue = -2147483648;
public const int RptSeqMinValue = -2147483647;
public const int RptSeqMaxValue = 2147483647;
public int RptSeq
{
get
{
return _buffer.Int32GetLittleEndian(_offset + 6);
}
set
{
_buffer.Int32PutLittleEndian(_offset + 6, value);
}
}
public const int MDEntryPxSchemaId = 270;
public static string MDEntryPxMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly PRICE _mDEntryPx = new PRICE();
public PRICE MDEntryPx
{
get
{
_mDEntryPx.Wrap(_buffer, _offset + 10, _actingVersion);
return _mDEntryPx;
}
}
public const int OpenCloseSettlFlagSchemaId = 286;
public static string OpenCloseSettlFlagMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "int";
}
return "";
}
public OpenCloseSettlFlag OpenCloseSettlFlag
{
get
{
return (OpenCloseSettlFlag)_buffer.Uint8Get(_offset + 18);
}
set
{
_buffer.Uint8Put(_offset + 18, (byte)value);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.