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; #if ES_BUILD_PCL || ES_BUILD_PN using System.Collections.Generic; #endif using System.Reflection; #if ES_BUILD_STANDALONE using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; #endif #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount => System.Environment.TickCount; public static string GetResourceString(string key, params object?[] args) { string? fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = string.Join(", ", args); return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object?[] args) { return GetResourceString(key, args); } private static readonly System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } #if ES_BUILD_STANDALONE internal static class BitOperations { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint RotateLeft(uint value, int offset) => (value << offset) | (value >> (32 - offset)); public static int PopCount(uint value) { const uint c1 = 0x_55555555u; const uint c2 = 0x_33333333u; const uint c3 = 0x_0F0F0F0Fu; const uint c4 = 0x_01010101u; value = value - ((value >> 1) & c1); value = (value & c2) + ((value >> 2) & c2); value = (((value + (value >> 4)) & c3) * c4) >> 24; return (int)value; } public static int TrailingZeroCount(uint value) { if (value == 0) return 32; int count = 0; while ((value & 1) == 0) { value >>= 1; count++; } return count; } } #endif } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { #if ES_BUILD_PCL [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif internal static class ReflectionExtensions { #if (!ES_BUILD_PCL && !ES_BUILD_PN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type? BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type? BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { #if ES_BUILD_PN return type.GetProperties(); #else return type.GetRuntimeProperties(); #endif } public static MethodInfo? GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type? GetNestedType(this Type type, string nestedTypeName) { TypeInfo? ti = null; foreach (var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object? GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } #if ES_BUILD_STANDALONE internal static partial class Interop { [SuppressUnmanagedCodeSecurityAttribute] internal static partial class Kernel32 { [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern int GetCurrentThreadId(); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern uint GetCurrentProcessId(); } internal static uint GetCurrentProcessId() => Kernel32.GetCurrentProcessId(); } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; #pragma warning disable 0414 namespace System.Reflection.Tests { public class MethodInfoPropertyTests { //Verify ReturnType for Method GetMethod [Fact] public static void TestReturnType1() { VerifyReturnType("GetMethod", "MethodInfo"); } //Verify ReturnType for Method DummyMethod1 [Fact] public static void TestReturnType2() { VerifyReturnType("DummyMethod1", "void"); } //Verify ReturnType for Method DummyMethod2 [Fact] public static void TestReturnType3() { VerifyReturnType("DummyMethod2", "Int32"); } //Verify ReturnType for Method DummyMethod3 [Fact] public static void TestReturnType4() { VerifyReturnType("DummyMethod3", "string"); } //Verify ReturnType for Method DummyMethod4 [Fact] public static void TestReturnType5() { VerifyReturnType("DummyMethod4", "String[]"); } //Verify ReturnType for Method DummyMethod5 [Fact] public static void TestReturnType6() { VerifyReturnType("DummyMethod5", "Boolean"); } //Verify ReturnParameter for Method DummyMethod5 [Fact] public static void TestReturnParam1() { VerifyReturnParameter("DummyMethod5", "Boolean"); } //Verify ReturnParameter for Method DummyMethod4 [Fact] public static void TestReturnParam2() { VerifyReturnParameter("DummyMethod4", "System.String[]"); } //Verify ReturnParameter for Method DummyMethod3 [Fact] public static void TestReturnParam3() { VerifyReturnParameter("DummyMethod3", "System.String"); } //Verify ReturnParameter for Method DummyMethod2 [Fact] public static void TestReturnParam4() { VerifyReturnParameter("DummyMethod2", "Int32"); } //Verify ReturnParameter for Method DummyMethod1 [Fact] public static void TestReturnParam5() { VerifyReturnParameter("DummyMethod1", "Void"); } //Verify ReturnParameter forclassA method method1 [Fact] public static void TestReturnParam6() { MethodInfo mi = GetMethod(typeof(classA), "method1"); ParameterInfo returnParam = mi.ReturnParameter; Assert.Equal(returnParam.Position, -1); } //Verify IsVirtual Property [Fact] public static void TestIsVirtual1() { MethodInfo mi = GetMethod("DummyMethod5"); Assert.True(mi.IsVirtual); } //Verify IsVirtual Property [Fact] public static void TestIsVirtual2() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsVirtual); } //Verify IsPublic Property [Fact] public static void TestIsPublic() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.True(mi.IsPublic); } //Verify IsPrivate Property [Fact] public static void TestIsPrivate() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsPrivate); } //Verify IsStatic Property [Fact] public static void TestIsStatic1() { MethodInfo mi = GetMethod(typeof(classA), "method1"); Assert.True(mi.IsStatic); } //Verify IsStatic Property [Fact] public static void TestIsStatic2() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsStatic); } //Verify IsGenericMethod Property [Fact] public static void TestIsGeneric1() { MethodInfo mi = GetMethod(typeof(classA), "GenericMethod"); Assert.True(mi.IsGenericMethod); } //Verify IsGenericMethod Property [Fact] public static void TestIsGeneric2() { MethodInfo mi = GetMethod(typeof(classA), "method1"); Assert.False(mi.IsGenericMethod); } //Verify IsGenericMethodDefinition Property [Fact] public static void TestIsGenericMethodDefinition1() { MethodInfo mi = GetMethod(typeof(classA), "method1"); Assert.False(mi.IsGenericMethodDefinition); } //Verify IsGenericMethodDefinition Property [Fact] public static void TestIsGenericMethodDefinition2() { MethodInfo mi = GetMethod(typeof(classA), "GenericMethod"); Type[] types = new Type[1]; types[0] = typeof(string); MethodInfo miConstructed = mi.MakeGenericMethod(types); MethodInfo midef = miConstructed.GetGenericMethodDefinition(); Assert.True(midef.IsGenericMethodDefinition); } //Verify IsFinal Property [Fact] public static void TestIsFinal1() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsFinal); } //Verify IsFinal Property [Fact] public static void TestIsFinal2() { MethodInfo mi = GetMethod(typeof(classC), "virtualMethod"); Assert.True(mi.IsFinal); } //Verify IsConstructor Property [Fact] public static void TestIsConstructor1() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsConstructor); } //Verify IsConstructor Property [Fact] public static void TestIsConstructor2() { ConstructorInfo ci = null; TypeInfo ti = typeof(classA).GetTypeInfo(); IEnumerator<ConstructorInfo> allctors = ti.DeclaredConstructors.GetEnumerator(); while (allctors.MoveNext()) { if (allctors.Current != null) { //found method ci = allctors.Current; break; } } Assert.True(ci.IsConstructor); } //Verify IsAbstract Property [Fact] public static void TestIsAbstract1() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsAbstract); } //Verify IsAbstract Property [Fact] public static void TestIsAbstract2() { MethodInfo mi = GetMethod(typeof(classB), "abstractMethod"); Assert.True(mi.IsAbstract); } //Verify IsAssembly Property [Fact] public static void TestIsAssembly() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsAssembly); } //Verify IsFamily Property [Fact] public static void TestIsFamily() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsFamily); } //Verify IsFamilyAndAssembly Property [Fact] public static void TestIsFamilyAndAssembly() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsFamilyAndAssembly); } //Verify IsFamilyOrAssembly Property [Fact] public static void TestIsFamilyOrAssembly() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsFamilyOrAssembly); } //Verify ContainsGenericParameters Property [Fact] public static void TestContainsGenericParameters1() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.ContainsGenericParameters); } //Verify ContainsGenericParameters Property [Fact] public static void TestContainsGenericParameters2() { MethodInfo mi = GetMethod(typeof(classA), "GenericMethod"); Assert.True(mi.ContainsGenericParameters); } //Verify CallingConventions Property [Fact] public static void TestCallingConventions() { MethodInfo mi = GetMethod("DummyMethod1"); CallingConventions myc = mi.CallingConvention; Assert.NotNull(myc); } //Verify IsSpecialName Property [Fact] public static void TestIsSpecialName() { MethodInfo mi = GetMethod("DummyMethod1"); Assert.False(mi.IsSpecialName); } //Verify IsHidebySig Property [Fact] public static void TestIsHidebySig() { MethodInfo mi = GetMethod(typeof(classC), "abstractMethod"); Assert.True(mi.IsHideBySig); } //Verify Attributes Property [Fact] public static void TestAttributes() { MethodInfo mi = GetMethod("DummyMethod1"); MethodAttributes myattr = mi.Attributes; Assert.NotNull(myattr); } //Helper Method to Verify ReturnType public static void VerifyReturnType(string methodName, string returnType) { MethodInfo mi = GetMethod(methodName); Assert.NotNull(mi); Assert.True(mi.Name.Equals(methodName, StringComparison.CurrentCultureIgnoreCase)); Assert.True(mi.ReturnType.Name.Equals(returnType, StringComparison.CurrentCultureIgnoreCase)); } //Helper Method to Verify ReturnParameter public static void VerifyReturnParameter(string methodName, string returnParam) { MethodInfo mi = GetMethod(methodName); Assert.NotNull(mi); Assert.True(mi.Name.Equals(methodName, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(mi.ReturnType, mi.ReturnParameter.ParameterType); Assert.Null(mi.ReturnParameter.Name); } // Helper Method to get MethodInfo public static MethodInfo GetMethod(string method) { return GetMethod(typeof(MethodInfoPropertyTests), method); } // Helper Method to get MethodInfo public static MethodInfo GetMethod(Type t, string method) { TypeInfo ti = t.GetTypeInfo(); IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); MethodInfo mi = null; while (alldefinedMethods.MoveNext()) { if (alldefinedMethods.Current.Name.Equals(method)) { //found method mi = alldefinedMethods.Current; break; } } return mi; } //Methods for Reflection Metadata public void DummyMethod1() { } public int DummyMethod2() { return 111; } public string DummyMethod3() { return "DummyMethod3"; } public virtual String[] DummyMethod4() { System.String[] strarray = new System.String[2]; return strarray; } public virtual bool DummyMethod5() { return true; } } //For Reflection metadata public class classA { public classA() { } public static int method1() { return 100; } public static void method2() { } public static void method3() { } public static void GenericMethod<T>(T toDisplay) { } } public abstract class classB { public abstract void abstractMethod(); public virtual void virtualMethod() { } } public class classC : classB { public sealed override void virtualMethod() { } public override void abstractMethod() { } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Reflection; using System.Xml; using System.Text; using System.Net; using System.IO; using System.Web; namespace Commanigy.Iquomi.Client { /// <summary> /// Displays window showing available Iquomi services. /// </summary> public class FrmToolbox : System.Windows.Forms.Form { private System.Windows.Forms.MenuItem mnuFile; private System.Windows.Forms.MenuItem mnuHelp; private System.Windows.Forms.Panel pnlToolbarCaption; private System.Windows.Forms.Label lblToolbarCaption; private System.Windows.Forms.Label lblToolbarCaptionDescription; private System.Windows.Forms.MenuItem mniFileExit; private System.Windows.Forms.MenuItem mniHelpAbout; private System.Windows.Forms.ListView ltvServices; private System.Windows.Forms.MainMenu mainMenu; private System.Windows.Forms.NotifyIcon notifyIcon; private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.ContextMenu contextMenu1; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.TextBox textBox1; private System.ComponentModel.IContainer components; public FrmToolbox() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // ltvServices.Clear(); /* ServicesListViewItem item = null; item = new ServicesListViewItem(); item.Name = "Notes"; item.URI = "http://localhost:89/iquomi/notes"; item.Form = @"D:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\RequestSOAPServer\NotesService\bin\Debug\NotesService.dll"; item.Text = item.Name; item.ImageIndex = 0; ltvServices.Items.Add(item); item = new ServicesListViewItem(); item.Name = "Contacts"; item.URI = "http://localhost:89/iquomi/contacts"; item.Form = "FrmContactsServices"; item.Text = item.Name; item.ImageIndex = 1; ltvServices.Items.Add(item); */ } /// <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() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FrmToolbox)); System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "Notes", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Window, new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))))}, 0); System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "Contacts", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Window, new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))))}, 1); System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "CD-ROM Collection", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Window, new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))))}, 2); System.Windows.Forms.ListViewItem listViewItem4 = new System.Windows.Forms.ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "Passwords", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Window, new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))))}, 1); System.Windows.Forms.ListViewItem listViewItem5 = new System.Windows.Forms.ListViewItem(new System.Windows.Forms.ListViewItem.ListViewSubItem[] { new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "Favorites", System.Drawing.SystemColors.WindowText, System.Drawing.SystemColors.Window, new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))))}, 0); this.mainMenu = new System.Windows.Forms.MainMenu(); this.mnuFile = new System.Windows.Forms.MenuItem(); this.mniFileExit = new System.Windows.Forms.MenuItem(); this.mnuHelp = new System.Windows.Forms.MenuItem(); this.mniHelpAbout = new System.Windows.Forms.MenuItem(); this.pnlToolbarCaption = new System.Windows.Forms.Panel(); this.textBox1 = new System.Windows.Forms.TextBox(); this.lblToolbarCaptionDescription = new System.Windows.Forms.Label(); this.lblToolbarCaption = new System.Windows.Forms.Label(); this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components); this.imageList = new System.Windows.Forms.ImageList(this.components); this.ltvServices = new System.Windows.Forms.ListView(); this.contextMenu1 = new System.Windows.Forms.ContextMenu(); this.statusBar1 = new System.Windows.Forms.StatusBar(); this.pnlToolbarCaption.SuspendLayout(); this.SuspendLayout(); // // mainMenu // this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuFile, this.mnuHelp}); // // mnuFile // this.mnuFile.Index = 0; this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniFileExit}); this.mnuFile.Text = "&File"; // // mniFileExit // this.mniFileExit.Index = 0; this.mniFileExit.Text = "E&xit"; this.mniFileExit.Click += new System.EventHandler(this.mniFileExit_Click); // // mnuHelp // this.mnuHelp.Index = 1; this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mniHelpAbout}); this.mnuHelp.Text = "&Help"; // // mniHelpAbout // this.mniHelpAbout.Index = 0; this.mniHelpAbout.Text = "&About..."; // // pnlToolbarCaption // this.pnlToolbarCaption.BackColor = System.Drawing.SystemColors.Desktop; this.pnlToolbarCaption.Controls.AddRange(new System.Windows.Forms.Control[] { this.textBox1, this.lblToolbarCaptionDescription, this.lblToolbarCaption}); this.pnlToolbarCaption.Dock = System.Windows.Forms.DockStyle.Top; this.pnlToolbarCaption.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.pnlToolbarCaption.Name = "pnlToolbarCaption"; this.pnlToolbarCaption.Size = new System.Drawing.Size(416, 48); this.pnlToolbarCaption.TabIndex = 0; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(272, 8); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(136, 21); this.textBox1.TabIndex = 2; this.textBox1.Text = "/notes/"; // // lblToolbarCaptionDescription // this.lblToolbarCaptionDescription.BackColor = System.Drawing.Color.Transparent; this.lblToolbarCaptionDescription.Location = new System.Drawing.Point(8, 24); this.lblToolbarCaptionDescription.Name = "lblToolbarCaptionDescription"; this.lblToolbarCaptionDescription.Size = new System.Drawing.Size(456, 23); this.lblToolbarCaptionDescription.TabIndex = 1; this.lblToolbarCaptionDescription.Text = "Pick a service below to start working on your managed data."; // // lblToolbarCaption // this.lblToolbarCaption.AutoSize = true; this.lblToolbarCaption.BackColor = System.Drawing.Color.Transparent; this.lblToolbarCaption.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.lblToolbarCaption.ForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.lblToolbarCaption.Location = new System.Drawing.Point(8, 8); this.lblToolbarCaption.Name = "lblToolbarCaption"; this.lblToolbarCaption.Size = new System.Drawing.Size(150, 14); this.lblToolbarCaption.TabIndex = 0; this.lblToolbarCaption.Text = "Available Iquomi services"; this.lblToolbarCaption.UseMnemonic = false; // // notifyIcon // this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon"))); this.notifyIcon.Text = "IQatium Toolbox"; this.notifyIcon.Visible = true; // // imageList // this.imageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageList.ImageSize = new System.Drawing.Size(32, 32); this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; // // ltvServices // this.ltvServices.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.ltvServices.FullRowSelect = true; this.ltvServices.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.ltvServices.HideSelection = false; this.ltvServices.Items.AddRange(new System.Windows.Forms.ListViewItem[] { listViewItem1, listViewItem2, listViewItem3, listViewItem4, listViewItem5}); this.ltvServices.LargeImageList = this.imageList; this.ltvServices.Location = new System.Drawing.Point(8, 56); this.ltvServices.MultiSelect = false; this.ltvServices.Name = "ltvServices"; this.ltvServices.Size = new System.Drawing.Size(400, 72); this.ltvServices.TabIndex = 3; this.ltvServices.ItemActivate += new System.EventHandler(this.ltvServices_ItemActivate); // // statusBar1 // this.statusBar1.Location = new System.Drawing.Point(0, 131); this.statusBar1.Name = "statusBar1"; this.statusBar1.Size = new System.Drawing.Size(416, 22); this.statusBar1.TabIndex = 4; this.statusBar1.Text = "For Help, press F1"; // // FrmToolbox // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(416, 153); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.statusBar1, this.ltvServices, this.pnlToolbarCaption}); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Menu = this.mainMenu; this.Name = "FrmToolbox"; this.Text = "Iquomi .client"; this.pnlToolbarCaption.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void mniFileExit_Click(object sender, System.EventArgs e) { Application.Exit(); } private bool activateService(ListViewItem item) { if (item == null) return false; /* ServicesListViewItem service = (ServicesListViewItem)item; Console.Out.WriteLine("Executing \"{0}\" ...", service.Name); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(service.URI); req.Headers.Add("XPath", textBox1.Text); // Create a new instance of CredentialCache. CredentialCache credentialCache = new CredentialCache(); // Create a new instance of NetworkCredential using the client // credentials. NetworkCredential credentials = new NetworkCredential("theill", "belle0"); // Add the NetworkCredential to the CredentialCache. credentialCache.Add( new Uri(service.URI), "Digest", credentials ); // Add the CredentialCache to the proxy class credentials. req.Credentials = credentialCache; req.PreAuthenticate = true; req.Timeout = 3000; WebResponse result = null; try { result = req.GetResponse(); Stream ReceiveStream = result.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader sr = new StreamReader(ReceiveStream, encode); XmlTextReader xml = new XmlTextReader(sr); // load DLL with service Assembly serviceAssembly = Assembly.LoadFrom(service.Form); // get class reference Type serviceType = serviceAssembly.GetType("NotesService.FrmNotesService"); // find 'Show' method implemented since service needs to // use a common interface MethodInfo serviceShowMethod = serviceType.GetMethod("Show"); // EventInfo e1 = serviceType.GetEvent("xLoad"); // EventInfo e2 = serviceType.GetEvent("xSave"); // EventInfo e3 = serviceType.GetEvent("xQuery"); // MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("Show"); // // // Obtain a reference to the parameters collection of the MethodInfo instance. // ParameterInfo[] Params = Method.GetParameters(); // // // Display information about method parameters. // // Param = sParam1 // // Type = System.String // // Position = 0 // // Optional=False // foreach (ParameterInfo Param in Params){ // Console.WriteLine("Param=" + Param.Name.ToString()); // Console.WriteLine(" Type=" + Param.ParameterType.ToString()); // Console.WriteLine(" Position=" + Param.Position.ToString()); // Console.WriteLine(" Optional=" + Param.IsOptional.ToString()); // } object serviceObj = serviceAssembly.CreateInstance(serviceType.FullName); serviceShowMethod.Invoke(serviceObj, null); MethodInfo mi = serviceType.GetMethod("xLoad"); mi.Invoke(serviceObj, new object[] { (XmlReader)xml }); } catch (Exception e) { Console.Out.WriteLine(e.StackTrace); } finally { if (result != null) { result.Close(); } } */ return true; } private void ltvServices_ItemActivate(object sender, System.EventArgs e) { ListView lv = (ListView)sender; activateService(lv.FocusedItem); } } }
// 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.Globalization; namespace System.Net { internal static class GlobalLog { [ThreadStatic] private static Stack<ThreadKinds> t_threadKindStack; private static Stack<ThreadKinds> ThreadKindStack { get { if (t_threadKindStack == null) { t_threadKindStack = new Stack<ThreadKinds>(); } return t_threadKindStack; } } internal static ThreadKinds CurrentThreadKind { get { return ThreadKindStack.Count > 0 ? ThreadKindStack.Peek() : ThreadKinds.Other; } } internal static IDisposable SetThreadKind(ThreadKinds kind) { if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown) { throw new InternalException(); } // Ignore during shutdown. if (Environment.HasShutdownStarted) { return null; } ThreadKinds threadKind = CurrentThreadKind; ThreadKinds source = threadKind & ThreadKinds.SourceMask; // Special warnings when doing dangerous things on a thread. if ((threadKind & ThreadKinds.User) != 0 && (kind & ThreadKinds.System) != 0) { EventSourceLogging.Log.WarningMessage("Thread changed from User to System; user's thread shouldn't be hijacked."); } if ((threadKind & ThreadKinds.Async) != 0 && (kind & ThreadKinds.Sync) != 0) { EventSourceLogging.Log.WarningMessage("Thread changed from Async to Sync, may block an Async thread."); } else if ((threadKind & (ThreadKinds.Other | ThreadKinds.CompletionPort)) == 0 && (kind & ThreadKinds.Sync) != 0) { EventSourceLogging.Log.WarningMessage("Thread from a limited resource changed to Sync, may deadlock or bottleneck."); } ThreadKindStack.Push( (((kind & ThreadKinds.OwnerMask) == 0 ? threadKind : kind) & ThreadKinds.OwnerMask) | (((kind & ThreadKinds.SyncMask) == 0 ? threadKind : kind) & ThreadKinds.SyncMask) | (kind & ~(ThreadKinds.OwnerMask | ThreadKinds.SyncMask)) | source); if (CurrentThreadKind != threadKind && IsEnabled) { Print("Thread becomes:(" + CurrentThreadKind.ToString() + ")"); } return new ThreadKindFrame(); } private class ThreadKindFrame : IDisposable { private readonly int _frameNumber; internal ThreadKindFrame() { _frameNumber = ThreadKindStack.Count; } void IDisposable.Dispose() { // Ignore during shutdown. if (Environment.HasShutdownStarted) { return; } if (_frameNumber != ThreadKindStack.Count) { throw new InternalException(); } ThreadKinds previous = ThreadKindStack.Pop(); if (CurrentThreadKind != previous && IsEnabled) { Print("Thread reverts:(" + CurrentThreadKind.ToString() + ")"); } } } internal static void SetThreadSource(ThreadKinds source) { if ((source & ThreadKinds.SourceMask) != source || source == ThreadKinds.Unknown) { throw new ArgumentException("Must specify the thread source.", "source"); } if (ThreadKindStack.Count == 0) { ThreadKindStack.Push(source); return; } if (ThreadKindStack.Count > 1) { EventSourceLogging.Log.WarningMessage("SetThreadSource must be called at the base of the stack, or the stack has been corrupted."); while (ThreadKindStack.Count > 1) { ThreadKindStack.Pop(); } } if (ThreadKindStack.Peek() != source) { EventSourceLogging.Log.WarningMessage("The stack has been corrupted."); ThreadKinds last = ThreadKindStack.Pop() & ThreadKinds.SourceMask; if (last != source && last != ThreadKinds.Other && IsEnabled) { AssertFormat("Thread source changed.|Was:({0}) Now:({1})", last, source); } ThreadKindStack.Push(source); } } internal static void ThreadContract(ThreadKinds kind, string errorMsg) { ThreadContract(kind, ThreadKinds.SafeSources, errorMsg); } internal static void ThreadContract(ThreadKinds kind, ThreadKinds allowedSources, string errorMsg) { if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown || (allowedSources & ThreadKinds.SourceMask) != allowedSources) { throw new InternalException(); } if (IsEnabled) { ThreadKinds threadKind = CurrentThreadKind; if ((threadKind & allowedSources) != 0) { AssertFormat(errorMsg, "Thread Contract Violation.|Expected source:({0}) Actual source:({1})", allowedSources, threadKind & ThreadKinds.SourceMask); } if ((threadKind & kind) == kind) { AssertFormat(errorMsg, "Thread Contract Violation.|Expected kind:({0}) Actual kind:({1})", kind, threadKind & ~ThreadKinds.SourceMask); } } } public static void Print(string msg) { EventSourceLogging.Log.DebugMessage(msg); } public static void Enter(string functionName) { EventSourceLogging.Log.FunctionStart(functionName); } public static void Enter(string functionName, string parameters) { EventSourceLogging.Log.FunctionStart(functionName, parameters); } public static void AssertFormat(string messageFormat, params object[] data) { string fullMessage = string.Format(CultureInfo.InvariantCulture, messageFormat, data); int pipeIndex = fullMessage.IndexOf('|'); if (pipeIndex == -1) { Assert(fullMessage); } else { int detailLength = fullMessage.Length - pipeIndex - 1; Assert(fullMessage.Substring(0, pipeIndex), detailLength > 0 ? fullMessage.Substring(pipeIndex + 1, detailLength) : null); } } public static void Assert(string message) { Assert(message, null); } public static void Assert(string message, string detailMessage) { EventSourceLogging.Log.AssertFailed(message, detailMessage); } public static void Leave(string functionName) { EventSourceLogging.Log.FunctionStop(functionName); } public static void Leave(string functionName, string result) { EventSourceLogging.Log.FunctionStop(functionName, result); } public static void Leave(string functionName, int returnval) { EventSourceLogging.Log.FunctionStop(functionName, returnval.ToString()); } public static void Leave(string functionName, bool returnval) { EventSourceLogging.Log.FunctionStop(functionName, returnval.ToString()); } public static void Dump(byte[] buffer, int length) { Dump(buffer, 0, length); } public static void Dump(byte[] buffer, int offset, int length) { string warning = buffer == null ? "buffer is null" : offset >= buffer.Length ? "offset out of range" : (length < 0) || (length > buffer.Length - offset) ? "length out of range" : null; if (warning != null) { EventSourceLogging.Log.WarningDumpArray(warning); return; } var bufferSegment = new byte[length]; Array.Copy(buffer, offset, bufferSegment, 0, length); EventSourceLogging.Log.DebugDumpArray(bufferSegment); } public static bool IsEnabled { get { return EventSourceLogging.Log.IsEnabled(); } } } [Flags] internal enum ThreadKinds { Unknown = 0x0000, // Mutually exclusive. User = 0x0001, // Thread has entered via an API. System = 0x0002, // Thread has entered via a system callback (e.g. completion port) or is our own thread. // Mutually exclusive. Sync = 0x0004, // Thread should block. Async = 0x0008, // Thread should not block. // Mutually exclusive, not always known for a user thread. Never changes. Timer = 0x0010, // Thread is the timer thread. (Can't call user code.) CompletionPort = 0x0020, // Thread is a ThreadPool completion-port thread. Worker = 0x0040, // Thread is a ThreadPool worker thread. Finalization = 0x0080, // Thread is the finalization thread. Other = 0x0100, // Unknown source. OwnerMask = User | System, SyncMask = Sync | Async, SourceMask = Timer | CompletionPort | Worker | Finalization | Other, // Useful "macros" SafeSources = SourceMask & ~(Timer | Finalization), // Methods that "unsafe" sources can call must be explicitly marked. ThreadPool = CompletionPort | Worker, // Like Thread.CurrentThread.IsThreadPoolThread } }
// <copyright file="DesiredCapabilities.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Remote { /// <summary> /// Class to Create the capabilities of the browser you require for <see cref="IWebDriver"/>. /// If you wish to use default values use the static methods /// </summary> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public class DesiredCapabilities : ICapabilities, IHasCapabilitiesDictionary { private readonly Dictionary<string, object> capabilities = new Dictionary<string, object>(); /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param> /// <param name="version">Version of the browser</param> /// <param name="platform">The platform it works on</param> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public DesiredCapabilities(string browser, string version, Platform platform) { this.SetCapability(CapabilityType.BrowserName, browser); this.SetCapability(CapabilityType.Version, version); this.SetCapability(CapabilityType.Platform, platform); } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public DesiredCapabilities() { } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="rawMap">Dictionary of items for the remote driver</param> /// <example> /// <code> /// DesiredCapabilities capabilities = new DesiredCapabilities(new Dictionary<![CDATA[<string,object>]]>(){["browserName","firefox"],["version",string.Empty],["javaScript",true]}); /// </code> /// </example> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public DesiredCapabilities(Dictionary<string, object> rawMap) { if (rawMap != null) { foreach (string key in rawMap.Keys) { if (key == CapabilityType.Platform) { object raw = rawMap[CapabilityType.Platform]; string rawAsString = raw as string; Platform rawAsPlatform = raw as Platform; if (rawAsString != null) { this.SetCapability(CapabilityType.Platform, Platform.FromString(rawAsString)); } else if (rawAsPlatform != null) { this.SetCapability(CapabilityType.Platform, rawAsPlatform); } } else { this.SetCapability(key, rawMap[key]); } } } } /// <summary> /// Initializes a new instance of the <see cref="DesiredCapabilities"/> class /// </summary> /// <param name="browser">Name of the browser e.g. firefox, internet explorer, safari</param> /// <param name="version">Version of the browser</param> /// <param name="platform">The platform it works on</param> /// <param name="isSpecCompliant">Sets a value indicating whether the capabilities are /// compliant with the W3C WebDriver specification.</param> internal DesiredCapabilities(string browser, string version, Platform platform, bool isSpecCompliant) { this.SetCapability(CapabilityType.BrowserName, browser); this.SetCapability(CapabilityType.Version, version); this.SetCapability(CapabilityType.Platform, platform); } /// <summary> /// Gets the browser name /// </summary> public string BrowserName { get { string name = string.Empty; object capabilityValue = this.GetCapability(CapabilityType.BrowserName); if (capabilityValue != null) { name = capabilityValue.ToString(); } return name; } } /// <summary> /// Gets or sets the platform /// </summary> public Platform Platform { get { return this.GetCapability(CapabilityType.Platform) as Platform ?? new Platform(PlatformType.Any); } set { this.SetCapability(CapabilityType.Platform, value); } } /// <summary> /// Gets the browser version /// </summary> public string Version { get { string browserVersion = string.Empty; object capabilityValue = this.GetCapability(CapabilityType.Version); if (capabilityValue != null) { browserVersion = capabilityValue.ToString(); } return browserVersion; } } /// <summary> /// Gets or sets a value indicating whether the browser accepts SSL certificates. /// </summary> public bool AcceptInsecureCerts { get { bool acceptSSLCerts = false; object capabilityValue = this.GetCapability(CapabilityType.AcceptInsecureCertificates); if (capabilityValue != null) { acceptSSLCerts = (bool)capabilityValue; } return acceptSSLCerts; } set { this.SetCapability(CapabilityType.AcceptInsecureCertificates, value); } } /// <summary> /// Gets the underlying Dictionary for a given set of capabilities. /// </summary> Dictionary<string, object> IHasCapabilitiesDictionary.CapabilitiesDictionary { get { return this.CapabilitiesDictionary; } } /// <summary> /// Gets the underlying Dictionary for a given set of capabilities. /// </summary> internal Dictionary<string, object> CapabilitiesDictionary { get { return this.capabilities; } } /// <summary> /// Gets the capability value with the specified name. /// </summary> /// <param name="capabilityName">The name of the capability to get.</param> /// <returns>The value of the capability.</returns> /// <exception cref="ArgumentException"> /// The specified capability name is not in the set of capabilities. /// </exception> public object this[string capabilityName] { get { if (!this.capabilities.ContainsKey(capabilityName)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName)); } return this.capabilities[capabilityName]; } set { this.capabilities[capabilityName] = value; } } /// <summary> /// Gets a value indicating whether the browser has a given capability. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>Returns <see langword="true"/> if the browser has the capability; otherwise, <see langword="false"/>.</returns> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public bool HasCapability(string capability) { return this.capabilities.ContainsKey(capability); } /// <summary> /// Gets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>An object associated with the capability, or <see langword="null"/> /// if the capability is not set on the browser.</returns> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public object GetCapability(string capability) { object capabilityValue = null; if (this.capabilities.ContainsKey(capability)) { capabilityValue = this.capabilities[capability]; string capabilityValueString = capabilityValue as string; if (capability == CapabilityType.Platform && capabilityValueString != null) { capabilityValue = Platform.FromString(capabilityValue.ToString()); } } return capabilityValue; } /// <summary> /// Sets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <param name="capabilityValue">The value for the capability.</param> [Obsolete("Use of DesiredCapabilities has been deprecated in favor of browser-specific Options classes")] public void SetCapability(string capability, object capabilityValue) { // Handle the special case of Platform objects. These should // be stored in the underlying dictionary as their protocol // string representation. Platform platformCapabilityValue = capabilityValue as Platform; if (platformCapabilityValue != null) { this.capabilities[capability] = platformCapabilityValue.ProtocolPlatformType; } else { this.capabilities[capability] = capabilityValue; } } /// <summary> /// Return HashCode for the DesiredCapabilities that has been created /// </summary> /// <returns>Integer of HashCode generated</returns> public override int GetHashCode() { int result; result = this.BrowserName != null ? this.BrowserName.GetHashCode() : 0; result = (31 * result) + (this.Version != null ? this.Version.GetHashCode() : 0); result = (31 * result) + (this.Platform != null ? this.Platform.GetHashCode() : 0); return result; } /// <summary> /// Return a string of capabilities being used /// </summary> /// <returns>String of capabilities being used</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Capabilities [BrowserName={0}, Platform={1}, Version={2}]", this.BrowserName, this.Platform.PlatformType.ToString(), this.Version); } /// <summary> /// Compare two DesiredCapabilities and will return either true or false /// </summary> /// <param name="obj">DesiredCapabilities you wish to compare</param> /// <returns>true if they are the same or false if they are not</returns> public override bool Equals(object obj) { if (this == obj) { return true; } DesiredCapabilities other = obj as DesiredCapabilities; if (other == null) { return false; } if (this.BrowserName != null ? this.BrowserName != other.BrowserName : other.BrowserName != null) { return false; } if (!this.Platform.IsPlatformType(other.Platform.PlatformType)) { return false; } if (this.Version != null ? this.Version != other.Version : other.Version != null) { return false; } return true; } /// <summary> /// Returns a read-only version of this capabilities object. /// </summary> /// <returns>A read-only version of this capabilities object.</returns> internal ReadOnlyDesiredCapabilities AsReadOnly() { ReadOnlyDesiredCapabilities readOnlyCapabilities = new ReadOnlyDesiredCapabilities(this); return readOnlyCapabilities; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using Encog.Util.CSV; using Encog.Util; namespace Encog.Persist { /// <summary> /// Used to read an Encog EG/EGA file. EG files are used to hold Encog objects. /// EGA files are used to hold Encog Analyst scripts. /// </summary> /// public class EncogReadHelper { /// <summary> /// The lines read from the file. /// </summary> /// private readonly IList<String> lines; /// <summary> /// The file being read. /// </summary> /// private readonly TextReader reader; /// <summary> /// The current section name. /// </summary> /// private String currentSectionName; /// <summary> /// The current subsection name. /// </summary> /// private String currentSubSectionName; /// <summary> /// The current section name. /// </summary> /// private EncogFileSection section; /// <summary> /// Construct the object. /// </summary> /// /// <param name="mask0">The input stream.</param> public EncogReadHelper(Stream mask0) { lines = new List<String>(); currentSectionName = ""; currentSubSectionName = ""; reader = new StreamReader(mask0); } /// <summary> /// Close the file. /// </summary> /// public void Close() { try { reader.Close(); } catch (IOException e) { throw new PersistError(e); } } /// <summary> /// Read the next section. /// </summary> /// /// <returns>The next section.</returns> public EncogFileSection ReadNextSection() { try { String line; var largeArrays = new List<double[]>(); while ((line = reader.ReadLine()) != null) { line = line.Trim(); // is it a comment if (line.StartsWith("//")) { continue; } // is it a section or subsection else if (line.StartsWith("[")) { // handle previous section section = new EncogFileSection( currentSectionName, currentSubSectionName); foreach (String str in lines) { section.Lines.Add(str); } // now begin the new section lines.Clear(); String s = line.Substring(1).Trim(); if (!s.EndsWith("]")) { throw new PersistError("Invalid section: " + line); } s = s.Substring(0, (line.Length - 2) - (0)); int idx = s.IndexOf(':'); if (idx == -1) { currentSectionName = s; currentSubSectionName = ""; } else { if (currentSectionName.Length < 1) { throw new PersistError( "Can't begin subsection when a section has not yet been defined: " + line); } String newSection = s.Substring(0, (idx) - (0)); String newSubSection = s.Substring(idx + 1); if (!newSection.Equals(currentSectionName)) { throw new PersistError("Can't begin subsection " + line + ", while we are still in the section: " + currentSectionName); } currentSubSectionName = newSubSection; } section.LargeArrays = largeArrays; return section; } else if (line.Length < 1) { continue; } else if (line.StartsWith("##double")) { double[] d = ReadLargeArray(line); largeArrays.Add(d); } else { if (currentSectionName.Length < 1) { throw new PersistError( "Unknown command before first section: " + line); } lines.Add(line); } } if (currentSectionName.Length == 0) { return null; } section = new EncogFileSection(currentSectionName, currentSubSectionName); foreach (String l in lines) { section.Lines.Add(l); } currentSectionName = ""; currentSubSectionName = ""; section.LargeArrays = largeArrays; return section; } catch (IOException ex) { throw new PersistError(ex); } } /// <summary> /// Called internally to read a large array. /// </summary> /// <param name="line">The line containing the beginning of a large array.</param> /// <returns>The array read.</returns> private double[] ReadLargeArray(String line) { String str = line.Substring(9); int l = int.Parse(str); double[] result = new double[l]; int index = 0; while ((line = this.reader.ReadLine()) != null) { line = line.Trim(); // is it a comment if (line.StartsWith("//")) { continue; } else if (line.StartsWith("##end")) { break; } double[] t = NumberList.FromList(CSVFormat.EgFormat, line); EngineArray.ArrayCopy(t, 0, result, index, t.Length); index += t.Length; } return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataFactory { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Azure Data Factory V2 management API provides a RESTful set of web /// services that interact with Azure Data Factory V2 services. /// </summary> public partial class DataFactoryManagementClient : ServiceClient<DataFactoryManagementClient>, IDataFactoryManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription identifier. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the IFactoriesOperations. /// </summary> public virtual IFactoriesOperations Factories { get; private set; } /// <summary> /// Gets the IIntegrationRuntimesOperations. /// </summary> public virtual IIntegrationRuntimesOperations IntegrationRuntimes { get; private set; } /// <summary> /// Gets the ILinkedServicesOperations. /// </summary> public virtual ILinkedServicesOperations LinkedServices { get; private set; } /// <summary> /// Gets the IDatasetsOperations. /// </summary> public virtual IDatasetsOperations Datasets { get; private set; } /// <summary> /// Gets the IPipelinesOperations. /// </summary> public virtual IPipelinesOperations Pipelines { get; private set; } /// <summary> /// Gets the IPipelineRunsOperations. /// </summary> public virtual IPipelineRunsOperations PipelineRuns { get; private set; } /// <summary> /// Gets the IActivityRunsOperations. /// </summary> public virtual IActivityRunsOperations ActivityRuns { get; private set; } /// <summary> /// Gets the ITriggersOperations. /// </summary> public virtual ITriggersOperations Triggers { get; private set; } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataFactoryManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DataFactoryManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DataFactoryManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected DataFactoryManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DataFactoryManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DataFactoryManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DataFactoryManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DataFactoryManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public DataFactoryManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Operations = new Operations(this); Factories = new FactoriesOperations(this); IntegrationRuntimes = new IntegrationRuntimesOperations(this); LinkedServices = new LinkedServicesOperations(this); Datasets = new DatasetsOperations(this); Pipelines = new PipelinesOperations(this); PipelineRuns = new PipelineRunsOperations(this); ActivityRuns = new ActivityRunsOperations(this); Triggers = new TriggersOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2017-09-01-preview"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<IntegrationRuntime>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<IntegrationRuntime>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<IntegrationRuntimeStatus>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<IntegrationRuntimeStatus>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<LinkedService>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<LinkedService>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Dataset>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Dataset>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Activity>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Activity>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Trigger>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Trigger>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<WebLinkedServiceTypeProperties>("authenticationType")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<WebLinkedServiceTypeProperties>("authenticationType")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<AzureKeyVaultReference>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<AzureKeyVaultReference>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DatasetCompression>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DatasetCompression>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DatasetStorageFormat>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DatasetStorageFormat>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DatasetPartitionValue>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DatasetPartitionValue>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<CopySource>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<CopySource>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<CopyTranslator>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<CopyTranslator>("type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<CopySink>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<CopySink>("type")); CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
#region License /* * HttpListenerPrefixCollection.cs * * This code is derived from HttpListenerPrefixCollection.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <[email protected]> */ #endregion using System; using System.Collections; using System.Collections.Generic; namespace CustomWebSocketSharp.Net { /// <summary> /// Provides the collection used to store the URI prefixes for the <see cref="HttpListener"/>. /// </summary> /// <remarks> /// The <see cref="HttpListener"/> responds to the request which has a requested URI that /// the prefixes most closely match. /// </remarks> public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable { #region Private Fields private HttpListener _listener; private List<string> _prefixes; #endregion #region Internal Constructors internal HttpListenerPrefixCollection (HttpListener listener) { _listener = listener; _prefixes = new List<string> (); } #endregion #region Public Properties /// <summary> /// Gets the number of prefixes in the collection. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of prefixes. /// </value> public int Count { get { return _prefixes.Count; } } /// <summary> /// Gets a value indicating whether the access to the collection is read-only. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether the access to the collection is synchronized. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsSynchronized { get { return false; } } #endregion #region Public Methods /// <summary> /// Adds the specified <paramref name="uriPrefix"/> to the collection. /// </summary> /// <param name="uriPrefix"> /// A <see cref="string"/> that represents the URI prefix to add. The prefix must be /// a well-formed URI prefix with http or https scheme, and must end with a <c>'/'</c>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="uriPrefix"/> is invalid. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this collection is closed. /// </exception> public void Add (string uriPrefix) { _listener.CheckDisposed (); HttpListenerPrefix.CheckPrefix (uriPrefix); if (_prefixes.Contains (uriPrefix)) return; _prefixes.Add (uriPrefix); if (_listener.IsListening) EndPointManager.AddPrefix (uriPrefix, _listener); } /// <summary> /// Removes all URI prefixes from the collection. /// </summary> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this collection is closed. /// </exception> public void Clear () { _listener.CheckDisposed (); _prefixes.Clear (); if (_listener.IsListening) EndPointManager.RemoveListener (_listener); } /// <summary> /// Returns a value indicating whether the collection contains the specified /// <paramref name="uriPrefix"/>. /// </summary> /// <returns> /// <c>true</c> if the collection contains <paramref name="uriPrefix"/>; /// otherwise, <c>false</c>. /// </returns> /// <param name="uriPrefix"> /// A <see cref="string"/> that represents the URI prefix to test. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this collection is closed. /// </exception> public bool Contains (string uriPrefix) { _listener.CheckDisposed (); if (uriPrefix == null) throw new ArgumentNullException ("uriPrefix"); return _prefixes.Contains (uriPrefix); } /// <summary> /// Copies the contents of the collection to the specified <see cref="Array"/>. /// </summary> /// <param name="array"> /// An <see cref="Array"/> that receives the URI prefix strings in the collection. /// </param> /// <param name="offset"> /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this collection is closed. /// </exception> public void CopyTo (Array array, int offset) { _listener.CheckDisposed (); ((ICollection) _prefixes).CopyTo (array, offset); } /// <summary> /// Copies the contents of the collection to the specified array of <see cref="string"/>. /// </summary> /// <param name="array"> /// An array of <see cref="string"/> that receives the URI prefix strings in the collection. /// </param> /// <param name="offset"> /// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this collection is closed. /// </exception> public void CopyTo (string[] array, int offset) { _listener.CheckDisposed (); _prefixes.CopyTo (array, offset); } /// <summary> /// Gets the enumerator used to iterate through the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.IEnumerator{string}"/> instance used to iterate /// through the collection. /// </returns> public IEnumerator<string> GetEnumerator () { return _prefixes.GetEnumerator (); } /// <summary> /// Removes the specified <paramref name="uriPrefix"/> from the collection. /// </summary> /// <returns> /// <c>true</c> if <paramref name="uriPrefix"/> is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="uriPrefix"> /// A <see cref="string"/> that represents the URI prefix to remove. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this collection is closed. /// </exception> public bool Remove (string uriPrefix) { _listener.CheckDisposed (); if (uriPrefix == null) throw new ArgumentNullException ("uriPrefix"); var ret = _prefixes.Remove (uriPrefix); if (ret && _listener.IsListening) EndPointManager.RemovePrefix (uriPrefix, _listener); return ret; } #endregion #region Explicit Interface Implementations /// <summary> /// Gets the enumerator used to iterate through the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> instance used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator () { return _prefixes.GetEnumerator (); } #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 System; using System.Collections.Generic; using System.Linq; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Diagnostics; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.UnitTests; using Avalonia.VisualTree; using JetBrains.dotMemoryUnit; using Moq; using Xunit; using Xunit.Abstractions; namespace Avalonia.LeakTests { [DotMemoryUnit(FailIfRunWithoutSupport = false)] public class ControlTests { public ControlTests(ITestOutputHelper atr) { DotMemoryUnitTestOutput.SetOutputMethod(atr.WriteLine); } [Fact] public void Canvas_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new Canvas() }; window.Show(); // Do a layout and make sure that Canvas gets added to visual tree. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void Named_Canvas_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new Canvas { Name = "foo" } }; window.Show(); // Do a layout and make sure that Canvas gets added to visual tree. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<Canvas>(window.Find<Canvas>("foo")); Assert.IsType<Canvas>(window.Presenter.Child); // Clear the content and ensure the Canvas is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void ScrollViewer_With_Content_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new ScrollViewer { Content = new Canvas() } }; window.Show(); // Do a layout and make sure that ScrollViewer gets added to visual tree and its // template applied. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<ScrollViewer>(window.Presenter.Child); Assert.IsType<Canvas>(((ScrollViewer)window.Presenter.Child).Presenter.Child); // Clear the content and ensure the ScrollViewer is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Canvas>()).ObjectsCount)); } } [Fact] public void TextBox_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { Content = new TextBox() }; window.Show(); // Do a layout and make sure that TextBox gets added to visual tree and its // template applied. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<TextBox>(window.Presenter.Child); Assert.NotEmpty(window.Presenter.Child.GetVisualChildren()); // Clear the content and ensure the TextBox is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); } } [Fact] public void TextBox_With_Xaml_Binding_Is_Freed() { using (Start()) { Func<Window> run = () => { var window = new Window { DataContext = new Node { Name = "foo" }, Content = new TextBox() }; var binding = new Avalonia.Markup.Xaml.Data.Binding { Path = "Name" }; var textBox = (TextBox)window.Content; textBox.Bind(TextBox.TextProperty, binding); window.Show(); // Do a layout and make sure that TextBox gets added to visual tree and its // Text property set. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.IsType<TextBox>(window.Presenter.Child); Assert.Equal("foo", ((TextBox)window.Presenter.Child).Text); // Clear the content and DataContext and ensure the TextBox is removed. window.Content = null; window.DataContext = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TextBox>()).ObjectsCount)); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<Node>()).ObjectsCount)); } } [Fact] public void TextBox_Class_Listeners_Are_Freed() { using (Start()) { TextBox textBox; var window = new Window { Content = textBox = new TextBox() }; window.Show(); // Do a layout and make sure that TextBox gets added to visual tree and its // template applied. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.Same(textBox, window.Presenter.Child); // Get the border from the TextBox template. var border = textBox.GetTemplateChildren().FirstOrDefault(x => x.Name == "border"); // The TextBox should have subscriptions to its Classes collection from the // default theme. Assert.NotEmpty(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers()); // Clear the content and ensure the TextBox is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); // Check that the TextBox has no subscriptions to its Classes collection. Assert.Null(((INotifyCollectionChangedDebug)textBox.Classes).GetCollectionChangedSubscribers()); } } [Fact] public void TreeView_Is_Freed() { using (Start()) { Func<Window> run = () => { var nodes = new[] { new Node { Children = new[] { new Node() }, } }; TreeView target; var window = new Window { Content = target = new TreeView { DataTemplates = { new FuncTreeDataTemplate<Node>( x => new TextBlock { Text = x.Name }, x => x.Children) }, Items = nodes } }; window.Show(); // Do a layout and make sure that TreeViewItems get realized. LayoutManager.Instance.ExecuteInitialLayoutPass(window); Assert.Single(target.ItemContainerGenerator.Containers); // Clear the content and ensure the TreeView is removed. window.Content = null; LayoutManager.Instance.ExecuteLayoutPass(); Assert.Null(window.Presenter.Child); return window; }; var result = run(); dotMemory.Check(memory => Assert.Equal(0, memory.GetObjects(where => where.Type.Is<TreeView>()).ObjectsCount)); } } [Fact] public void RendererIsDisposed() { using (Start()) { var renderer = new Mock<IRenderer>(); renderer.Setup(x => x.Dispose()); var impl = new Mock<IWindowImpl>(); impl.SetupGet(x => x.Scaling).Returns(1); impl.SetupProperty(x => x.Closed); impl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object); impl.Setup(x => x.Dispose()).Callback(() => impl.Object.Closed()); AvaloniaLocator.CurrentMutable.Bind<IWindowingPlatform>() .ToConstant(new MockWindowingPlatform(() => impl.Object)); var window = new Window() { Content = new Button() }; window.Show(); window.Close(); renderer.Verify(r => r.Dispose()); } } private IDisposable Start() { return UnitTestApplication.Start(TestServices.StyledWindow); } private class Node { public string Name { get; set; } public IEnumerable<Node> Children { get; set; } } private class NullRenderer : IRenderer { public bool DrawFps { get; set; } public bool DrawDirtyRects { get; set; } public void AddDirty(IVisual visual) { } public void Dispose() { } public IEnumerable<IVisual> HitTest(Point p, IVisual root, Func<IVisual, bool> filter) => null; public void Paint(Rect rect) { } public void Resized(Size size) { } public void Start() { } public void Stop() { } } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections.Generic; namespace UMA.CharacterSystem { //Because this is a class for user generated content it is marked as partial so it can be extended without modifying the underlying code public partial class UMAWardrobeCollection : UMATextRecipe { [Tooltip("Cover images for the collection as a whole. Use these for a promotional images for this collection, presenting the goodies inside.")] public List<Sprite> coverImages = new List<Sprite>(); public WardrobeCollectionList wardrobeCollection = new WardrobeCollectionList(); [Tooltip("WardrobeCollections can also contain an arbitrary list of wardrobeRecipes, not associated with any particular race.You can use this to make a 'hairStyles' pack or a 'tattoos' pack for example")] public List<string> arbitraryRecipes = new List<string>(); #region CONSTRUCTOR public UMAWardrobeCollection() { recipeType = "WardrobeCollection"; wardrobeSlot = "FullOutfit"; } #endregion #region PUBLIC METHODS /// <summary> /// Gets the CoverImage for the collection at the desired index (if set) if none is set falls back to the first wardrobeThumb (if set) /// </summary> public Sprite GetCoverImage(int desiredIndex = 0) { if (coverImages.Count > desiredIndex) { return coverImages[desiredIndex]; } else if (coverImages.Count > 0) { return coverImages[0]; } else if (wardrobeRecipeThumbs.Count > 0) { return wardrobeRecipeThumbs[0].thumb; } else { return null; } } /// <summary> /// Requests each recipe in the Collection from DynamicCharacterSystem (optionally limited by race) which will trigger the download of the recipes if they are in asset bundles. /// </summary> public void EnsureLocalAvailability(string forRace = "") { var thisDCS = (UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem); if (thisDCS == null) return; //Ensure WardrobeCollection items var thisRecipeNames = wardrobeCollection.GetAllRecipeNamesInCollection(forRace); if (thisRecipeNames.Count > 0) { //we maybe adding recipes for races we have not downloaded yet so make sure DCS has a place for them in its index if (forRace != "") thisDCS.EnsureRaceKey(forRace); else foreach (string race in compatibleRaces) { thisDCS.EnsureRaceKey(race); } for (int i = 0; i < thisRecipeNames.Count; i++) { thisDCS.GetRecipe(thisRecipeNames[i], true); } } //Ensure Arbitrary Items if(arbitraryRecipes.Count > 0) { for (int i = 0; i < arbitraryRecipes.Count; i++) { thisDCS.GetRecipe(arbitraryRecipes[i], true); } } } public List<WardrobeSettings> GetRacesWardrobeSet(string race) { var thisContext = UMAContext.FindInstance(); if(thisContext == null) { Debug.LogWarning("Getting the WardrobeSet from a WardrobeCollection requires a valid UMAContext in the scene"); return new List<WardrobeSettings>(); } var thisRace = (thisContext.raceLibrary as DynamicRaceLibrary).GetRace(race, true); return GetRacesWardrobeSet(thisRace); } /// <summary> /// Gets the wardrobeSet set in this collection for the given race /// Or wardrobeSet for first matched cross compatible race the given race has /// </summary> public List<WardrobeSettings> GetRacesWardrobeSet(RaceData race) { var setToUse = wardrobeCollection[race.raceName]; //if no set was directly compatible with the active race, check if it has sets for any cross compatible races that race may have if (setToUse.Count == 0) { var thisDCACCRaces = race.GetCrossCompatibleRaces(); for (int i = 0; i < thisDCACCRaces.Count; i++) { if (wardrobeCollection[thisDCACCRaces[i]].Count > 0) { setToUse = wardrobeCollection[thisDCACCRaces[i]]; break; } } } return setToUse; } /// <summary> /// Gets the recipe names for the given race from the WardrobeCollection /// </summary> public List<string> GetRacesRecipeNames(string race, DynamicCharacterSystem dcs) { var recipesToGet = GetRacesWardrobeSet(race); List<string> recipesWeGot = new List<string>(); for (int i = 0; i < recipesToGet.Count; i++) { recipesWeGot.Add(recipesToGet[i].recipe); } return recipesWeGot; } /// <summary> /// Gets the wardrobeRecipes for the given race from the WardrobeCollection /// </summary> public List<UMATextRecipe> GetRacesRecipes(string race, DynamicCharacterSystem dcs) { var recipesToGet = GetRacesWardrobeSet(race); List<UMATextRecipe> recipesWeGot = new List<UMATextRecipe>(); for (int i = 0; i < recipesToGet.Count; i++) { recipesWeGot.Add(dcs.GetRecipe(recipesToGet[i].recipe, true)); } return recipesWeGot; } /// <summary> /// Gets the recipe names from this collections arbitrary recipes list /// </summary> public List<string> GetArbitraryRecipesNames() { return arbitraryRecipes; } /// <summary> /// Gets the wardrobeRecipes from this collections arbitrary recipes list /// </summary> public List<UMATextRecipe> GetArbitraryRecipes(DynamicCharacterSystem dcs) { List<UMATextRecipe> recipesWeGot = new List<UMATextRecipe>(); for (int i = 0; i < arbitraryRecipes.Count; i++) { recipesWeGot.Add(dcs.GetRecipe(arbitraryRecipes[i], true)); } return recipesWeGot; } /// <summary> /// Gets a DCSUnversalPackRecipeModel that has the wardrobeSet set to be the set in this collection for the given race of the sent avatar /// Or if this recipe is cross compatible returns the wardrobe set for the first matched cross compatible race /// </summary> public DCSUniversalPackRecipe GetUniversalPackRecipe(DynamicCharacterAvatar dca, UMAContext context) { var thisPackRecipe = PackedLoadDCSInternal(context); var setToUse = GetRacesWardrobeSet(dca.activeRace.racedata); thisPackRecipe.wardrobeSet = setToUse; thisPackRecipe.race = dca.activeRace.name; return thisPackRecipe; } //Override Load from PackedRecipeBase /// <summary> /// NOTE: Use GetUniversalPackRecipe to get a recipe that includes a wardrobeSet. Load this Recipe's recipeString into the specified UMAData.UMARecipe. /// </summary> public override void Load(UMA.UMAData.UMARecipe umaRecipe, UMAContext context) { if ((recipeString != null) && (recipeString.Length > 0)) { var packedRecipe = PackedLoadDCSInternal(context); if(packedRecipe != null) UnpackRecipe(umaRecipe, packedRecipe, context); } } #endregion #if UNITY_EDITOR [UnityEditor.MenuItem("Assets/Create/UMA/DCS/Wardrobe Collection")] public static void CreateWardrobeCollectionAsset() { UMA.CustomAssetUtility.CreateAsset<UMAWardrobeCollection>(); } #endif } }
using Microsoft.VisualStudio.Modeling.Validation; using nHydrate.Generator.Common.Util; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace nHydrate.Dsl { [ValidationState(ValidationState.Enabled)] partial class Entity { #region Dirty [System.ComponentModel.Browsable(false)] public bool IsDirty { get { return _isDirty || this.Fields.IsDirty() || this.Indexes.IsDirty(); } set { _isDirty = value; if (!value) { this.Fields.ForEach(x => x.IsDirty = false); this.Indexes.ForEach(x => x.IsDirty = false); } } } private bool _isDirty = false; #endregion [ValidationMethod(ValidationCategories.Open | ValidationCategories.Save | ValidationCategories.Menu | ValidationCategories.Custom | ValidationCategories.Load)] public void Validate(ValidationContext context) { //if (!this.IsDirty) return; System.Windows.Forms.Application.DoEvents(); #region Cache this. It is expensive var heirList = this.GetTableHierarchy(); var relationshipList = this.RelationshipList.ToList(); var relationManyMany = relationshipList.Where(x => x.IsManyToMany).ToList(); var relationFieldMap = new Dictionary<EntityHasEntities, IEnumerable<RelationField>>(); //Cache the field map minus relations with missing fields (error condition) foreach (var relation in relationshipList) { var mapList = relation.FieldMapList(); if (mapList.Count(x => x.GetSourceField(relation) == null || x.GetTargetField(relation) == null) == 0) relationFieldMap.Add(relation, mapList); else relationFieldMap.Add(relation, new List<RelationField>()); } #endregion #region Check that non-key relationships have a unique index on fields foreach (var relation in relationshipList) { if (!relation.IsPrimaryKeyRelation()) { foreach (var columnRelationship in relationFieldMap[relation]) { var parentColumn = columnRelationship.GetSourceField(relation); if (!parentColumn.IsUnique) context.LogError(string.Format(ValidationHelper.ErrorTextTableColumnNonPrimaryRelationNotUnique, parentColumn.DatabaseName, this.Name), string.Empty, this); else context.LogWarning(string.Format(ValidationHelper.WarningTextTableColumnNonPrimaryRelationNotUnique, parentColumn.DatabaseName, this.Name), string.Empty, this); } } } #endregion #region Check that object has at least one generated column if (!this.GeneratedColumns.Any()) context.LogError(ValidationHelper.ErrorTextColumnsRequired, string.Empty, this); #endregion #region Clean up bogus references (in case this happened) //Verify that no column has same name as container foreach (var field in this.Fields) { if (field.PascalName.Match(this.PascalName)) { context.LogError(string.Format(ValidationHelper.ErrorTextTableColumnNameMatch, field.Name, this.Name), string.Empty, this); } } //Verify relationships foreach (var relation in relationshipList) { if (relation != null) { foreach (var relationField in relationFieldMap[relation]) { var column1 = relationField.GetSourceField(relation); var column2 = relationField.GetTargetField(relation); if (column1 == null || column2 == null) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationshipMustHaveFields, relation.ParentEntity.Name, relation.ChildEntity.Name), string.Empty, this); } else if (column1.DataType != column2.DataType) { context.LogError(ValidationHelper.ErrorTextRelationshipTypeMismatch + " (" + column1.ToString() + " -> " + column2.ToString() + ")", string.Empty, this); } } if (!relationFieldMap[relation].Any()) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationshipMustHaveFields, relation.ParentEntity.Name, relation.ChildEntity.Name), string.Empty, this); } } } //Verify that inheritance is setup correctly if (!this.IsValidInheritance) { context.LogError(string.Format(ValidationHelper.ErrorTextInvalidInheritance, this.Name), string.Empty, this); } #endregion #region Check that table does not have same name as project if (this.PascalName == this.nHydrateModel.ProjectName) { context.LogError(string.Format(ValidationHelper.ErrorTextTableProjectSameName, this.PascalName), string.Empty, this); } #endregion #region Check for classes that will confict with generated classes var classExtensions = new[] { "collection", "enumerator", "query", "pagingfielditem", "paging", "primarykey", "selectall", "pagedselect", "selectbypks", "selectbycreateddaterange", "selectbymodifieddaterange", "selectbysearch", "beforechangeeventargs", "afterchangeeventargs" }; foreach (var ending in classExtensions) { if (this.PascalName.ToLower().EndsWith(ending)) context.LogError(string.Format(ValidationHelper.ErrorTextNameConflictsWithGeneratedCode, this.Name), string.Empty, this); } #endregion #region Check for inherit hierarchy that all tables are modifiable or not modifiable //If this table is Mutable then make sure it is NOT derived from an Immutable table if (!this.Immutable) { var immutableCount = 0; Entity immutableTable = null; foreach (var h in heirList) { if (h.Immutable) { if (immutableTable == null) immutableTable = h; immutableCount++; } } //If the counts are different then show errors if (immutableCount > 0) { context.LogError(string.Format(ValidationHelper.ErrorTextMutableInherit, this.Name, immutableTable.Name), string.Empty, this); } } #endregion #region Type Tables must be immutable if (this.TypedEntity != TypedEntityConstants.None & !this.Immutable) context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableIsMutable, this.Name), string.Empty, this); #endregion #region Type Tables must have specific columns and data if (this.TypedEntity != TypedEntityConstants.None && (this.PrimaryKeyFields.Count > 0)) { //Must have one PK that is integer type if ((this.PrimaryKeyFields.Count > 1) || !this.PrimaryKeyFields.First().DataType.IsIntegerType()) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTablePrimaryKey, this.Name), string.Empty, this); } //Must have static data if (this.StaticDatum.Count == 0) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableNoData, this.CodeFacade), string.Empty, this); } //Must have a "Name" or "Description" field var typeTableTextField = this.GeneratedColumns.FirstOrDefault(x => x.Name.ToLower() == "name"); if (typeTableTextField == null) typeTableTextField = this.GeneratedColumns.FirstOrDefault(x => x.Name.ToLower() == "description"); if (typeTableTextField == null) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableTextField, this.Name), string.Empty, this); } else if (this.StaticDatum.Count > 0) { //Verify that type tables have data foreach (var row in this.StaticDatum.ToRows()) { //Primary key must be set var cellValue = row[this.PrimaryKeyFields.First().Id]; if (cellValue == null) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this); } else if (string.IsNullOrEmpty(cellValue)) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this); } //Enum name must be set cellValue = row[typeTableTextField.Id]; if (cellValue == null) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this); } else if (string.IsNullOrEmpty(cellValue)) { context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this); } } } } //Verify that the static data is not duplicated if (this.StaticDatum.HasDuplicates(this)) { context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateStaticData, this.Name), string.Empty, this); } #endregion #region Self-ref table cannot map child column to PK field foreach (var relation in relationshipList) { var parentTable = relation.SourceEntity; var childTable = relation.TargetEntity; if (parentTable == childTable) { if (string.IsNullOrEmpty(relation.RoleName)) { context.LogError(string.Format(ValidationHelper.ErrorTextSelfRefMustHaveRole, this.Name), string.Empty, this); } else { foreach (var columnRelationShip in relationFieldMap[relation]) { if (this.PrimaryKeyFields.Contains(columnRelationShip.GetTargetField(relation))) { context.LogError(string.Format(ValidationHelper.ErrorTextSelfRefChildColumnPK, this.Name), string.Empty, this); } } } } } #endregion #region There can be only 1 self reference per table if (this.AllRelationships.Count(x => x.TargetEntity == x.SourceEntity) > 1) { context.LogError(string.Format(ValidationHelper.ErrorTextSelfRefOnlyOne, this.Name), string.Empty, this); } #endregion #region Verify Relations var relationKeyList = new List<string>(); foreach (var relation in relationshipList) { var key = relation.RoleName; var parentTable = relation.SourceEntity; var childTable = relation.TargetEntity; var foreignKeyMap = new List<string>(); var columnList = new List<string>(); var relationKeyMap = string.Empty; foreach (var columnRelationship in relationFieldMap[relation].OrderBy(x => x.SourceFieldId).ThenBy(x => x.TargetFieldId)) { var parentColumn = columnRelationship.GetSourceField(relation); var childColumn = columnRelationship.GetTargetField(relation); if (!string.IsNullOrEmpty(key)) key += ", "; key += parentTable.Name + "." + childColumn.Name + " -> " + childTable.Name + "." + parentColumn.Name; if ((parentColumn.Identity == IdentityTypeConstants.Database) && (childColumn.Identity == IdentityTypeConstants.Database)) { context.LogError(string.Format(ValidationHelper.ErrorTextChildTableRelationIdentity, childTable.Name, parentTable.Name), string.Empty, this); } relationKeyMap += parentColumn.Name + "|" + childTable.Name + "|" + childColumn.Name; //Verify that field name does not match foreign table name if (childColumn.PascalName == parentTable.PascalName) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationFieldNotMatchAssociatedTable, parentTable.Name, childTable.Name), string.Empty, this); } //Verify that a relation does not have duplicate column links if (columnList.Contains(parentColumn.Name + "|" + childColumn.Name)) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationFieldDuplicated, parentTable.Name, childTable.Name), string.Empty, relation); } else columnList.Add(parentColumn.Name + "|" + childColumn.Name); //Verify the OnDelete action if (relation.DeleteAction == DeleteActionConstants.SetNull && !childColumn.Nullable) { //If SetNull then child fields must be nullable context.LogError(string.Format(ValidationHelper.ErrorTextRelationChildNotNullable, parentTable.Name, childTable.Name), string.Empty, relation); } } if (foreignKeyMap.Contains(relationKeyMap)) { context.LogWarning(string.Format(ValidationHelper.ErrorTextMultiFieldRelationsMapDifferentFields, parentTable.Name, childTable.Name), string.Empty, this); } foreignKeyMap.Add(relationKeyMap); if (!relationFieldMap[relation].Any()) { System.Diagnostics.Debug.Write(string.Empty); } //Role names cannot start with number if (relation.PascalRoleName.Length > 0) { var roleFirstChar = relation.PascalRoleName.First(); if ("0123456789".Contains(roleFirstChar)) { context.LogError(string.Format(ValidationHelper.ErrorTextRoleNoStartNumber, key), string.Empty, this); } } //Verify that relations are not duplicated (T1.C1 -> T2.C2) if (!relationKeyList.Contains(relation.PascalRoleName + "|" + key)) { relationKeyList.Add(relation.PascalRoleName + "|" + key); } else { context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateRelation, key, parentTable.Name, childTable.Name), string.Empty, this); } } //Verify M:N relations have same role name on both sides foreach (var relation in relationManyMany) { var relation2 = relation.GetAssociativeOtherRelation(); if (relation2 == null) { //TODO } else if (relation.RoleName != relation.GetAssociativeOtherRelation().RoleName) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationM_NRoleMismatch, relation.TargetEntity.Name), string.Empty, this); } } //Verify M:N relations do not map to same property names //This can happen if 2 M:N tables are defined between the same two tables...(why people do this I do not know) relationKeyList.Clear(); foreach (var relation in relationManyMany) { var relation2 = relation.GetAssociativeOtherRelation(); if (relation2 == null) { //TODO } else { var mappedName = relation.RoleName + "|" + relation.GetSecondaryAssociativeTable().Name; if (relationKeyList.Contains(mappedName)) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationM_NNameDuplication, this.Name, relation.GetSecondaryAssociativeTable().Name), string.Empty, this); } else { relationKeyList.Add(mappedName); } } } { //Verify that if related to an associative table I do not also have a direct link var relatedTables = new List<string>(); foreach (var relation in relationManyMany) { relatedTables.Add(relation.GetSecondaryAssociativeTable().PascalName + relation.RoleName); } //Now verify that I have no relation to them var invalid = false; foreach (var relation in relationshipList) { if (!relation.IsManyToMany) { if (relatedTables.Contains(relation.TargetEntity.PascalName + relation.RoleName)) { invalid = true; } } } if (invalid) context.LogError(string.Format(ValidationHelper.ErrorTextRelationCausesNameConflict, this.Name, relatedTables.First()), string.Empty, this); } //Only 1 relation can exist from A->B on the same columns { var hashList = new List<string>(); var rList = relationshipList.ToList(); foreach (var r in rList) { if (!hashList.Contains(r.LinkHash)) hashList.Add(r.LinkHash); } if (rList.Count != hashList.Count) context.LogError(string.Format(ValidationHelper.ErrorTextRelationDuplicate, this.Name), string.Empty, this); } //Relation fields cannot be duplicated with a relation. All source fields must be unique and all target fields must be unique foreach (var relation in relationshipList.Where(x => x != null)) { var inError = false; var colList1 = new List<Guid>(); var colList2 = new List<Guid>(); foreach (var columnRelationship in relationFieldMap[relation].OrderBy(x => x.SourceFieldId).ThenBy(x => x.TargetFieldId)) { if (colList1.Contains(columnRelationship.SourceFieldId)) inError = true; else colList1.Add(columnRelationship.SourceFieldId); if (colList2.Contains(columnRelationship.TargetFieldId)) inError = true; else colList2.Add(columnRelationship.TargetFieldId); } if (inError) { context.LogError(string.Format(ValidationHelper.ErrorTextRelationNeedUniqueFields, relation.ParentEntity.Name, relation.ChildEntity.Name), string.Empty, this); } } #endregion #region Associative Tables if (this.IsAssociative) { var count = 0; foreach (var relation in this.nHydrateModel.AllRelations) { if (relation.TargetEntity == this) { count++; } } if (count != 2) { context.LogError(string.Format(ValidationHelper.ErrorTextAssociativeTableMustHave2Relations, this.Name, count), string.Empty, this); } } #endregion #region There can be only 1 Identity per table var identityCount = this.GeneratedColumns.Count(x => x.Identity == IdentityTypeConstants.Database); if (identityCount > 1) { //If there is an identity column, it can be the only PK context.LogError(string.Format(ValidationHelper.ErrorTextIdentityOnlyOnePerTable, this.Name), string.Empty, this); } #endregion #region Identity PK can be only PK var pkIdentityCount = this.PrimaryKeyFields.Count(x => x.Identity != IdentityTypeConstants.None); if ((pkIdentityCount > 0) && (this.PrimaryKeyFields.Count != pkIdentityCount)) { //If there is an identity column, it can be the only PK context.LogWarning(string.Format(ValidationHelper.ErrorTextIdentityPKNotOnlyKey, this.Name), string.Empty, this); } #endregion #region Type tables cannot have Identity PK if ((pkIdentityCount > 0) && (this.TypedEntity != TypedEntityConstants.None)) { //If there is an identity column, error context.LogError(string.Format(ValidationHelper.ErrorTextIdentityPKTypeTable, this.Name), string.Empty, this); } #endregion #region Associative table cannot be immutable if (this.IsAssociative & this.Immutable) { context.LogError(ValidationHelper.ErrorTextAssociativeTableNotImmutable, string.Empty, this); } #endregion #region Tables must have a non-identity column if (!this.Immutable) { if (this.GeneratedColumns.Count(x => x.Identity == IdentityTypeConstants.Database) == this.GeneratedColumns.Count()) { context.LogError(string.Format(ValidationHelper.ErrorTextTableNotHave1IdentityOnly, this.Name), string.Empty, this); } } #endregion #region Associative must have non-overlapping PK column if (this.IsAssociative) { var rlist = this.GetRelationsWhereChild().ToList(); if (rlist.Count == 2) { var r1 = rlist.First(); var r2 = rlist.Last(); if (this.PrimaryKeyFields.Count != r1.GetSecondaryAssociativeTable().PrimaryKeyFields.Count + r2.GetSecondaryAssociativeTable().PrimaryKeyFields.Count) { context.LogError(string.Format(ValidationHelper.ErrorTextTableAssociativeNeedsNonOverlappingColumns, this.Name), string.Empty, this); } } if (this.Fields.Count(x => !x.IsPrimaryKey) > 0) { context.LogError(string.Format(ValidationHelper.ErrorTextTableAssociativeNeedsOnlyPK, this.Name), string.Empty, this); } } #endregion #region Verify Static Data if (!this.StaticDatum.IsDataValid(this)) context.LogError(string.Format(ValidationHelper.ErrorTextTableBadStaticData, this.Name), string.Empty, this); #endregion #region Verify Indexes //Check for missing mapped index columns foreach (var index in this.Indexes) { if (index.IndexColumns.Count == 0) { context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalid, this.Name), string.Empty, this); } else { foreach (var ic in index.IndexColumns.ToList()) { if (ic.GetField() == null) { context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalid, this.Name), string.Empty, this); } else if (ic.Field != null && ic.Field.DataType == DataTypeConstants.VarChar && ((ic.Field.Length == 0) || (ic.Field.Length > 900))) { context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalidLength, this.Name + "." + ic.Field.Name), string.Empty, this); } else if (ic.Field != null && ic.Field.DataType == DataTypeConstants.NVarChar && ((ic.Field.Length == 0) || (ic.Field.Length > 450))) { context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalidLength, this.Name + "." + ic.Field.Name), string.Empty, this); } } } } //Check that there are no duplicate indexes var mappedOrderedIndexes = new List<string>(); var mappedUnorderedIndexes = new List<string>(); foreach (var index in this.Indexes) { var indexKey = string.Empty; var columns = index.IndexColumns.Where(x => x.GetField() != null); //Ordered foreach (var ic in columns.OrderBy(x => x.GetField().Name)) { var field = ic.GetField(); indexKey += field.Id + ic.Ascending.ToString() + "|"; } mappedOrderedIndexes.Add(indexKey); //Unordered (by name..just in index order) indexKey = string.Empty; foreach (var ic in columns.OrderBy(x => x.SortOrder)) { var field = ic.GetField(); indexKey += field.Id + ic.Ascending.ToString() + "|"; } mappedUnorderedIndexes.Add(indexKey); } //Ordered duplicate is a warning if (mappedOrderedIndexes.Count != mappedOrderedIndexes.Distinct().Count()) context.LogWarning(string.Format(ValidationHelper.ErrorTextEntityIndexIsPossibleDuplicate, this.Name), string.Empty, this); //Unordered is an error since this is a REAL duplicate if (mappedUnorderedIndexes.Count != mappedUnorderedIndexes.Distinct().Count()) context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexIsDuplicate, this.Name), string.Empty, this); //Only one clustered allowed if (this.Indexes.Count(x => x.Clustered) > 1) { context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexMultipleClustered, this.Name), string.Empty, this); } #endregion #region Associative Table //If no generated CRUD cannot have auditing on Associative if (this.IsAssociative && (this.AllowCreateAudit || this.AllowModifyAudit || this.AllowTimestamp)) { context.LogError(string.Format(ValidationHelper.ErrorTextTableAssociativeNoCRUDAudit, this.Name), string.Empty, this); } #endregion #region Tenant if (this.IsTenant && this.TypedEntity == TypedEntityConstants.DatabaseTable) { context.LogError(string.Format(ValidationHelper.ErrorTextTenantTypeTable, this.Name), string.Empty, this); } if (this.IsTenant && this.Fields.Any(x => x.Name.ToLower() == this.nHydrateModel.TenantColumnName.ToLower())) { context.LogError(string.Format(ValidationHelper.ErrorTextTenantTypeTableTenantColumnMatch, this.Name, this.nHydrateModel.TenantColumnName), string.Empty, this); } #endregion #region Warn if GUID is Clustered Key var fields = this.Indexes.Where(x => x.Clustered).SelectMany(x => x.FieldList).Where(x => x.DataType == DataTypeConstants.UniqueIdentifier).ToList(); if (fields.Any()) { foreach (var f in fields) { context.LogWarning(string.Format(ValidationHelper.ErrorTextClusteredGuid, f.Name, this.Name), string.Empty, this); } } #endregion #region Warn of defaults on nullable fields var nullableList = this.FieldList .ToList() .Cast<Field>() .Where<Field>(x => x.Nullable && !string.IsNullOrEmpty(x.Default)) .ToList(); foreach (var field in nullableList) { context.LogWarning(string.Format(ValidationHelper.ErrorTextNullableFieldHasDefault, field.Name, this.Name), string.Empty, this); //If default on nullable that is FK then ERROR foreach (var r in this.GetRelationsWhereChild()) { foreach (var q in r.FieldMapList().Where(z => z.TargetFieldId == field.Id)) { var f = this.FieldList.ToList().Cast<Field>().FirstOrDefault(x => x.Id == q.TargetFieldId); if (f != null) context.LogError(string.Format(ValidationHelper.ErrorTextNullableFieldHasDefaultWithRelation, f.Name, this.Name, r.SourceEntity.Name), string.Empty, this); } } } #endregion #region DateTime 2008+ foreach (var field in this.FieldList.Where(x => x.DataType == DataTypeConstants.DateTime).ToList()) { context.LogWarning(string.Format(ValidationHelper.ErrorTextDateTimeDeprecated, field.Name), string.Empty, this); } #endregion } [ValidationMethod(ValidationCategories.Open | ValidationCategories.Save | ValidationCategories.Menu | ValidationCategories.Custom | ValidationCategories.Load)] public void ValidateFields(ValidationContext context) { var columnList = this.Fields.ToList(); #region Check for duplicate names var nameList = new Hashtable(); foreach (var column in columnList) { var name = column.Name.ToLower(); if (nameList.ContainsKey(name)) context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateName, column.Name), string.Empty, this); else nameList.Add(name, string.Empty); } #endregion #region Check for duplicate codefacades if (context.CurrentViolations.Count == 0) { nameList = new Hashtable(); foreach (var column in columnList) { var name = column.PascalName.ToLower(); if (nameList.ContainsKey(name)) context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateCodeFacade, column.Name), string.Empty, this); else nameList.Add(name, string.Empty); } } #endregion #region Check for a primary key var isPrimaryNull = false; foreach (var column in columnList) { if (column.IsPrimaryKey) { //hasPrimary = true; isPrimaryNull |= column.Nullable; } } #endregion #region Check for field named created,modfied,timestamp as these are taken foreach (var column in columnList) { var name = column.Name.ToLower().Replace("_", string.Empty); var t = this; //If there is a CreateAudit then no fields can be named the predefined values if (name.Match(this.nHydrateModel.CreatedByColumnName.Replace("_", string.Empty))) context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this); else if (name.Match(this.nHydrateModel.CreatedDateColumnName.Replace("_", string.Empty))) context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this); if (name.Match(this.nHydrateModel.ModifiedByColumnName.Replace("_", string.Empty))) context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this); else if (name.Match(this.nHydrateModel.ModifiedDateColumnName.Replace("_", string.Empty))) context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this); if (name.Match(this.nHydrateModel.ConcurrencyCheckColumnName.Replace("_", string.Empty))) context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this); } #endregion #region Verify something is generated if (columnList.Count != 0) { //Make sure all PK are generated if (this.PrimaryKeyFields.Count != columnList.Count(x => x.IsPrimaryKey == true)) context.LogError(string.Format(ValidationHelper.ErrorTextNoPrimaryKey, this.Name), string.Empty, this); else if (this.PrimaryKeyFields.Count == 0) context.LogError(string.Format(ValidationHelper.ErrorTextNoPrimaryKey, this.Name), string.Empty, this); else if (isPrimaryNull) context.LogError(ValidationHelper.ErrorTextPrimaryKeyNull, string.Empty, this); } #endregion #region Verify only one timestamp/table var timestampcount = this.AllowTimestamp ? 1 : 0; timestampcount += this.Fields.Count(x => x.DataType == DataTypeConstants.Timestamp); if (timestampcount > 1) { context.LogError(string.Format(ValidationHelper.ErrorTextOnlyOneTimestamp, this.Name), string.Empty, this); } #endregion } } }
// 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.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestPagingTestService : ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// The management credentials for Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout for Long Running Operations. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } public virtual IPagingOperations Paging { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> public AutoRestPagingTestService() : base() { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestPagingTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestPagingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestPagingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestPagingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Paging = new PagingOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings = new JsonSerializerSettings{ DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Moritz.Xml; namespace Moritz.Symbols { public class BeamBlock : LineMetrics { public BeamBlock(Clef clef, List<ChordSymbol> chordsBeamedTogether, VerticalDir voiceStemDirection, float beamThickness, float strokeThickness, bool isInput) : base(isInput ? CSSObjectClass.inputBeamBlock : CSSObjectClass.beamBlock, strokeThickness, "black", "black") { Chords = new List<ChordSymbol>(chordsBeamedTogether); SetBeamedGroupStemDirection(clef, chordsBeamedTogether, voiceStemDirection); foreach(ChordSymbol chord in chordsBeamedTogether) chord.BeamBlock = this; // prevents an isolated flag from being created _gap = Chords[0].Voice.Staff.Gap; _beamSeparation = _gap; _beamThickness = beamThickness; _strokeThickness = strokeThickness; _stemDirection = Chords[0].Stem.Direction; /****************************************************************************** * Important to set stem tips to this value before justifying horizontally. * Allows collisions between the objects outside the tips (e.g. dynamics or ornaments) * to be detected correctly. */ _defaultStemTipY = GetDefaultStemTipY(clef, chordsBeamedTogether); } /// <summary> /// This algorithm follows Gardner Read when the stemDirection is "none" (i.e. not forced): /// If there were no beam, and the majority of the stems would go up, then all the stems in the beam go up. /// ji: if there are the same number of default up and default down stems, then the direction is decided by /// the most extreme notehead in the beam group. If both extremes are the same (e.g. 1 ledgeline up and down) /// then the stems are all down. /// </summary> /// <param name="currentClef"></param> /// <param name="chordsBeamedTogether"></param> private void SetBeamedGroupStemDirection(Clef currentClef, List<ChordSymbol> chordsBeamedTogether, VerticalDir voiceStemDirection) { Debug.Assert(chordsBeamedTogether.Count > 1); VerticalDir groupStemDirection = voiceStemDirection; if(voiceStemDirection == VerticalDir.none) { // here, there is only one voice in the staff, so the direction depends on the height of the noteheads. int upStems = 0; int downStems = 0; foreach(ChordSymbol chord in chordsBeamedTogether) { VerticalDir direction = chord.DefaultStemDirection(currentClef); if(direction == VerticalDir.up) upStems++; else downStems++; } if(upStems == downStems) groupStemDirection = GetDirectionFromExtremes(currentClef, chordsBeamedTogether); else if(upStems > downStems) groupStemDirection = VerticalDir.up; else groupStemDirection = VerticalDir.down; } foreach(ChordSymbol chord in chordsBeamedTogether) { chord.Stem.Direction = groupStemDirection; } } private VerticalDir GetDirectionFromExtremes(Clef currentClef, List<ChordSymbol> chordsBeamedTogether) { float headMinTop = float.MaxValue; float headMaxBottom = float.MinValue; float gap = chordsBeamedTogether[0].Voice.Staff.Gap; int numberOfStafflines = chordsBeamedTogether[0].Voice.Staff.NumberOfStafflines; foreach(ChordSymbol chord in chordsBeamedTogether) { foreach(Head head in chord.HeadsTopDown) { float headY = head.GetOriginY(currentClef, gap); headMinTop = headMinTop < headY ? headMinTop : headY; headMaxBottom = headMaxBottom > headY ? headMaxBottom : headY; } } headMaxBottom -= (gap * (numberOfStafflines - 1)); headMinTop *= -1; if(headMaxBottom > headMinTop) return VerticalDir.up; else return VerticalDir.down; } private float GetDefaultStemTipY(Clef currentClef, List<ChordSymbol> chordsBeamedTogether) { float headMinTop = float.MaxValue; float headMaxBottom = float.MinValue; float gap = chordsBeamedTogether[0].Voice.Staff.Gap; int numberOfStafflines = chordsBeamedTogether[0].Voice.Staff.NumberOfStafflines; VerticalDir direction = chordsBeamedTogether[0].Stem.Direction; foreach(ChordSymbol chord in chordsBeamedTogether) { foreach(Head head in chord.HeadsTopDown) { float headY = head.GetOriginY(currentClef, gap); headMinTop = headMinTop < headY ? headMinTop : headY; headMaxBottom = headMaxBottom > headY ? headMaxBottom : headY; } } if(direction == VerticalDir.up) return headMinTop - (gap * numberOfStafflines); else return headMaxBottom + (gap * numberOfStafflines); } /// <summary> /// This beam is attached to chords in one voice of a 2-voice staff. /// The returned chords are the chords in the other voice whose msPosition /// is greater than or equal to the msPosition at the start of this beamBlock, /// and less than or equal to the msPosition at the end of this beamBlock. /// </summary> public List<ChordSymbol> EnclosedChords(Voice otherVoice) { Debug.Assert(Chords.Count > 1); int startMsPos = Chords[0].AbsMsPosition; int endMsPos = Chords[Chords.Count - 1].AbsMsPosition; List<ChordSymbol> enclosedChordSymbols = new List<ChordSymbol>(); foreach(ChordSymbol otherChord in otherVoice.ChordSymbols) { if(otherChord.AbsMsPosition >= startMsPos && otherChord.AbsMsPosition <= endMsPos) enclosedChordSymbols.Add(otherChord); if(otherChord.AbsMsPosition > endMsPos) break; } return enclosedChordSymbols; } /// <summary> /// The system has been justified horizontally, so all objects are at their final horizontal positions. /// This function /// 1. creates all the contained beams horizontally with their top edges at 0F. /// 2. expands the beams vertically, and moves them to the closest position on the correct side of their noteheads. /// 3. shears the beams. /// 4. moves the stem tips and related objects (dynamics, ornament numbers) to their correct positions wrt the outer beam. /// Especially note that neither this beam Block or its contained beams ever move _horizontally_. /// </summary> public void FinalizeBeamBlock() { #region create the individual beams all with top edge horizontal at 0F. HashSet<DurationClass> durationClasses = new HashSet<DurationClass>() { DurationClass.fiveFlags, DurationClass.fourFlags, DurationClass.threeFlags, DurationClass.semiquaver, DurationClass.quaver }; foreach(DurationClass durationClass in durationClasses) { List<Beam> beams = CreateBeams(durationClass); _left = float.MaxValue; _right = float.MinValue; foreach(Beam beam in beams) { _left = _left < beam.LeftX ? _left : beam.LeftX; _right = _right > beam.RightX ? _right : beam.RightX; Beams.Add(beam); } _originX = _left; // _left, _right and _originX never change again after they have been set here } SetBeamStubs(Beams); SetVerticalBounds(); #endregion Dictionary<DurationClass, float> durationClassBeamThicknesses = GetBeamThicknessesPerDurationClass(durationClasses); List<ChordMetrics> chordsMetrics = GetChordsMetrics(); ExpandVerticallyAtNoteheads(chordsMetrics, durationClassBeamThicknesses); Shear(chordsMetrics); FinalAdjustmentReNoteheads(chordsMetrics, durationClassBeamThicknesses[DurationClass.quaver]); FinalAdjustmentReAccidentals(chordsMetrics, durationClassBeamThicknesses[DurationClass.quaver]); MoveStemTips(); } /// <summary> /// If the minimum distance between an inner beam and a notehead is less than 2.5 gaps, /// The beamBlock is moved away from the noteheads until the minimum distance is 2.5 gaps /// </summary> private void FinalAdjustmentReNoteheads(List<ChordMetrics> chordsMetrics, float singleBeamThickness) { float beamTan = GetBeamTan(); foreach(ChordMetrics chordMetrics in chordsMetrics) { if(this._stemDirection == VerticalDir.down) { float minimumSeparationY = float.MaxValue; HeadMetrics bottomHeadMetrics = chordMetrics.BottomHeadMetrics; float bhLeft = bottomHeadMetrics.Left; float bhRight = bottomHeadMetrics.Right; float bhOriginX = bottomHeadMetrics.OriginX; foreach(Beam beam in Beams) { if(beam.LeftX <= bhRight && beam.RightX >= bhLeft) { float beamTopAtHeadOriginX = beam.LeftTopY + ((bhOriginX - beam.LeftX) * beamTan); float localSeparationY = beamTopAtHeadOriginX - bottomHeadMetrics.OriginY; minimumSeparationY = (localSeparationY < minimumSeparationY) ? localSeparationY : minimumSeparationY; } } float shiftY = (_gap * 2.5F) - minimumSeparationY; if(shiftY > 0) { Move(shiftY); } } if(this._stemDirection == VerticalDir.up) { float minimumSeparationY = float.MaxValue; HeadMetrics topHeadMetrics = chordMetrics.TopHeadMetrics; float thLeft = topHeadMetrics.Left; float thRight = topHeadMetrics.Right; float thOriginX = topHeadMetrics.OriginX; foreach(Beam beam in Beams) { if(beam.LeftX <= thRight && beam.RightX >= thLeft) { float beamBottomAtHeadOriginX = beam.LeftTopY + ((thOriginX - beam.LeftX) * beamTan) + singleBeamThickness; float localSeparationY = topHeadMetrics.OriginY - beamBottomAtHeadOriginX; minimumSeparationY = (localSeparationY < minimumSeparationY) ? localSeparationY : minimumSeparationY; } } float shiftY = (_gap * 2.5F) - minimumSeparationY; if(shiftY > 0) { Move(shiftY * -1); } } } } /// <summary> /// If the minimum distance between an inner beam overlaps an accidental, /// The beamBlock is moved away from the accidentals. /// </summary> private void FinalAdjustmentReAccidentals(List<ChordMetrics> chordsMetrics, float singleBeamThickness) { float beamTan = GetBeamTan(); foreach(ChordMetrics chordMetrics in chordsMetrics) { if(this._stemDirection == VerticalDir.down) { float positiveDeltaY = -1; if(chordMetrics.AccidentalsMetrics.Count > 0) { AccidentalMetrics bottomAccidentalMetrics = chordMetrics.AccidentalsMetrics[chordMetrics.AccidentalsMetrics.Count - 1]; float baLeft = bottomAccidentalMetrics.Left; float baRight = bottomAccidentalMetrics.Right; float baOriginX = bottomAccidentalMetrics.OriginX; foreach(Beam beam in Beams) { if(beam.LeftX <= baRight && beam.RightX >= baLeft) { float beamTopAtAccidentalOriginX = beam.LeftTopY + ((baOriginX - beam.LeftX) * beamTan); if(bottomAccidentalMetrics.Bottom > beamTopAtAccidentalOriginX) { float localdeltaY = bottomAccidentalMetrics.Bottom - beamTopAtAccidentalOriginX; positiveDeltaY = (localdeltaY > positiveDeltaY) ? localdeltaY : positiveDeltaY; } } } } if(positiveDeltaY >= 0) { float shiftY = 0; while(shiftY < positiveDeltaY) { shiftY += _gap * 0.75F; } Move(shiftY); } } if(this._stemDirection == VerticalDir.up) { float negativeDeltaY = 1; if(chordMetrics.AccidentalsMetrics.Count > 0) { AccidentalMetrics topAccidentalMetrics = chordMetrics.AccidentalsMetrics[0]; float taLeft = topAccidentalMetrics.Left; float taRight = topAccidentalMetrics.Right; float taOriginX = topAccidentalMetrics.OriginX; foreach(Beam beam in Beams) { if(beam.LeftX <= taRight && beam.RightX >= taLeft) { float beamBottomAtAccidentalOriginX = beam.LeftTopY + ((taOriginX - beam.LeftX) * beamTan) + singleBeamThickness; if(topAccidentalMetrics.Top < beamBottomAtAccidentalOriginX) { float localdeltaY = topAccidentalMetrics.Top - beamBottomAtAccidentalOriginX; negativeDeltaY = (localdeltaY < negativeDeltaY) ? localdeltaY : negativeDeltaY; } } } } if(negativeDeltaY <= 0) { float shiftY = 0; while(shiftY > negativeDeltaY) { shiftY -= _gap * 0.75F; } Move(shiftY); } } } } private float GetBeamTan() { Beam longestbeam = null; float maxwidth = float.MinValue; float width = 0; foreach(Beam beam in Beams) { width = beam.RightX - beam.LeftX; if(width > maxwidth) { longestbeam = beam; maxwidth = width; } } float beamTan = (longestbeam.RightTopY - longestbeam.LeftTopY) / maxwidth; return beamTan; } private void SetBeamStubs(HashSet<Beam> beamsHash) { List<Beam> beams = new List<Beam>(beamsHash); float stubWidth = _gap * 1.2F; for(int i = 0; i < beams.Count; ++i) { Beam beam = beams[i]; if(beam is IBeamStub) { Beam leftEndLongBeam = LeftEndLongBeam(beams, beam.LeftX); beamsHash.Remove(beam); DurationClass durationClass = (beam as IBeamStub).DurationClass; Beam newBeamStub; if(leftEndLongBeam.LeftX == beam.LeftX) { // add a beamStub to the right of the stem newBeamStub = NewBeam(durationClass, beam.LeftX, beam.LeftX + stubWidth, true); } else { newBeamStub = NewBeam(durationClass, beam.LeftX - stubWidth, beam.LeftX, true); } beamsHash.Add(newBeamStub); } } } private Beam LeftEndLongBeam(List<Beam> beams, float stemX) { float leftX = int.MaxValue; Beam rval = null; foreach(Beam beam in beams) { if(!(beam is IBeamStub) && beam.LeftX < leftX) { rval = beam; leftX = beam.LeftX; } } foreach(Beam beam in beams) { if(stemX == beam.LeftX && !(beam is IBeamStub) && !(rval == beam)) { rval = beam; } } Debug.Assert(!(rval is IBeamStub)); return rval; } List<ChordMetrics> GetChordsMetrics() { List<ChordMetrics> chordsMetrics = new List<ChordMetrics>(); foreach(ChordSymbol chord in Chords) { chordsMetrics.Add((ChordMetrics)chord.Metrics); } return chordsMetrics; } private void SetVerticalBounds() { _top = float.MaxValue; _bottom = float.MinValue; foreach(Beam beam in Beams) { float beamBoundsTop = beam.LeftTopY < beam.RightTopY ? beam.LeftTopY : beam.RightTopY; float beamBoundsBottom = beam.LeftTopY > beam.RightTopY ? beam.LeftTopY : beam.RightTopY; beamBoundsBottom += _beamThickness; _bottom = _bottom > beamBoundsBottom ? _bottom : beamBoundsBottom; _top = _top < beamBoundsTop ? _top : beamBoundsTop; } _originY = _top; } private List<Beam> CreateBeams(DurationClass durationClass) { List<Beam> newBeams = new List<Beam>(); bool inBeam = false; float beamLeft = -1F; float beamRight = -1F; ChordMetrics rightMostChordMetrics = (ChordMetrics)Chords[Chords.Count - 1].Metrics; float rightMostStemX = rightMostChordMetrics.StemMetrics.OriginX; int stemNumber = 1; foreach(ChordSymbol chord in Chords) { ChordMetrics chordMetrics = (ChordMetrics)chord.Metrics; float stemX = chordMetrics.StemMetrics.OriginX; bool hasLessThanOrEqualBeams = HasLessThanOrEqualBeams(durationClass, chord.DurationClass); if(!inBeam && hasLessThanOrEqualBeams) { beamLeft = stemX; beamRight = stemX; inBeam = true; } else if(inBeam && hasLessThanOrEqualBeams) { beamRight = stemX; } if(inBeam && ((!hasLessThanOrEqualBeams) || stemX == rightMostStemX)) // different durationClass or end of beamBlock { // BeamStubs are initially created with LeftX == RightX == stemX. // They are replaced by proper beamStubs when the BeamBlock is complete // (See SetBeamStubs() above.) bool isStub = (beamLeft == beamRight) ? true : false; Beam newBeam = NewBeam(durationClass, beamLeft, beamRight, isStub); newBeams.Add(newBeam); inBeam = false; } stemNumber++; } return newBeams; } /// <summary> /// returns true if the currentDC has a less than or equal number of beams than the stemDC /// </summary> /// <param name="currentDC"></param> /// <param name="stemDC"></param> /// <returns></returns> private bool HasLessThanOrEqualBeams(DurationClass currentDC, DurationClass stemDC) { bool hasLessThanOrEqualBeams = false; switch(currentDC) { case DurationClass.fiveFlags: if(stemDC == DurationClass.fiveFlags) hasLessThanOrEqualBeams = true; break; case DurationClass.fourFlags: if(stemDC == DurationClass.fiveFlags || stemDC == DurationClass.fourFlags) hasLessThanOrEqualBeams = true; break; case DurationClass.threeFlags: if(stemDC == DurationClass.fiveFlags || stemDC == DurationClass.fourFlags || stemDC == DurationClass.threeFlags) hasLessThanOrEqualBeams = true; break; case DurationClass.semiquaver: if(stemDC == DurationClass.fiveFlags || stemDC == DurationClass.fourFlags || stemDC == DurationClass.threeFlags || stemDC == DurationClass.semiquaver) hasLessThanOrEqualBeams = true; break; case DurationClass.quaver: if(stemDC == DurationClass.fiveFlags || stemDC == DurationClass.fourFlags || stemDC == DurationClass.threeFlags || stemDC == DurationClass.semiquaver || stemDC == DurationClass.quaver) hasLessThanOrEqualBeams = true; break; } return hasLessThanOrEqualBeams; } private Beam NewBeam(DurationClass durationClass, float leftX, float rightX, bool isStub) { Beam newBeam = null; switch(durationClass) { case DurationClass.fiveFlags: if(isStub) newBeam = new FiveFlagsBeamStub(leftX, rightX); else newBeam = new FiveFlagsBeam(leftX, rightX); break; case DurationClass.fourFlags: if(isStub) newBeam = new FourFlagsBeamStub(leftX, rightX); else newBeam = new FourFlagsBeam(leftX, rightX); break; case DurationClass.threeFlags: if(isStub) newBeam = new ThreeFlagsBeamStub(leftX, rightX); else newBeam = new ThreeFlagsBeam(leftX, rightX); break; case DurationClass.semiquaver: if(isStub) newBeam = new SemiquaverBeamStub(leftX, rightX); else newBeam = new SemiquaverBeam(leftX, rightX); break; case DurationClass.quaver: newBeam = new QuaverBeam(leftX, rightX); break; default: Debug.Assert(false, "Illegal beam duration class"); break; } return newBeam; } public void Move(float dy) { foreach(Beam beam in Beams) { beam.MoveYs(dy, dy); } SetVerticalBounds(); } /// <summary> /// Moves the horizontal beams to their correct vertical positions re the chords /// leaving the outer leftY of the beamBlock at leftY /// </summary> /// <param name="outerLeftY"></param> private void ExpandVerticallyAtNoteheads(List<ChordMetrics> chordsMetrics, Dictionary<DurationClass, float> durationClassBeamThicknesses) { ExpandVerticallyOnStaff(); MoveToNoteheads(chordsMetrics, durationClassBeamThicknesses); SetVerticalBounds(); } /// <summary> /// Expands the beamBlock vertically, leaving its outer edge on the top line of the staff /// </summary> private void ExpandVerticallyOnStaff() { float staffOriginY = Chords[0].Voice.Staff.Metrics.OriginY; foreach(Beam beam in Beams) { beam.ShiftYsForBeamBlock(staffOriginY, _gap, _stemDirection, _beamThickness); } } /// <summary> /// The beamBlock has been vertically expanded. It is currently horizontal, and its outer edge is on the top staffline (at staffOriginY). /// This function moves the beamBlock vertically until it is on the right side (above or below) the noteheads, and as close as possible /// to the noteheads. /// If there is only a single (quaver) beam, it ends up with its inner edge one octave from the OriginY of the closest notehead in the group. /// Otherwise the smallest distance between any beam and the closest notehead will be a sixth. /// </summary> /// <returns></returns> private void MoveToNoteheads(List<ChordMetrics> chordsMetrics, Dictionary<DurationClass, float> durationClassBeamThicknesses) { float staffOriginY = Chords[0].Voice.Staff.Metrics.OriginY; if(_stemDirection == VerticalDir.down) { float lowestBottomReStaff = float.MinValue; for(int i = 0; i < Chords.Count; ++i) { ChordMetrics chordMetrics = chordsMetrics[i]; HeadMetrics bottomHeadMetrics = chordMetrics.BottomHeadMetrics; float bottomNoteOriginYReStaff = bottomHeadMetrics.OriginY - staffOriginY; float beamBottomReStaff = 0; float beamThickness = durationClassBeamThicknesses[Chords[i].DurationClass]; if(bottomNoteOriginYReStaff < (_gap * -1)) // above the staff { if(Chords[i].DurationClass == DurationClass.quaver) { beamBottomReStaff = (_gap * 2) + beamThickness; } else { beamBottomReStaff = _gap + beamThickness; } } else if(bottomNoteOriginYReStaff <= (_gap * 2)) // above the mid line { if(Chords[i].DurationClass == DurationClass.quaver) { beamBottomReStaff = bottomNoteOriginYReStaff + (_gap * 3.5F) + beamThickness; } else { beamBottomReStaff = bottomNoteOriginYReStaff + (_gap * 2.5F) + beamThickness; } } else { beamBottomReStaff = bottomNoteOriginYReStaff + (_gap * 3F) + beamThickness; } lowestBottomReStaff = lowestBottomReStaff > beamBottomReStaff ? lowestBottomReStaff : beamBottomReStaff; } Move(lowestBottomReStaff); } else // stems up { float highestTopReStaff = float.MaxValue; for(int i = 0; i < Chords.Count; ++i) { ChordMetrics chordMetrics = chordsMetrics[i]; HeadMetrics topHeadMetrics = chordMetrics.TopHeadMetrics; float topNoteOriginYReStaff = topHeadMetrics.OriginY - staffOriginY; float beamTopReStaff = 0; float beamThickness = durationClassBeamThicknesses[Chords[i].DurationClass]; if(topNoteOriginYReStaff > (_gap * 5)) // below the staff { if(Chords[i].DurationClass == DurationClass.quaver) { beamTopReStaff = (_gap * 2) - beamThickness; } else { beamTopReStaff = (_gap * 3) - beamThickness; } } else if(topNoteOriginYReStaff >= (_gap * 2)) // below the mid line { if(Chords[i].DurationClass == DurationClass.quaver) { beamTopReStaff = topNoteOriginYReStaff - (_gap * 3.5F) - beamThickness; } else { beamTopReStaff = topNoteOriginYReStaff - (_gap * 2.5F) - beamThickness; } } else // above the mid-line { beamTopReStaff = topNoteOriginYReStaff - (_gap * 3F) - beamThickness; } highestTopReStaff = highestTopReStaff < beamTopReStaff ? highestTopReStaff : beamTopReStaff; } Move(highestTopReStaff); } } private Dictionary<DurationClass, float> GetBeamThicknessesPerDurationClass(HashSet<DurationClass> durationClasses) { Dictionary<DurationClass, float> btpdc = new Dictionary<DurationClass, float>(); float thickness = 0F; foreach(DurationClass dc in durationClasses) { switch(dc) { case DurationClass.fiveFlags: thickness = (4 * _beamSeparation) + _beamThickness; btpdc.Add(DurationClass.fiveFlags, thickness); break; case DurationClass.fourFlags: thickness = (3 * _beamSeparation) + _beamThickness; btpdc.Add(DurationClass.fourFlags, thickness); break; case DurationClass.threeFlags: thickness = (2 * _beamSeparation) + _beamThickness; btpdc.Add(DurationClass.threeFlags, thickness); break; case DurationClass.semiquaver: thickness = _beamSeparation + _beamThickness; btpdc.Add(DurationClass.semiquaver, thickness); break; case DurationClass.quaver: thickness = _beamThickness; btpdc.Add(DurationClass.quaver, thickness); break; } } return btpdc; } private void Shear(List<ChordMetrics> chordsMetrics) { float tanAlpha = ShearAngle(chordsMetrics); float shearAxis = ShearAxis(chordsMetrics, tanAlpha); if(Beams.Count == 1 && (tanAlpha > 0.02 || tanAlpha < -0.02)) { if(_stemDirection == VerticalDir.up) Move(_gap * 0.75F); else Move(-_gap * 0.75F); } foreach(ChordMetrics chordMetrics in chordsMetrics) { float width = chordMetrics.StemMetrics.OriginX - shearAxis; float stemX = chordMetrics.StemMetrics.OriginX; float dy = width * tanAlpha; foreach(Beam beam in Beams) { if(beam is IBeamStub beamStub) { beamStub.ShearBeamStub(shearAxis, tanAlpha, stemX); } else { if(beam.LeftX == stemX) beam.MoveYs(dy, 0F); else if(beam.RightX == stemX) beam.MoveYs(0F, dy); } } } SetVerticalBounds(); SetToStaff(); } private float ShearAngle(List<ChordMetrics> chordsMetrics) { ChordMetrics leftChordMetrics = chordsMetrics[0]; ChordMetrics rightChordMetrics = chordsMetrics[chordsMetrics.Count - 1]; float height = (((rightChordMetrics.TopHeadMetrics.OriginY + rightChordMetrics.BottomHeadMetrics.OriginY) / 2) - ((leftChordMetrics.TopHeadMetrics.OriginY + leftChordMetrics.BottomHeadMetrics.OriginY) / 2)); float width = rightChordMetrics.StemMetrics.OriginX - leftChordMetrics.StemMetrics.OriginX; float tanAlpha = (height / width) / 3; if(tanAlpha > 0.10F) tanAlpha = 0.10F; if(tanAlpha < -0.10F) tanAlpha = -0.10F; return tanAlpha; } /// </summary> /// <param name="chordDaten"></param> /// <returns></returns> private float ShearAxis(List<ChordMetrics> chordsMetrics, float tanAlpha) { List<float> innerNoteheadHeights = GetInnerNoteheadHeights(chordsMetrics); float smallestDistance = float.MaxValue; foreach(float distance in innerNoteheadHeights) smallestDistance = smallestDistance < distance ? smallestDistance : distance; List<int> indices = new List<int>(); for(int i = 0; i < innerNoteheadHeights.Count; ++i) { if(innerNoteheadHeights[i] == smallestDistance) indices.Add(i); } if((_stemDirection == VerticalDir.down && tanAlpha <= 0) || (_stemDirection == VerticalDir.up && tanAlpha > 0)) return chordsMetrics[indices[indices.Count - 1]].StemMetrics.OriginX; else return chordsMetrics[indices[0]].StemMetrics.OriginX; } private List<float> GetInnerNoteheadHeights(List<ChordMetrics> chordsMetrics) { List<float> distances = new List<float>(); if(_stemDirection == VerticalDir.down) { foreach(ChordMetrics chordMetrics in chordsMetrics) { distances.Add(-(chordMetrics.BottomHeadMetrics.OriginY)); } } else { foreach(ChordMetrics chordMetrics in chordsMetrics) { distances.Add(chordMetrics.TopHeadMetrics.OriginY); } } return distances; } /// <summary> /// Resets the height of the beamBlock, if it is too high or too low. /// </summary> /// <param name="chordsMetrics"></param> private void SetToStaff() { float staffTopY = Chords[0].Voice.Staff.Metrics.OriginY; float staffBottomY = staffTopY + (_gap * (Chords[0].Voice.Staff.NumberOfStafflines - 1)); float staffMiddleY = (staffTopY + staffBottomY) / 2F; float deltaY = 0; if(this._stemDirection == VerticalDir.up) { if(Beams.Count == 1) { deltaY = staffMiddleY + (_gap * 0.35F) - this._bottom; } else if(this._bottom >= staffBottomY) { deltaY = staffMiddleY + (_gap * 1.35F) - this._bottom; } if(deltaY < 0F) Move(deltaY); } else // this._stemDirection == VerticalDir.down { if(Beams.Count == 1) { deltaY = staffMiddleY - (_gap * 0.35F) - this._top; } else if(this._top <= staffTopY) { deltaY = staffMiddleY - (_gap * 1.35F) - this._top; } if(deltaY > 0F) Move(deltaY); } } private void MoveStemTips() { float staffOriginY = Chords[0].Voice.Staff.Metrics.OriginY; QuaverBeam quaverBeam = null; foreach(Beam beam in Beams) { quaverBeam = beam as QuaverBeam; if(quaverBeam != null) break; } Debug.Assert(quaverBeam != null); float tanAlpha = (quaverBeam.RightTopY - quaverBeam.LeftTopY) / (quaverBeam.RightX - quaverBeam.LeftX); foreach(ChordSymbol chord in Chords) { ChordMetrics chordMetrics = ((ChordMetrics)chord.Metrics); StemMetrics stemMetrics = chordMetrics.StemMetrics; // a clone Debug.Assert(chord.Stem.Direction == _stemDirection); // just to be sure. float stemTipDeltaY = ((stemMetrics.OriginX - this._left) * tanAlpha); float stemTipY = quaverBeam.LeftTopY + stemTipDeltaY; chordMetrics.MoveOuterStemTip(stemTipY, _stemDirection); // dont just move the clone! Moves the auxilliaries too. } } /// <summary> /// The tangent of this beam's angle. This value is positive if the beam slopes upwards to the right. /// </summary> /// <returns></returns> private float TanAngle { get { QuaverBeam qBeam = null; foreach(Beam beam in Beams) { qBeam = beam as QuaverBeam; if(qBeam != null) break; } Debug.Assert(qBeam != null); float tan = ((qBeam.LeftTopY - qBeam.RightTopY) / (qBeam.RightX - qBeam.LeftX)); return tan; } } /// <summary> /// Returns a list of HLine representing the outer edge of the outer (=quaver) beam. /// </summary> /// <returns></returns> public List<HLine> OuterEdge() { QuaverBeam qBeam = null; foreach(Beam beam in Beams) { qBeam = beam as QuaverBeam; if(qBeam != null) break; } Debug.Assert(qBeam != null); List<HLine> outerEdge = new List<HLine>(); float hlineY = 0F; if(_stemDirection == VerticalDir.up) hlineY = qBeam.LeftTopY; else hlineY = qBeam.LeftTopY + _beamThickness; float heightDiff = qBeam.LeftTopY - qBeam.RightTopY; //float heightDiff = qBeam.RightTopY - qBeam.LeftTopY; float stepHeight = (_beamThickness * 0.2F); int nSteps = (int) Math.Round(heightDiff / stepHeight); if(nSteps == 0) { outerEdge.Add(new HLine(_left, _right, hlineY)); } else { if(nSteps < 0) nSteps *= -1; stepHeight = heightDiff / nSteps; float stepWidth = (_right - _left) / nSteps; float left = _left; float tanAlpha = stepHeight / stepWidth; for(int i = 0; i < nSteps; i++) { outerEdge.Add(new HLine(left, left + stepWidth, hlineY)); left += stepWidth; hlineY -= (stepWidth * tanAlpha); } } return outerEdge; } public void ShiftStemsForOtherVoice(Voice otherVoice) { float minMsPosition = Chords[0].AbsMsPosition; float maxMsPosition = Chords[Chords.Count - 1].AbsMsPosition; List<ChordSymbol> otherChords = new List<ChordSymbol>(); foreach(ChordSymbol otherChordSymbol in otherVoice.ChordSymbols) { if(otherChordSymbol.AbsMsPosition >= minMsPosition && otherChordSymbol.AbsMsPosition <= maxMsPosition) otherChords.Add(otherChordSymbol); if(otherChordSymbol.AbsMsPosition > maxMsPosition) break; } if(otherChords.Count > 0) { float minimumDistanceToChords = _gap * 2F; float distanceToChords = DistanceToChords(otherChords); if(_stemDirection == VerticalDir.up) // move the beam up { if(distanceToChords < minimumDistanceToChords) { float deltaY = -(minimumDistanceToChords - distanceToChords); this.Move(deltaY); foreach(ChordSymbol chord in Chords) { float newStemTipY = chord.ChordMetrics.StemMetrics.Top + deltaY; chord.ChordMetrics.MoveOuterStemTip(newStemTipY, VerticalDir.up); } } } else // _stemDirection == VerticalDir.down, move the beam down { if(distanceToChords < minimumDistanceToChords) { float deltaY = minimumDistanceToChords - distanceToChords; this.Move(deltaY); foreach(ChordSymbol chord in Chords) { float newStemTipY = chord.ChordMetrics.StemMetrics.Bottom + deltaY; chord.ChordMetrics.MoveOuterStemTip(newStemTipY, VerticalDir.down); } } } } } /// <summary> /// Returns the smallest distance between the inner edge of this beam and the noteheads /// in the other chords. The other chords are in a second voice on this staff. /// </summary> private float DistanceToChords(List<ChordSymbol> otherChords) { float minimumDistanceToChords = float.MaxValue; foreach(ChordSymbol chord in otherChords) { float distanceToChord = float.MaxValue; if(_stemDirection == VerticalDir.up) distanceToChord = VerticalDistanceToHead(chord.ChordMetrics.TopHeadMetrics, chord.AbsMsPosition); else distanceToChord = VerticalDistanceToHead(chord.ChordMetrics.BottomHeadMetrics, chord.AbsMsPosition); minimumDistanceToChords = minimumDistanceToChords < distanceToChord ? minimumDistanceToChords : distanceToChord; } return minimumDistanceToChords; } /// <summary> /// The distance between the inner edge of this beamBlock and the headmetrics. /// This is a positive value /// a) if the _stemDirection is VerticalDir.up and the headMetrics is completely below this beamBlock, /// or b) if the _stemDirection is VerticalDir.down and the headMetrics is completely above this beamBlock. /// </summary> private float VerticalDistanceToHead(HeadMetrics headMetrics, float headMsPosition) { float headX = headMetrics.OriginX; float headY = headMetrics.Top; float minDistanceToHead = float.MaxValue; float tanA = this.TanAngle; if(_stemDirection == VerticalDir.up) { float beamBottomAtHeadY; foreach(Beam beam in Beams) { float beamBeginMsPosition = BeamBeginMsPosition(beam); float beamEndMsPosition = BeamEndMsPosition(beam); if(beamBeginMsPosition <= headMsPosition && beamEndMsPosition >= headMsPosition) { beamBottomAtHeadY = beam.LeftTopY - ((headX - beam.LeftX) * tanA) + _beamThickness; float distanceToHead = headY - beamBottomAtHeadY; minDistanceToHead = minDistanceToHead < distanceToHead ? minDistanceToHead : distanceToHead; } } } else // _stemDirection == VerticalDir.down { headY = headMetrics.Bottom; float beamTopAtHeadY; foreach(Beam beam in Beams) { float beamBeginMsPosition = BeamBeginMsPosition(beam); float beamEndMsPosition = BeamEndMsPosition(beam); if(beamBeginMsPosition <= headMsPosition && beamEndMsPosition >= headMsPosition) { beamTopAtHeadY = beam.LeftTopY - ((headX - beam.LeftX) * tanA); float distanceToHead = beamTopAtHeadY - headY; minDistanceToHead = minDistanceToHead < distanceToHead ? minDistanceToHead : distanceToHead; } } } return minDistanceToHead; } private float BeamBeginMsPosition(Beam beam) { Debug.Assert(this.Beams.Contains(beam)); float beamBeginAbsMsPosition = float.MinValue; foreach(ChordSymbol chord in Chords) { float stemX = chord.ChordMetrics.StemMetrics.OriginX; if(stemX == beam.LeftX || stemX == beam.RightX) // rightX can be a beam stub { beamBeginAbsMsPosition = chord.AbsMsPosition; break; } } Debug.Assert(beamBeginAbsMsPosition != float.MinValue); return beamBeginAbsMsPosition; } private float BeamEndMsPosition(Beam beam) { Debug.Assert(this.Beams.Contains(beam)); float beamEndAbsMsPosition = float.MinValue; for(int i = Chords.Count - 1; i >= 0; --i) { ChordSymbol chord = Chords[i]; float stemX = chord.ChordMetrics.StemMetrics.OriginX; if(stemX == beam.LeftX || stemX == beam.RightX) // rightX can be a beam stub { beamEndAbsMsPosition = chord.AbsMsPosition; break; } } Debug.Assert(beamEndAbsMsPosition != float.MinValue); return beamEndAbsMsPosition; } public override void WriteSVG(SvgWriter w) { bool isInput = (CSSObjectClass == CSSObjectClass.inputBeamBlock); w.SvgStartGroup(CSSObjectClass.ToString()); foreach(Beam beam in Beams) { if(!(beam is QuaverBeam)) { float topLeft = 0F; float topRight = 0F; if(_stemDirection == VerticalDir.down) { topLeft = beam.LeftTopY + _beamThickness; topRight = beam.RightTopY + _beamThickness; } else { topLeft = beam.LeftTopY - _beamThickness; topRight = beam.RightTopY - _beamThickness; } w.SvgBeam(beam.LeftX, beam.RightX, topLeft, topRight, _beamThickness * 1.5F, true, isInput); } w.SvgBeam(beam.LeftX, beam.RightX, beam.LeftTopY, beam.RightTopY, _beamThickness, false, isInput); } w.SvgEndGroup(); } public readonly List<ChordSymbol> Chords = null; public float DefaultStemTipY { get { return _defaultStemTipY; } } private readonly float _defaultStemTipY; private readonly float _gap; private readonly float _beamSeparation; // the distance from the top of one beam to the top of the next beam private readonly float _beamThickness; private readonly float _strokeThickness; private readonly VerticalDir _stemDirection = VerticalDir.none; public HashSet<Beam> Beams = new HashSet<Beam>(); } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.NodeAddressBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBNodeAddressNodeAddressStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonULong64))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBNodeAddressMonitorAssociation))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBMonitorIP))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBMonitorInstanceState))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBObjectStatus))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBNodeAddressMonitorAssociationRemoval))] public partial class LocalLBNodeAddress : iControlInterface { public LocalLBNodeAddress() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void create( string [] node_addresses, long [] limits ) { this.Invoke("create", new object [] { node_addresses, limits}); } public System.IAsyncResult Begincreate(string [] node_addresses,long [] limits, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { node_addresses, limits}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_node_addresses //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void delete_all_node_addresses( ) { this.Invoke("delete_all_node_addresses", new object [0]); } public System.IAsyncResult Begindelete_all_node_addresses(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_node_addresses", new object[0], callback, asyncState); } public void Enddelete_all_node_addresses(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_node_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void delete_node_address( string [] node_addresses ) { this.Invoke("delete_node_address", new object [] { node_addresses}); } public System.IAsyncResult Begindelete_node_address(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_node_address", new object[] { node_addresses}, callback, asyncState); } public void Enddelete_node_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBNodeAddressNodeAddressStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBNodeAddressNodeAddressStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBNodeAddressNodeAddressStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBNodeAddressNodeAddressStatistics)(results[0])); } //----------------------------------------------------------------------- // get_connection_limit //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonULong64 [] get_connection_limit( string [] node_addresses ) { object [] results = this.Invoke("get_connection_limit", new object [] { node_addresses}); return ((CommonULong64 [])(results[0])); } public System.IAsyncResult Beginget_connection_limit(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_connection_limit", new object[] { node_addresses}, callback, asyncState); } public CommonULong64 [] Endget_connection_limit(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonULong64 [])(results[0])); } //----------------------------------------------------------------------- // get_dynamic_ratio //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public short [] get_dynamic_ratio( string [] node_addresses ) { object [] results = this.Invoke("get_dynamic_ratio", new object [] { node_addresses}); return ((short [])(results[0])); } public System.IAsyncResult Beginget_dynamic_ratio(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dynamic_ratio", new object[] { node_addresses}, callback, asyncState); } public short [] Endget_dynamic_ratio(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((short [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_monitor_association //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBNodeAddressMonitorAssociation [] get_monitor_association( LocalLBMonitorIP [] addresses ) { object [] results = this.Invoke("get_monitor_association", new object [] { addresses}); return ((LocalLBNodeAddressMonitorAssociation [])(results[0])); } public System.IAsyncResult Beginget_monitor_association(LocalLBMonitorIP [] addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_monitor_association", new object[] { addresses}, callback, asyncState); } public LocalLBNodeAddressMonitorAssociation [] Endget_monitor_association(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBNodeAddressMonitorAssociation [])(results[0])); } //----------------------------------------------------------------------- // get_monitor_instance //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBMonitorInstanceState [] [] get_monitor_instance( LocalLBMonitorIP [] addresses ) { object [] results = this.Invoke("get_monitor_instance", new object [] { addresses}); return ((LocalLBMonitorInstanceState [] [])(results[0])); } public System.IAsyncResult Beginget_monitor_instance(LocalLBMonitorIP [] addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_monitor_instance", new object[] { addresses}, callback, asyncState); } public LocalLBMonitorInstanceState [] [] Endget_monitor_instance(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBMonitorInstanceState [] [])(results[0])); } //----------------------------------------------------------------------- // get_monitor_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBMonitorStatus [] get_monitor_status( string [] node_addresses ) { object [] results = this.Invoke("get_monitor_status", new object [] { node_addresses}); return ((LocalLBMonitorStatus [])(results[0])); } public System.IAsyncResult Beginget_monitor_status(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_monitor_status", new object[] { node_addresses}, callback, asyncState); } public LocalLBMonitorStatus [] Endget_monitor_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBMonitorStatus [])(results[0])); } //----------------------------------------------------------------------- // get_object_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBObjectStatus [] get_object_status( string [] node_addresses ) { object [] results = this.Invoke("get_object_status", new object [] { node_addresses}); return ((LocalLBObjectStatus [])(results[0])); } public System.IAsyncResult Beginget_object_status(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_object_status", new object[] { node_addresses}, callback, asyncState); } public LocalLBObjectStatus [] Endget_object_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBObjectStatus [])(results[0])); } //----------------------------------------------------------------------- // get_ratio //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] get_ratio( string [] node_addresses ) { object [] results = this.Invoke("get_ratio", new object [] { node_addresses}); return ((long [])(results[0])); } public System.IAsyncResult Beginget_ratio(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_ratio", new object[] { node_addresses}, callback, asyncState); } public long [] Endget_ratio(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [])(results[0])); } //----------------------------------------------------------------------- // get_screen_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_screen_name( string [] node_addresses ) { object [] results = this.Invoke("get_screen_name", new object [] { node_addresses}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_screen_name(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_screen_name", new object[] { node_addresses}, callback, asyncState); } public string [] Endget_screen_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_session_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] get_session_enabled_state( string [] node_addresses ) { object [] results = this.Invoke("get_session_enabled_state", new object [] { node_addresses}); return ((CommonEnabledState [])(results[0])); } public System.IAsyncResult Beginget_session_enabled_state(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_session_enabled_state", new object[] { node_addresses}, callback, asyncState); } public CommonEnabledState [] Endget_session_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [])(results[0])); } //----------------------------------------------------------------------- // get_session_status //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBSessionStatus [] get_session_status( string [] node_addresses ) { object [] results = this.Invoke("get_session_status", new object [] { node_addresses}); return ((LocalLBSessionStatus [])(results[0])); } public System.IAsyncResult Beginget_session_status(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_session_status", new object[] { node_addresses}, callback, asyncState); } public LocalLBSessionStatus [] Endget_session_status(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBSessionStatus [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBNodeAddressNodeAddressStatistics get_statistics( string [] node_addresses ) { object [] results = this.Invoke("get_statistics", new object [] { node_addresses}); return ((LocalLBNodeAddressNodeAddressStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { node_addresses}, callback, asyncState); } public LocalLBNodeAddressNodeAddressStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBNodeAddressNodeAddressStatistics)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_monitor_association //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void remove_monitor_association( LocalLBNodeAddressMonitorAssociationRemoval [] monitor_associations ) { this.Invoke("remove_monitor_association", new object [] { monitor_associations}); } public System.IAsyncResult Beginremove_monitor_association(LocalLBNodeAddressMonitorAssociationRemoval [] monitor_associations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_monitor_association", new object[] { monitor_associations}, callback, asyncState); } public void Endremove_monitor_association(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void reset_statistics( string [] node_addresses ) { this.Invoke("reset_statistics", new object [] { node_addresses}); } public System.IAsyncResult Beginreset_statistics(string [] node_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { node_addresses}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_connection_limit //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_connection_limit( string [] node_addresses, CommonULong64 [] limits ) { this.Invoke("set_connection_limit", new object [] { node_addresses, limits}); } public System.IAsyncResult Beginset_connection_limit(string [] node_addresses,CommonULong64 [] limits, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_connection_limit", new object[] { node_addresses, limits}, callback, asyncState); } public void Endset_connection_limit(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_dynamic_ratio //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_dynamic_ratio( string [] node_addresses, short [] dynamic_ratios ) { this.Invoke("set_dynamic_ratio", new object [] { node_addresses, dynamic_ratios}); } public System.IAsyncResult Beginset_dynamic_ratio(string [] node_addresses,short [] dynamic_ratios, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_dynamic_ratio", new object[] { node_addresses, dynamic_ratios}, callback, asyncState); } public void Endset_dynamic_ratio(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_monitor_association //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_monitor_association( LocalLBNodeAddressMonitorAssociation [] monitor_associations ) { this.Invoke("set_monitor_association", new object [] { monitor_associations}); } public System.IAsyncResult Beginset_monitor_association(LocalLBNodeAddressMonitorAssociation [] monitor_associations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_monitor_association", new object[] { monitor_associations}, callback, asyncState); } public void Endset_monitor_association(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_monitor_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_monitor_state( string [] node_addresses, CommonEnabledState [] states ) { this.Invoke("set_monitor_state", new object [] { node_addresses, states}); } public System.IAsyncResult Beginset_monitor_state(string [] node_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_monitor_state", new object[] { node_addresses, states}, callback, asyncState); } public void Endset_monitor_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_ratio //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_ratio( string [] node_addresses, long [] ratios ) { this.Invoke("set_ratio", new object [] { node_addresses, ratios}); } public System.IAsyncResult Beginset_ratio(string [] node_addresses,long [] ratios, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_ratio", new object[] { node_addresses, ratios}, callback, asyncState); } public void Endset_ratio(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_screen_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_screen_name( string [] node_addresses, string [] names ) { this.Invoke("set_screen_name", new object [] { node_addresses, names}); } public System.IAsyncResult Beginset_screen_name(string [] node_addresses,string [] names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_screen_name", new object[] { node_addresses, names}, callback, asyncState); } public void Endset_screen_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_session_enabled_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/NodeAddress", RequestNamespace="urn:iControl:LocalLB/NodeAddress", ResponseNamespace="urn:iControl:LocalLB/NodeAddress")] public void set_session_enabled_state( string [] node_addresses, CommonEnabledState [] states ) { this.Invoke("set_session_enabled_state", new object [] { node_addresses, states}); } public System.IAsyncResult Beginset_session_enabled_state(string [] node_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_session_enabled_state", new object[] { node_addresses, states}, callback, asyncState); } public void Endset_session_enabled_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.NodeAddress.MonitorAssociation", Namespace = "urn:iControl")] public partial class LocalLBNodeAddressMonitorAssociation { private LocalLBMonitorIP node_addressField; public LocalLBMonitorIP node_address { get { return this.node_addressField; } set { this.node_addressField = value; } } private LocalLBMonitorRule monitor_ruleField; public LocalLBMonitorRule monitor_rule { get { return this.monitor_ruleField; } set { this.monitor_ruleField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.NodeAddress.MonitorAssociationRemoval", Namespace = "urn:iControl")] public partial class LocalLBNodeAddressMonitorAssociationRemoval { private LocalLBMonitorIP node_addressField; public LocalLBMonitorIP node_address { get { return this.node_addressField; } set { this.node_addressField = value; } } private LocalLBMonitorAssociationRemovalRule removal_ruleField; public LocalLBMonitorAssociationRemovalRule removal_rule { get { return this.removal_ruleField; } set { this.removal_ruleField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.NodeAddress.NodeAddressStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBNodeAddressNodeAddressStatisticEntry { private string node_addressField; public string node_address { get { return this.node_addressField; } set { this.node_addressField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.NodeAddress.NodeAddressStatistics", Namespace = "urn:iControl")] public partial class LocalLBNodeAddressNodeAddressStatistics { private LocalLBNodeAddressNodeAddressStatisticEntry [] statisticsField; public LocalLBNodeAddressNodeAddressStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Audio; using osu.Framework.Audio.Sample; using osu.Framework.Graphics.Audio; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Audio; using osu.Game.IO; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.UI; using osu.Game.Screens.Play; using osu.Game.Skinning; using osu.Game.Storyboards; using osu.Game.Storyboards.Drawables; using osu.Game.Tests.Resources; using osu.Game.Tests.Visual; namespace osu.Game.Tests.Gameplay { [HeadlessTest] public class TestSceneStoryboardSamples : OsuTestScene, IStorageResourceProvider { [Test] public void TestRetrieveTopLevelSample() { ISkin skin = null; ISample channel = null; AddStep("create skin", () => skin = new TestSkin("test-sample", this)); AddStep("retrieve sample", () => channel = skin.GetSample(new SampleInfo("test-sample"))); AddAssert("sample is non-null", () => channel != null); } [Test] public void TestRetrieveSampleInSubFolder() { ISkin skin = null; ISample channel = null; AddStep("create skin", () => skin = new TestSkin("folder/test-sample", this)); AddStep("retrieve sample", () => channel = skin.GetSample(new SampleInfo("folder/test-sample"))); AddAssert("sample is non-null", () => channel != null); } [Test] public void TestSamplePlaybackAtZero() { GameplayClockContainer gameplayContainer = null; DrawableStoryboardSample sample = null; AddStep("create container", () => { var working = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo); working.LoadTrack(); Add(gameplayContainer = new MasterGameplayClockContainer(working, 0) { IsPaused = { Value = true }, Child = new FrameStabilityContainer { Child = sample = new DrawableStoryboardSample(new StoryboardSampleInfo(string.Empty, 0, 1)) } }); }); AddStep("reset clock", () => gameplayContainer.Start()); AddUntilStep("sample played", () => sample.RequestedPlaying); AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue); } [Test] public void TestSampleHasLifetimeEndWithInitialClockTime() { GameplayClockContainer gameplayContainer = null; DrawableStoryboardSample sample = null; AddStep("create container", () => { var working = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo); working.LoadTrack(); Add(gameplayContainer = new MasterGameplayClockContainer(working, 1000, true) { IsPaused = { Value = true }, Child = new FrameStabilityContainer { Child = sample = new DrawableStoryboardSample(new StoryboardSampleInfo(string.Empty, 0, 1)) } }); }); AddStep("start time", () => gameplayContainer.Start()); AddUntilStep("sample not played", () => !sample.RequestedPlaying); AddUntilStep("sample has lifetime end", () => sample.LifetimeEnd < double.MaxValue); } [TestCase(typeof(OsuModDoubleTime), 1.5)] [TestCase(typeof(OsuModHalfTime), 0.75)] [TestCase(typeof(ModWindUp), 1.5)] [TestCase(typeof(ModWindDown), 0.75)] [TestCase(typeof(OsuModDoubleTime), 2)] [TestCase(typeof(OsuModHalfTime), 0.5)] [TestCase(typeof(ModWindUp), 2)] [TestCase(typeof(ModWindDown), 0.5)] public void TestSamplePlaybackWithRateMods(Type expectedMod, double expectedRate) { GameplayClockContainer gameplayContainer = null; StoryboardSampleInfo sampleInfo = null; TestDrawableStoryboardSample sample = null; Mod testedMod = Activator.CreateInstance(expectedMod) as Mod; switch (testedMod) { case ModRateAdjust m: m.SpeedChange.Value = expectedRate; break; case ModTimeRamp m: m.FinalRate.Value = m.InitialRate.Value = expectedRate; break; } AddStep("setup storyboard sample", () => { Beatmap.Value = new TestCustomSkinWorkingBeatmap(new OsuRuleset().RulesetInfo, this); SelectedMods.Value = new[] { testedMod }; var beatmapSkinSourceContainer = new BeatmapSkinProvidingContainer(Beatmap.Value.Skin); Add(gameplayContainer = new MasterGameplayClockContainer(Beatmap.Value, 0) { Child = beatmapSkinSourceContainer }); beatmapSkinSourceContainer.Add(sample = new TestDrawableStoryboardSample(sampleInfo = new StoryboardSampleInfo("test-sample", 1, 1)) { Clock = gameplayContainer.GameplayClock }); }); AddStep("start", () => gameplayContainer.Start()); AddAssert("sample playback rate matches mod rates", () => testedMod != null && Precision.AlmostEquals( sample.ChildrenOfType<DrawableSample>().First().AggregateFrequency.Value, ((IApplicableToRate)testedMod).ApplyToRate(sampleInfo.StartTime))); } private class TestSkin : LegacySkin { public TestSkin(string resourceName, IStorageResourceProvider resources) : base(DefaultLegacySkin.Info, new TestResourceStore(resourceName), resources, "skin.ini") { } } private class TestResourceStore : IResourceStore<byte[]> { private readonly string resourceName; public TestResourceStore(string resourceName) { this.resourceName = resourceName; } public byte[] Get(string name) => name == resourceName ? TestResources.GetStore().Get("Resources/Samples/test-sample.mp3") : null; public Task<byte[]> GetAsync(string name) => name == resourceName ? TestResources.GetStore().GetAsync("Resources/Samples/test-sample.mp3") : null; public Stream GetStream(string name) => name == resourceName ? TestResources.GetStore().GetStream("Resources/Samples/test-sample.mp3") : null; public IEnumerable<string> GetAvailableResources() => new[] { resourceName }; public void Dispose() { } } private class TestCustomSkinWorkingBeatmap : ClockBackedTestWorkingBeatmap { private readonly IStorageResourceProvider resources; public TestCustomSkinWorkingBeatmap(RulesetInfo ruleset, IStorageResourceProvider resources) : base(ruleset, null, resources.AudioManager) { this.resources = resources; } protected internal override ISkin GetSkin() => new TestSkin("test-sample", resources); } private class TestDrawableStoryboardSample : DrawableStoryboardSample { public TestDrawableStoryboardSample(StoryboardSampleInfo sampleInfo) : base(sampleInfo) { } } #region IResourceStorageProvider public AudioManager AudioManager => Audio; public IResourceStore<byte[]> Files => null; public new IResourceStore<byte[]> Resources => base.Resources; public IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => null; #endregion } }
/***************************************************************************** * Spine Attribute Drawers created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Reflection; using Spine; public struct SpineDrawerValuePair { public string str; public SerializedProperty property; public SpineDrawerValuePair(string val, SerializedProperty property) { this.str = val; this.property = property; } } public abstract class SpineTreeItemDrawerBase<T> : PropertyDrawer where T:SpineAttributeBase { protected SkeletonDataAsset skeletonDataAsset; protected T TargetAttribute { get { return (T)attribute; } } public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType != SerializedPropertyType.String) { EditorGUI.LabelField(position, "ERROR:", "May only apply to type string"); return; } var dataProperty = property.serializedObject.FindProperty(TargetAttribute.dataField); if (dataProperty != null) { if (dataProperty.objectReferenceValue is SkeletonDataAsset) { skeletonDataAsset = (SkeletonDataAsset)dataProperty.objectReferenceValue; } else if (dataProperty.objectReferenceValue is SkeletonRenderer) { var renderer = (SkeletonRenderer)dataProperty.objectReferenceValue; if (renderer != null) skeletonDataAsset = renderer.skeletonDataAsset; } else { EditorGUI.LabelField(position, "ERROR:", "Invalid reference type"); return; } } else if (property.serializedObject.targetObject is Component) { var component = (Component)property.serializedObject.targetObject; if (component.GetComponentInChildren<SkeletonRenderer>() != null) { var skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>(); skeletonDataAsset = skeletonRenderer.skeletonDataAsset; } } if (skeletonDataAsset == null) { EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset"); return; } position = EditorGUI.PrefixLabel(position, label); if (GUI.Button(position, property.stringValue, EditorStyles.popup)) { Selector(property); } } protected virtual void Selector (SerializedProperty property) { SkeletonData data = skeletonDataAsset.GetSkeletonData(true); if (data == null) return; GenericMenu menu = new GenericMenu(); PopulateMenu (menu, property, this.TargetAttribute, data); menu.ShowAsContext(); } protected abstract void PopulateMenu (GenericMenu menu, SerializedProperty property, T targetAttribute, SkeletonData data); protected virtual void HandleSelect (object val) { var pair = (SpineDrawerValuePair)val; pair.property.stringValue = pair.str; pair.property.serializedObject.ApplyModifiedProperties(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 18; } } [CustomPropertyDrawer(typeof(SpineSlot))] public class SpineSlotDrawer : SpineTreeItemDrawerBase<SpineSlot> { protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineSlot targetAttribute, SkeletonData data) { for (int i = 0; i < data.Slots.Count; i++) { string name = data.Slots.Items[i].Name; if (name.StartsWith(targetAttribute.startsWith)) { if (targetAttribute.containsBoundingBoxes) { int slotIndex = i; List<Attachment> attachments = new List<Attachment>(); foreach (var skin in data.Skins) { skin.FindAttachmentsForSlot(slotIndex, attachments); } bool hasBoundingBox = false; foreach (var attachment in attachments) { if (attachment is BoundingBoxAttachment) { menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); hasBoundingBox = true; break; } } if (!hasBoundingBox) menu.AddDisabledItem(new GUIContent(name)); } else { menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } } } } } [CustomPropertyDrawer(typeof(SpineSkin))] public class SpineSkinDrawer : SpineTreeItemDrawerBase<SpineSkin> { protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineSkin targetAttribute, SkeletonData data) { menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name)); menu.AddSeparator(""); for (int i = 0; i < data.Skins.Count; i++) { string name = data.Skins.Items[i].Name; if (name.StartsWith(targetAttribute.startsWith)) menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } } } [CustomPropertyDrawer(typeof(SpineAnimation))] public class SpineAnimationDrawer : SpineTreeItemDrawerBase<SpineAnimation> { protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineAnimation targetAttribute, SkeletonData data) { var animations = skeletonDataAsset.GetAnimationStateData().SkeletonData.Animations; for (int i = 0; i < animations.Count; i++) { string name = animations.Items[i].Name; if (name.StartsWith(targetAttribute.startsWith)) menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } } } [CustomPropertyDrawer(typeof(SpineEvent))] public class SpineEventNameDrawer : SpineTreeItemDrawerBase<SpineEvent> { protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineEvent targetAttribute, SkeletonData data) { var events = skeletonDataAsset.GetSkeletonData(false).Events; for (int i = 0; i < events.Count; i++) { string name = events.Items[i].Name; if (name.StartsWith(targetAttribute.startsWith)) menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } } } [CustomPropertyDrawer(typeof(SpineAttachment))] public class SpineAttachmentDrawer : SpineTreeItemDrawerBase<SpineAttachment> { protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineAttachment targetAttribute, SkeletonData data) { List<Skin> validSkins = new List<Skin>(); SkeletonRenderer skeletonRenderer = null; var component = property.serializedObject.targetObject as Component; if (component != null) { if (component.GetComponentInChildren<SkeletonRenderer>() != null) { skeletonRenderer = component.GetComponentInChildren<SkeletonRenderer>(); //if (skeletonDataAsset != skeletonRenderer.skeletonDataAsset) Debug.LogWarning("DataField SkeletonDataAsset and SkeletonRenderer/SkeletonAnimation's SkeletonDataAsset do not match. Remove the explicit dataField parameter of your [SpineAttachment] field."); skeletonDataAsset = skeletonRenderer.skeletonDataAsset; } } if (skeletonRenderer != null && targetAttribute.currentSkinOnly) { if (skeletonRenderer.skeleton.Skin != null) { validSkins.Add(skeletonRenderer.skeleton.Skin); } else { validSkins.Add(data.Skins.Items[0]); } } else { foreach (Skin skin in data.Skins) { if (skin != null) validSkins.Add(skin); } } List<string> attachmentNames = new List<string>(); List<string> placeholderNames = new List<string>(); string prefix = ""; if (skeletonRenderer != null && targetAttribute.currentSkinOnly) menu.AddDisabledItem(new GUIContent(skeletonRenderer.gameObject.name + " (SkeletonRenderer)")); else menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name)); menu.AddSeparator(""); menu.AddItem(new GUIContent("Null"), property.stringValue == "", HandleSelect, new SpineDrawerValuePair("", property)); menu.AddSeparator(""); Skin defaultSkin = data.Skins.Items[0]; SerializedProperty slotProperty = property.serializedObject.FindProperty(targetAttribute.slotField); string slotMatch = ""; if (slotProperty != null) { if (slotProperty.propertyType == SerializedPropertyType.String) { slotMatch = slotProperty.stringValue.ToLower(); } } foreach (Skin skin in validSkins) { string skinPrefix = skin.Name + "/"; if (validSkins.Count > 1) prefix = skinPrefix; for (int i = 0; i < data.Slots.Count; i++) { if (slotMatch.Length > 0 && data.Slots.Items[i].Name.ToLower().Contains(slotMatch) == false) continue; attachmentNames.Clear(); placeholderNames.Clear(); skin.FindNamesForSlot(i, attachmentNames); if (skin != defaultSkin) { defaultSkin.FindNamesForSlot(i, attachmentNames); skin.FindNamesForSlot(i, placeholderNames); } for (int a = 0; a < attachmentNames.Count; a++) { string attachmentPath = attachmentNames[a]; string menuPath = prefix + data.Slots.Items[i].Name + "/" + attachmentPath; string name = attachmentNames[a]; if (targetAttribute.returnAttachmentPath) name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath; if (targetAttribute.placeholdersOnly && placeholderNames.Contains(attachmentPath) == false) { menu.AddDisabledItem(new GUIContent(menuPath)); } else { menu.AddItem(new GUIContent(menuPath), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } } } } } } [CustomPropertyDrawer(typeof(SpineBone))] public class SpineBoneDrawer : SpineTreeItemDrawerBase<SpineBone> { protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineBone targetAttribute, SkeletonData data) { menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name)); menu.AddSeparator(""); for (int i = 0; i < data.Bones.Count; i++) { string name = data.Bones.Items[i].Name; if (name.StartsWith(targetAttribute.startsWith)) menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } } } [CustomPropertyDrawer(typeof(SpineAtlasRegion))] public class SpineAtlasRegionDrawer : PropertyDrawer { Component component; SerializedProperty atlasProp; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType != SerializedPropertyType.String) { EditorGUI.LabelField(position, "ERROR:", "May only apply to type string"); return; } component = (Component)property.serializedObject.targetObject; if (component != null) atlasProp = property.serializedObject.FindProperty("atlasAsset"); else atlasProp = null; if (atlasProp == null) { EditorGUI.LabelField(position, "ERROR:", "Must have AtlasAsset variable!"); return; } else if (atlasProp.objectReferenceValue == null) { EditorGUI.LabelField(position, "ERROR:", "Atlas variable must not be null!"); return; } else if (atlasProp.objectReferenceValue.GetType() != typeof(AtlasAsset)) { EditorGUI.LabelField(position, "ERROR:", "Atlas variable must be of type AtlasAsset!"); } position = EditorGUI.PrefixLabel(position, label); if (GUI.Button(position, property.stringValue, EditorStyles.popup)) { Selector(property); } } void Selector (SerializedProperty property) { GenericMenu menu = new GenericMenu(); AtlasAsset atlasAsset = (AtlasAsset)atlasProp.objectReferenceValue; Atlas atlas = atlasAsset.GetAtlas(); FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic); List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas); for (int i = 0; i < regions.Count; i++) { string name = regions[i].name; menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property)); } menu.ShowAsContext(); } static void HandleSelect (object val) { var pair = (SpineDrawerValuePair)val; pair.property.stringValue = pair.str; pair.property.serializedObject.ApplyModifiedProperties(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void HorizontalAddDouble() { var test = new HorizontalBinaryOpTest__HorizontalAddDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalAddDouble { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private HorizontalBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static HorizontalBinaryOpTest__HorizontalAddDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public HorizontalBinaryOpTest__HorizontalAddDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new HorizontalBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse3.HorizontalAdd( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse3.HorizontalAdd( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse3.HorizontalAdd( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse3).GetMethod(nameof(Sse3.HorizontalAdd), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse3.HorizontalAdd( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse3.HorizontalAdd(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse3.HorizontalAdd(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new HorizontalBinaryOpTest__HorizontalAddDouble(); var result = Sse3.HorizontalAdd(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse3.HorizontalAdd(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { for (var outer = 0; outer < (VectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Double)); inner++) { var i1 = (outer * (16 / sizeof(Double))) + inner; var i2 = i1 + (8 / sizeof(Double)); var i3 = (outer * (16 / sizeof(Double))) + (inner * 2); if (BitConverter.DoubleToInt64Bits(result[i1]) != BitConverter.DoubleToInt64Bits(left[i3] + left[i3 + 1])) { Succeeded = false; break; } if (BitConverter.DoubleToInt64Bits(result[i2]) != BitConverter.DoubleToInt64Bits(right[i3] + right[i3 + 1])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse3)}.{nameof(Sse3.HorizontalAdd)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using Gedcomx.Model.Rt; using Gx.Common; using Gx.Conclusion; using Gx.Links; using Gx.Records; using Gx.Source; // <auto-generated> // // // Generated by <a href="http://enunciate.codehaus.org">Enunciate</a>. // </auto-generated> using System; using System.Xml.Serialization; using Newtonsoft.Json; using System.Collections.Generic; namespace Gx { /// <remarks> /// &lt;p&gt;The GEDCOM X data formats define the serialization formats of the GEDCOM X conceptual model. The canonical documentation /// is provided by the formal specification documents:&lt;/p&gt; /// /// &lt;ul&gt; /// &lt;li&gt;&lt;a href=&quot;https://github.com/FamilySearch/gedcomx/blob/master/specifications/conceptual-model-specification.md&quot;&gt;The GEDCOM X Conceptual Model, Version 1.0&lt;/a&gt;&lt;/li&gt; /// &lt;li&gt;&lt;a href=&quot;https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md&quot;&gt;The GEDCOM X JSON Format, Version 1.0&lt;/a&gt;&lt;/li&gt; /// &lt;li&gt;&lt;a href=&quot;https://github.com/FamilySearch/gedcomx/blob/master/specifications/xml-format-specification.md&quot;&gt;The GEDCOM X XML Format, Version 1.0&lt;/a&gt;&lt;/li&gt; /// &lt;/ul&gt; /// /// &lt;p&gt;This documentation is provided as a non-normative reference guide.&lt;/p&gt; /// </remarks> /// <summary> /// &lt;p&gt;The GEDCOM X data formats define the serialization formats of the GEDCOM X conceptual model. The canonical documentation /// is provided by the formal specification documents:&lt;/p&gt; /// /// &lt;ul&gt; /// &lt;li&gt;&lt;a href=&quot;https://github.com/FamilySearch/gedcomx/blob/master/specifications/conceptual-model-specification.md&quot;&gt;The GEDCOM X Conceptual Model, Version 1.0&lt;/a&gt;&lt;/li&gt; /// &lt;li&gt;&lt;a href=&quot;https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md&quot;&gt;The GEDCOM X JSON Format, Version 1.0&lt;/a&gt;&lt;/li&gt; /// &lt;li&gt;&lt;a href=&quot;https://github.com/FamilySearch/gedcomx/blob/master/specifications/xml-format-specification.md&quot;&gt;The GEDCOM X XML Format, Version 1.0&lt;/a&gt;&lt;/li&gt; /// &lt;/ul&gt; /// /// &lt;p&gt;This documentation is provided as a non-normative reference guide.&lt;/p&gt; /// </summary> [Serializable] [XmlType(Namespace = "http://gedcomx.org/v1/", TypeName = "Gedcomx")] [XmlRoot(Namespace = "http://gedcomx.org/v1/", ElementName = "gedcomx")] public partial class Gedcomx : Gx.Links.HypermediaEnabledData { private string _lang; private string _descriptionRef; private string _profile; private Gx.Common.Attribution _attribution; private List<Gx.Conclusion.Person> _persons; private List<Gx.Conclusion.Relationship> _relationships; private List<Gx.Source.SourceDescription> _sourceDescriptions; private List<Gx.Agent.Agent> _agents; private List<Gx.Conclusion.Event> _events; private List<Gx.Conclusion.PlaceDescription> _places; private List<Gx.Conclusion.Document> _documents; private List<Gx.Records.Collection> _collections; private List<Gx.Records.Field> _fields; private List<Gx.Records.RecordDescriptor> _recordDescriptors; /// <summary> /// The language of the genealogical data. /// </summary> [XmlAttribute(AttributeName = "lang", Namespace = "http://www.w3.org/XML/1998/namespace")] [JsonProperty("lang")] public string Lang { get { return this._lang; } set { this._lang = value; } } /// <summary> /// A reference to a description of this data set. /// </summary> [XmlAttribute(AttributeName = "description")] [JsonProperty("description")] public string DescriptionRef { get { return this._descriptionRef; } set { this._descriptionRef = value; } } /// <summary> /// A reference to the profile that describes this data set. /// </summary> [XmlAttribute(AttributeName = "profile")] [JsonProperty("profile")] public string Profile { get { return this._profile; } set { this._profile = value; } } /// <summary> /// The attribution of this genealogical data. /// </summary> [XmlElement(ElementName = "attribution", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("attribution")] public Gx.Common.Attribution Attribution { get { return this._attribution; } set { this._attribution = value; } } /// <summary> /// The persons included in this genealogical data set. /// </summary> [XmlElement(ElementName = "person", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("persons")] public List<Gx.Conclusion.Person> Persons { get { return this._persons; } set { this._persons = value; } } /// <summary> /// The relationships included in this genealogical data set. /// </summary> [XmlElement(ElementName = "relationship", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("relationships")] public List<Gx.Conclusion.Relationship> Relationships { get { return this._relationships; } set { this._relationships = value; } } /// <summary> /// The descriptions of sources included in this genealogical data set. /// </summary> [XmlElement(ElementName = "sourceDescription", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("sourceDescriptions")] public List<Gx.Source.SourceDescription> SourceDescriptions { get { return this._sourceDescriptions; } set { this._sourceDescriptions = value; } } /// <summary> /// The agents included in this genealogical data set. /// </summary> [XmlElement(ElementName = "agent", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("agents")] public List<Gx.Agent.Agent> Agents { get { return this._agents; } set { this._agents = value; } } /// <summary> /// The events included in this genealogical data set. /// </summary> [XmlElement(ElementName = "event", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("events")] public List<Gx.Conclusion.Event> Events { get { return this._events; } set { this._events = value; } } /// <summary> /// The places included in this genealogical data set. /// </summary> [XmlElement(ElementName = "place", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("places")] public List<Gx.Conclusion.PlaceDescription> Places { get { return this._places; } set { this._places = value; } } /// <summary> /// The documents included in this genealogical data set. /// </summary> [XmlElement(ElementName = "document", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("documents")] public List<Gx.Conclusion.Document> Documents { get { return this._documents; } set { this._documents = value; } } /// <summary> /// The collections included in this genealogical data set. /// </summary> [XmlElement(ElementName = "collection", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("collections")] public List<Gx.Records.Collection> Collections { get { return this._collections; } set { this._collections = value; } } /// <summary> /// The extracted fields included in this genealogical data set. /// </summary> [XmlElement(ElementName = "field", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("fields")] public List<Gx.Records.Field> Fields { get { return this._fields; } set { this._fields = value; } } /// <summary> /// The record descriptors included in this genealogical data set. /// </summary> [XmlElement(ElementName = "recordDescriptor", Namespace = "http://gedcomx.org/v1/")] [JsonProperty("recordDescriptors")] public List<Gx.Records.RecordDescriptor> RecordDescriptors { get { return this._recordDescriptors; } set { this._recordDescriptors = value; } } public Gedcomx AddCollection(Collection collection) { if (collection != null) { if (Collections == null) { Collections = new List<Collection>(); } Collections.Add(collection); } return this; } public void AddPerson(Person person) { if (person != null) { if (Persons == null) { Persons = new List<Person>(); } Persons.Add(person); } } /// <summary> /// Add a relationship to the data set. /// </summary> /// <param name="relationship">The relationship to be added.</param> public void AddRelationship(Relationship relationship) { if (relationship != null) { if (Relationships == null) Relationships = new List<Relationship>(); Relationships.Add(relationship); } } /// <summary> /// Add a source description to the data set. /// </summary> /// <param name="sourceDescription">The source description to be added.</param> public void AddSourceDescription(SourceDescription sourceDescription) { if (sourceDescription != null) { if (SourceDescriptions == null) SourceDescriptions = new List<SourceDescription>(); SourceDescriptions.Add(sourceDescription); } } /// <summary> /// Add a agent to the data set. /// </summary> /// <param name="agent">The agent to be added.</param> public void AddAgent(Gx.Agent.Agent agent) { if (agent != null) { if (Agents == null) Agents = new List<Gx.Agent.Agent>(); Agents.Add(agent); } } /// <summary> /// Add a event to the data set. /// </summary> /// <param name="event">The event to be added.</param> public void AddEvent(Event @event) { if (@event != null) { if (Events == null) Events = new List<Event>(); Events.Add(@event); } } /// <summary> /// Add a place to the data set. /// </summary> /// <param name="place">The place to be added.</param> public void AddPlace(PlaceDescription place) { if (place != null) { if (Places == null) Places = new List<PlaceDescription>(); Places.Add(place); } } /// <summary> /// Add a document to the data set. /// </summary> /// <param name="document">The document to be added.</param> public void AddDocument(Document document) { if (document != null) { if (Documents == null) Documents = new List<Document>(); Documents.Add(document); } } /// <summary> /// Add a field to the data set. /// </summary> /// <param name="field">The field to be added.</param> public void AddField(Field field) { if (field != null) { if (Fields == null) Fields = new List<Field>(); Fields.Add(field); } } /** * Add a recordDescriptor to the data set. * * @param recordDescriptor The recordDescriptor to be added. */ public void AddRecordDescriptor(RecordDescriptor recordDescriptor) { if (recordDescriptor != null) { if (RecordDescriptors == null) RecordDescriptors = new List<RecordDescriptor>(); RecordDescriptors.Add(recordDescriptor); } } public virtual void Embed(Gedcomx gedcomx) { List<Link> links = gedcomx.Links; if (links != null) { foreach (Link link in links) { bool found = false; if (link.Rel != null) { if (Links != null) { foreach (Link target in Links) { if (link.Rel.Equals(target.Rel)) { found = true; break; } } } } if (!found) { AddLink(link); } } } List<Person> persons = gedcomx.Persons; if (persons != null) { foreach (Person person in persons) { bool found = false; if (person.Id != null) { if (Persons != null) { foreach (Person target in Persons) { if (person.Id.Equals(target.Id)) { target.Embed(person); found = true; break; } } } } if (!found) { AddPerson(person); } } } List<Relationship> relationships = gedcomx.Relationships; if (relationships != null) { foreach (Relationship relationship in relationships) { bool found = false; if (relationship.Id != null) { if (Relationships != null) { foreach (Relationship target in Relationships) { if (relationship.Id.Equals(target.Id)) { target.Embed(relationship); found = true; break; } } } } if (!found) { AddRelationship(relationship); } } } List<SourceDescription> sourceDescriptions = gedcomx.SourceDescriptions; if (sourceDescriptions != null) { foreach (SourceDescription sourceDescription in sourceDescriptions) { bool found = false; if (sourceDescription.Id != null) { if (SourceDescriptions != null) { foreach (SourceDescription target in SourceDescriptions) { if (sourceDescription.Id.Equals(target.Id)) { target.Embed(sourceDescription); found = true; break; } } } } if (!found) { AddSourceDescription(sourceDescription); } } } List<Gx.Agent.Agent> agents = gedcomx.Agents; if (agents != null) { foreach (Gx.Agent.Agent agent in agents) { bool found = false; if (agent.Id != null) { if (Agents != null) { foreach (Gx.Agent.Agent target in Agents) { if (agent.Id.Equals(target.Id)) { target.Embed(agent); found = true; break; } } } } if (!found) { AddAgent(agent); } } } List<Event> events = gedcomx.Events; if (events != null) { foreach (Event @event in events) { bool found = false; if (@event.Id != null) { if (Events != null) { foreach (Event target in Events) { if (@event.Id.Equals(target.Id)) { target.Embed(@event); found = true; break; } } } } if (!found) { AddEvent(@event); } } } List<PlaceDescription> placeDescriptions = gedcomx.Places; if (placeDescriptions != null) { foreach (PlaceDescription placeDescription in placeDescriptions) { bool found = false; if (placeDescription.Id != null) { if (Places != null) { foreach (PlaceDescription target in Places) { if (placeDescription.Id.Equals(target.Id)) { target.Embed(placeDescription); found = true; break; } } } } if (!found) { AddPlace(placeDescription); } } } List<Document> documents = gedcomx.Documents; if (documents != null) { foreach (Document document in documents) { bool found = false; if (document.Id != null) { if (Documents != null) { foreach (Document target in Documents) { if (document.Id.Equals(target.Id)) { target.Embed(document); found = true; break; } } } } if (!found) { AddDocument(document); } } } List<Collection> collections = gedcomx.Collections; if (collections != null) { foreach (Collection collection in collections) { bool found = false; if (collection.Id != null) { if (Collections != null) { foreach (Collection target in Collections) { if (collection.Id.Equals(target.Id)) { target.Embed(collection); found = true; break; } } } } if (!found) { AddCollection(collection); } } } List<Field> fields = gedcomx.Fields; if (fields != null) { foreach (Field field in fields) { bool found = false; if (field.Id != null) { if (Fields != null) { foreach (Field target in Fields) { if (field.Id.Equals(target.Id)) { found = true; break; } } } } if (!found) { AddField(field); } } } List<RecordDescriptor> recordDescriptors = gedcomx.RecordDescriptors; if (recordDescriptors != null) { foreach (RecordDescriptor recordDescriptor in recordDescriptors) { bool found = false; if (recordDescriptor.Id != null) { if (RecordDescriptors != null) { foreach (RecordDescriptor target in RecordDescriptors) { if (recordDescriptor.Id.Equals(target.Id)) { target.Embed(recordDescriptor); found = true; break; } } } } if (!found) { AddRecordDescriptor(recordDescriptor); } } } } /** * Accept a visitor. * * @param visitor The visitor. */ public void Accept(IGedcomxModelVisitor visitor) { visitor.VisitGedcomx(this); } /** * Build out this envelope with a lang. * * @param lang The lang. * @return this. */ public Gedcomx SetLang(String lang) { Lang = lang; return this; } /** * Build out this with a description ref. * * @param descriptionRef The description ref. * @return this. */ public Gedcomx SetDescriptionRef(String descriptionRef) { DescriptionRef = descriptionRef; return this; } /** * Build this out with an attribution. * @param attribution The attribution. * @return this. */ public Gedcomx SetAttribution(Attribution attribution) { Attribution = attribution; return this; } /** * Build this out with a person. * @param person The person. * @return this. */ public Gedcomx SetPerson(Person person) { AddPerson(person); return this; } /** * Build this out with a relationship. * @param relationship The relationship. * @return this. */ public Gedcomx SetRelationship(Relationship relationship) { AddRelationship(relationship); return this; } /** * Build this out with a source description. * @param sourceDescription The source description. * @return this. */ public Gedcomx SetSourceDescription(SourceDescription sourceDescription) { AddSourceDescription(sourceDescription); return this; } /** * Build this out with a agent. * @param agent The agent. * @return this. */ public Gedcomx SetAgent(Gx.Agent.Agent agent) { AddAgent(agent); return this; } /** * Build this out with a event. * @param event The event. * @return this. */ public Gedcomx SetEvent(Event @event) { AddEvent(@event); return this; } /** * Build this out with a place. * @param place The place. * @return this. */ public Gedcomx SetPlace(PlaceDescription place) { AddPlace(place); return this; } /** * Build this out with a document. * @param document The document. * @return this. */ public Gedcomx SetDocument(Document document) { AddDocument(document); return this; } /** * Build this out with a collection. * @param collection The collection. * @return this. */ public Gedcomx SetCollection(Collection collection) { AddCollection(collection); return this; } /** * Build this out with a field. * @param field The field. * @return this. */ public Gedcomx SetField(Field field) { AddField(field); return this; } /** * Build this out with a record descriptor. * * @param recordDescriptor The record descriptor. * @return this. */ public Gedcomx SetRecordDescriptor(RecordDescriptor recordDescriptor) { AddRecordDescriptor(recordDescriptor); return this; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Provisioning.OnPrem.Async.Console { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:41 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext { #region Object /// <summary> /// <p>A collection of useful static methods to deal with objects.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class Object { /// <summary> /// Returns a new object with the given object as the prototype chain. /// </summary> /// <param name="object"><p>The prototype chain for the new object.</p> /// </param> public static void chain(object @object){} /// <summary> /// Parameters<li><span>object</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="object"> /// </param> private static void classify(object @object){} /// <summary> /// Iterates through an object and invokes the given callback function for each iteration. /// The iteration can be stopped by returning false in the callback function. For example: /// <code>var person = { /// name: 'Jacky' /// hairColor: 'black' /// loves: ['food', 'sleeping', 'wife'] /// }; /// <see cref="Ext.Object.each">Ext.Object.each</see>(person, function(key, value, myself) { /// console.log(key + ":" + value); /// if (key === 'hairColor') { /// return false; // stop the iteration /// } /// }); /// </code> /// </summary> /// <param name="object"><p>The object to iterate</p> /// </param> /// <param name="fn"><p>The callback function.</p> /// <h3>Parameters</h3><ul><li><span>key</span> : <see cref="String">String</see><div></div></li><li><span>value</span> : <see cref="Object">Object</see><div></div></li><li><span>object</span> : <see cref="Object">Object</see><div><p>The object itself</p> /// </div></li></ul></param> /// <param name="scope"><p>The execution scope (<c>this</c>) of the callback function</p> /// </param> public static void each(object @object, System.Delegate fn, object scope=null){} /// <summary> /// Converts a query string back into an object. /// Non-recursive: /// <code><see cref="Ext.Object.fromQueryString">Ext.Object.fromQueryString</see>("foo=1&amp;bar=2"); // returns {foo: 1, bar: 2} /// <see cref="Ext.Object.fromQueryString">Ext.Object.fromQueryString</see>("foo=&amp;bar=2"); // returns {foo: null, bar: 2} /// <see cref="Ext.Object.fromQueryString">Ext.Object.fromQueryString</see>("some%20price=%24300"); // returns {'some price': '$300'} /// <see cref="Ext.Object.fromQueryString">Ext.Object.fromQueryString</see>("colors=red&amp;colors=green&amp;colors=blue"); // returns {colors: ['red', 'green', 'blue']} /// </code> /// Recursive: /// <code><see cref="Ext.Object.fromQueryString">Ext.Object.fromQueryString</see>( /// "username=Jacky&amp;"+ /// "dateOfBirth[day]=1&amp;dateOfBirth[month]=2&amp;dateOfBirth[year]=1911&amp;"+ /// "hobbies[0]=coding&amp;hobbies[1]=eating&amp;hobbies[2]=sleeping&amp;"+ /// "hobbies[3][0]=nested&amp;hobbies[3][1]=stuff", true); /// // returns /// { /// username: 'Jacky', /// dateOfBirth: { /// day: '1', /// month: '2', /// year: '1911' /// }, /// hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']] /// } /// </code> /// </summary> /// <param name="queryString"><p>The query string to decode</p> /// </param> /// <param name="recursive"><p>Whether or not to recursively decode the string. This format is supported by /// PHP / Ruby on Rails servers and similar.</p> /// <p>Defaults to: <c>false</c></p></param> /// <returns> /// <span><see cref="Object">Object</see></span><div> /// </div> /// </returns> public static object fromQueryString(JsString queryString, object recursive=null){return null;} /// <summary> /// Returns the first matching key corresponding to the given value. /// If no matching value is found, null is returned. /// <code>var person = { /// name: 'Jacky', /// loves: 'food' /// }; /// alert(<see cref="Ext.Object.getKey">Ext.Object.getKey</see>(person, 'food')); // alerts 'loves' /// </code> /// </summary> /// <param name="object"> /// </param> /// <param name="value"><p>The value to find</p> /// </param> public static void getKey(object @object, object value){} /// <summary> /// Gets all keys of the given object as an array. /// <code>var values = <see cref="Ext.Object.getKeys">Ext.Object.getKeys</see>({ /// name: 'Jacky', /// loves: 'food' /// }); // ['name', 'loves'] /// </code> /// </summary> /// <param name="object"> /// </param> /// <returns> /// <span><see cref="String">String</see>[]</span><div><p>An array of keys from the object</p> /// </div> /// </returns> public static JsString[] getKeys(object @object){return null;} /// <summary> /// Gets the total number of this object's own properties /// <code>var size = <see cref="Ext.Object.getSize">Ext.Object.getSize</see>({ /// name: 'Jacky', /// loves: 'food' /// }); // size equals 2 /// </code> /// </summary> /// <param name="object"> /// </param> /// <returns> /// <span><see cref="Number">Number</see></span><div><p>size</p> /// </div> /// </returns> public static JsNumber getSize(object @object){return null;} /// <summary> /// Gets all values of the given object as an array. /// <code>var values = <see cref="Ext.Object.getValues">Ext.Object.getValues</see>({ /// name: 'Jacky', /// loves: 'food' /// }); // ['Jacky', 'food'] /// </code> /// </summary> /// <param name="object"> /// </param> /// <returns> /// <span><see cref="Array">Array</see></span><div><p>An array of values from the object</p> /// </div> /// </returns> public static JsArray getValues(object @object){return null;} /// <summary> /// Merges any number of objects recursively without referencing them or their children. /// <code>var extjs = { /// companyName: 'Ext JS', /// products: ['Ext JS', 'Ext GWT', 'Ext Designer'], /// isSuperCool: true, /// office: { /// size: 2000, /// location: 'Palo Alto', /// isFun: true /// } /// }; /// var newStuff = { /// companyName: 'Sencha Inc.', /// products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'], /// office: { /// size: 40000, /// location: 'Redwood City' /// } /// }; /// var sencha = <see cref="Ext.Object.merge">Ext.Object.merge</see>(extjs, newStuff); /// // extjs and sencha then equals to /// { /// companyName: 'Sencha Inc.', /// products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'], /// isSuperCool: true, /// office: { /// size: 40000, /// location: 'Redwood City', /// isFun: true /// } /// } /// </code> /// </summary> /// <param name="destination"><p>The object into which all subsequent objects are merged.</p> /// </param> /// <param name="object"><p>Any number of objects to merge into the destination.</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>merged The destination object with all passed objects merged in.</p> /// </div> /// </returns> public static object merge(object destination, object @object){return null;} /// <summary> /// Parameters<li><span>destination</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="destination"> /// </param> private static void mergeIf(object destination){} /// <summary> /// Converts a name - value pair to an array of objects with support for nested structures. Useful to construct /// query strings. For example: /// <code>var objects = <see cref="Ext.Object.toQueryObjects">Ext.Object.toQueryObjects</see>('hobbies', ['reading', 'cooking', 'swimming']); /// // objects then equals: /// [ /// { name: 'hobbies', value: 'reading' }, /// { name: 'hobbies', value: 'cooking' }, /// { name: 'hobbies', value: 'swimming' }, /// ]; /// var objects = <see cref="Ext.Object.toQueryObjects">Ext.Object.toQueryObjects</see>('dateOfBirth', { /// day: 3, /// month: 8, /// year: 1987, /// extra: { /// hour: 4 /// minute: 30 /// } /// }, true); // Recursive /// // objects then equals: /// [ /// { name: 'dateOfBirth[day]', value: 3 }, /// { name: 'dateOfBirth[month]', value: 8 }, /// { name: 'dateOfBirth[year]', value: 1987 }, /// { name: 'dateOfBirth[extra][hour]', value: 4 }, /// { name: 'dateOfBirth[extra][minute]', value: 30 }, /// ]; /// </code> /// </summary> /// <param name="name"> /// </param> /// <param name="value"> /// </param> /// <param name="recursive"><p>True to traverse object recursively</p> /// <p>Defaults to: <c>false</c></p></param> /// <returns> /// <span><see cref="Array">Array</see></span><div> /// </div> /// </returns> public static JsArray toQueryObjects(JsString name, object value, object recursive=null){return null;} /// <summary> /// Takes an object and converts it to an encoded query string. /// Non-recursive: /// <code><see cref="Ext.Object.toQueryString">Ext.Object.toQueryString</see>({foo: 1, bar: 2}); // returns "foo=1&amp;bar=2" /// <see cref="Ext.Object.toQueryString">Ext.Object.toQueryString</see>({foo: null, bar: 2}); // returns "foo=&amp;bar=2" /// <see cref="Ext.Object.toQueryString">Ext.Object.toQueryString</see>({'some price': '$300'}); // returns "some%20price=%24300" /// <see cref="Ext.Object.toQueryString">Ext.Object.toQueryString</see>({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22" /// <see cref="Ext.Object.toQueryString">Ext.Object.toQueryString</see>({colors: ['red', 'green', 'blue']}); // returns "colors=red&amp;colors=green&amp;colors=blue" /// </code> /// Recursive: /// <code><see cref="Ext.Object.toQueryString">Ext.Object.toQueryString</see>({ /// username: 'Jacky', /// dateOfBirth: { /// day: 1, /// month: 2, /// year: 1911 /// }, /// hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']] /// }, true); // returns the following string (broken down and url-decoded for ease of reading purpose): /// // username=Jacky /// // &amp;dateOfBirth[day]=1&amp;dateOfBirth[month]=2&amp;dateOfBirth[year]=1911 /// // &amp;hobbies[0]=coding&amp;hobbies[1]=eating&amp;hobbies[2]=sleeping&amp;hobbies[3][0]=nested&amp;hobbies[3][1]=stuff /// </code> /// </summary> /// <param name="object"><p>The object to encode</p> /// </param> /// <param name="recursive"><p>Whether or not to interpret the object in recursive format. /// (PHP / Ruby on Rails servers and similar).</p> /// <p>Defaults to: <c>false</c></p></param> /// <returns> /// <span><see cref="String">String</see></span><div><p>queryString</p> /// </div> /// </returns> public static JsString toQueryString(object @object, object recursive=null){return null;} public Object(ObjectConfig config){} public Object(){} public Object(params object[] args){} } #endregion #region ObjectConfig [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ObjectConfig { public ObjectConfig(params object[] args){} } #endregion #region ObjectEvents [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class ObjectEvents { public ObjectEvents(params object[] args){} } #endregion }
using System; using System.Collections; using System.Collections.Generic; using Sip.Message; using Base.Message; namespace Sip.Server { partial class LocationService { sealed class Bindings : IEnumerable<Binding> { private readonly object sync; private readonly byte[] aor; private Binding[] bindings; private bool isNew; private bool isStale; [ThreadStatic] private static SkipNullArrayEnumerator<Binding> enumerator; public Bindings(ByteArrayPart toAor) { isStale = false; isNew = true; aor = new byte[toAor.Length]; toAor.BlockCopyTo(aor, 0); bindings = new Binding[1]; sync = this.aor; } public bool IsStale { get { return isStale; } } public bool IsNew { get { return isNew; } } public ByteArrayPart Aor { get { return new ByteArrayPart() { Bytes = aor, Begin = 0, End = aor.Length, }; } } public bool TryRemoveExpired(Action<Bindings, Binding> onRemoveBinding) { lock (sync) { if (isStale) return false; for (int i = 0; i < bindings.Length; i++) if (bindings[i] != null && bindings[i].IsExpired) RemoveBinding(i, onRemoveBinding); UpdateStale(); return true; } } public bool TryRemoveAll(Action<Bindings, Binding> onRemoveBinding) { lock (sync) { if (isStale) return false; for (int i = 0; i < bindings.Length; i++) if (bindings[i] != null && bindings[i].IsExpired) RemoveBinding(i, onRemoveBinding); UpdateStale(); return true; } } public bool TryRemoveByConnectionId(int connectionId, Action<Bindings, Binding> onRemoveBinding) { lock (sync) { if (isStale) return false; for (int i = 0; i < bindings.Length; i++) if (bindings[i] != null && bindings[i].ConnectionAddresses.ConnectionId == connectionId) RemoveBinding(i, onRemoveBinding); UpdateStale(); return true; } } public bool TryUpdate(IncomingMessageEx request, int defaultExpires, out bool isNewData, Action<Bindings, Binding, SipMessageReader> onAddBinding, Action<Bindings, Binding> onRemoveBinding) { isNewData = false; lock (sync) { if (isStale) return false; isNewData = IsNewData(request.Reader.CallId, request.Reader.CSeq.Value); if (isNewData) { var reader = request.Reader; for (int i = 0; i < reader.Count.ContactCount; i++) { int index = FindBindingByAddrSpec(reader.Contact[i].AddrSpec.Value); int expires = GetExpires(reader, i, defaultExpires); if (expires > 0) { if (index >= 0 && bindings[index].IsChanged(reader, i) == false) { bindings[index].Update(reader.CSeq.Value, expires); } else { if (index < 0 && reader.Contact[i].SipInstance.IsValid) index = FindBindingBySipInstance(reader.Contact[i].SipInstance); if (index >= 0) RemoveBinding(index, onRemoveBinding); AddBinding(new Binding(reader, i, expires, request.ConnectionAddresses), onAddBinding, reader); } } else { if (index >= 0) RemoveBinding(index, onRemoveBinding); } } } UpdateStale(); return true; } } private bool IsNewData(ByteArrayPart callId, int cseq) { foreach (var binging in bindings) if (binging != null && binging.IsNewData(callId, cseq) == false) return false; return true; } private void UpdateStale() { for (int i = 0; i < bindings.Length; i++) if (bindings[i] != null) return; isStale = true; } private static int GetExpires(SipMessageReader reader, int contactIndex, int defaultExpires) { int expires; if (reader.Contact[contactIndex].Expires != int.MinValue) expires = reader.Contact[contactIndex].Expires; else if (reader.Expires != int.MinValue) expires = reader.Expires; else expires = defaultExpires; return expires; } #region IEnumerable<Binding> public IEnumerator<Binding> GetEnumerator() { if (enumerator == null) enumerator = new SkipNullArrayEnumerator<Binding>(16); lock (sync) enumerator.Initialize(bindings); return enumerator; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region bindings[] Helpers private int FindBindingByAddrSpec(ByteArrayPart addrSpec) { for (int i = 0; i < bindings.Length; i++) if (bindings[i] != null && bindings[i].AddrSpec == addrSpec) return i; return -1; } private int FindBindingBySipInstance(ByteArrayPart sipInstance) { if (bindings != null) for (int i = 0; i < bindings.Length; i++) if (bindings[i] != null && bindings[i].SipInstance == sipInstance) return i; return -1; } private int AddBinding() { for (int i = 0; i < bindings.Length; i++) if (bindings[i] == null) return i; int length = bindings.Length; Array.Resize<Binding>(ref bindings, length + 1); return length; } private Binding FindBinding(ByteArrayPart addrSpec) { int index = FindBindingByAddrSpec(addrSpec); return (index < 0) ? null : bindings[index]; } private void RemoveBinding(int index, Action<Bindings, Binding> onRemoveBinding) { var binding = bindings[index]; bindings[index] = null; onRemoveBinding(this, binding); } private void AddBinding(Binding binding, Action<Bindings, Binding, SipMessageReader> onAddBinding, SipMessageReader param) { int index = AddBinding(); bindings[index] = binding; onAddBinding(this, binding, param); isNew = false; } #endregion } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Baseline; using Marten.Events.Projections; using Marten.Schema; using Marten.Storage; namespace Marten.Events { public enum StreamIdentity { AsGuid, AsString } public class EventGraph : IFeatureSchema { private readonly ConcurrentDictionary<string, IAggregator> _aggregateByName = new ConcurrentDictionary<string, IAggregator>(); private readonly ConcurrentDictionary<Type, IAggregator> _aggregates = new ConcurrentDictionary<Type, IAggregator>(); private readonly ConcurrentCache<string, EventMapping> _byEventName = new ConcurrentCache<string, EventMapping>(); private readonly ConcurrentCache<Type, EventMapping> _events = new ConcurrentCache<Type, EventMapping>(); private IAggregatorLookup _aggregatorLookup; private string _databaseSchemaName; public EventGraph(StoreOptions options) { Options = options; _aggregatorLookup = new AggregatorLookup(); _events.OnMissing = eventType => { var mapping = typeof(EventMapping<>).CloseAndBuildAs<EventMapping>(this, eventType); Options.Storage.AddMapping(mapping); return mapping; }; _byEventName.OnMissing = name => { return AllEvents().FirstOrDefault(x => x.EventTypeName == name); }; InlineProjections = new ProjectionCollection(options); AsyncProjections = new ProjectionCollection(options); } public StreamIdentity StreamIdentity { get; set; } = StreamIdentity.AsGuid; internal StoreOptions Options { get; } internal DbObjectName Table => new DbObjectName(DatabaseSchemaName, "mt_events"); public EventMapping EventMappingFor(Type eventType) { return _events[eventType]; } public EventMapping EventMappingFor<T>() where T : class, new() { return EventMappingFor(typeof(T)); } public IEnumerable<EventMapping> AllEvents() { return _events; } public IEnumerable<IAggregator> AllAggregates() { return _aggregates.Values; } public EventMapping EventMappingFor(string eventType) { return _byEventName[eventType]; } public void AddEventType(Type eventType) { _events.FillDefault(eventType); } public void AddEventTypes(IEnumerable<Type> types) { types.Each(AddEventType); } public bool IsActive(StoreOptions options) => _events.Any() || _aggregates.Any(); public string DatabaseSchemaName { get { return _databaseSchemaName ?? Options.DatabaseSchemaName; } set { _databaseSchemaName = value; } } public void AddAggregator<T>(IAggregator<T> aggregator) where T : class, new() { Options.Storage.MappingFor(typeof(T)); _aggregates.AddOrUpdate(typeof(T), aggregator, (type, previous) => aggregator); } public IAggregator<T> AggregateFor<T>() where T : class, new() { return _aggregates .GetOrAdd(typeof(T), type => { Options.Storage.MappingFor(typeof(T)); return _aggregatorLookup.Lookup<T>(); }) .As<IAggregator<T>>(); } public Type AggregateTypeFor(string aggregateTypeName) { if (_aggregateByName.ContainsKey(aggregateTypeName)) { return _aggregateByName[aggregateTypeName].AggregateType; } var aggregate = AllAggregates().FirstOrDefault(x => x.Alias == aggregateTypeName); if (aggregate == null) { return null; } return _aggregateByName.GetOrAdd(aggregateTypeName, name => { return AllAggregates().FirstOrDefault(x => x.Alias == name); }).AggregateType; } public ProjectionCollection InlineProjections { get; } public ProjectionCollection AsyncProjections { get; } internal DbObjectName ProgressionTable => new DbObjectName(DatabaseSchemaName, "mt_event_progression"); public string AggregateAliasFor(Type aggregateType) { return _aggregates .GetOrAdd(aggregateType, type => _aggregatorLookup.Lookup(type)).Alias; } public IProjection ProjectionFor(Type viewType) { return AsyncProjections.ForView(viewType) ?? InlineProjections.ForView(viewType); } public ViewProjection<TView, TId> ProjectView<TView, TId>() where TView : class, new() { var projection = new ViewProjection<TView, TId>(); InlineProjections.Add(projection); return projection; } /// <summary> /// Set default strategy to lookup IAggregator when no explicit IAggregator registration exists. /// </summary> /// <remarks>Unless called, <see cref="AggregatorLookup"/> is used</remarks> public void UseAggregatorLookup(IAggregatorLookup aggregatorLookup) { _aggregatorLookup = aggregatorLookup; } IEnumerable<Type> IFeatureSchema.DependentTypes() { yield break; } ISchemaObject[] IFeatureSchema.Objects { get { var eventsTable = new EventsTable(this); var sequence = new Sequence(new DbObjectName(DatabaseSchemaName, "mt_events_sequence")) { Owner = eventsTable.Identifier, OwnerColumn = "seq_id" }; return new ISchemaObject[] { new StreamsTable(this), eventsTable, new EventProgressionTable(DatabaseSchemaName), sequence, new AppendEventFunction(this), new SystemFunction(DatabaseSchemaName, "mt_mark_event_progression", "varchar, bigint"), }; } } Type IFeatureSchema.StorageType => typeof(EventGraph); public string Identifier { get; } = "eventstore"; public void WritePermissions(DdlRules rules, StringWriter writer) { // Nothing } internal string GetStreamIdType() { return StreamIdentity == StreamIdentity.AsGuid ? "uuid" : "varchar"; } private readonly ConcurrentDictionary<Type, string> _dotnetTypeNames = new ConcurrentDictionary<Type, string>(); internal string DotnetTypeNameFor(Type type) { if (!_dotnetTypeNames.ContainsKey(type)) { _dotnetTypeNames[type] = $"{type.FullName}, {type.GetTypeInfo().Assembly.GetName().Name}"; } return _dotnetTypeNames[type]; } private readonly ConcurrentDictionary<string, Type> _nameToType = new ConcurrentDictionary<string, Type>(); internal Type TypeForDotNetName(string assemblyQualifiedName) { if (!_nameToType.ContainsKey(assemblyQualifiedName)) { _nameToType[assemblyQualifiedName] = Type.GetType(assemblyQualifiedName); } return _nameToType[assemblyQualifiedName]; } } }
// Copyright 2008 Adrian Akison // Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx using System; using System.Collections.Generic; using System.Text; namespace MCEBuddy.Util.Combinatorics { /// <summary> /// Combinations defines a meta-collection, typically a list of lists, of all possible /// subsets of a particular size from the set of values. This list is enumerable and /// allows the scanning of all possible combinations using a simple foreach() loop. /// Within the returned set, there is no prescribed order. This follows the mathematical /// concept of choose. For example, put 10 dominoes in a hat and pick 5. The number of possible /// combinations is defined as "10 choose 5", which is calculated as (10!) / ((10 - 5)! * 5!). /// </summary> /// <remarks> /// The MetaCollectionType parameter of the constructor allows for the creation of /// two types of sets, those with and without repetition in the output set when /// presented with repetition in the input set. /// /// When given a input collect {A B C} and lower index of 2, the following sets are generated: /// MetaCollectionType.WithRepetition => /// {A A}, {A B}, {A C}, {B B}, {B C}, {C C} /// MetaCollectionType.WithoutRepetition => /// {A B}, {A C}, {B C} /// /// Input sets with multiple equal values will generate redundant combinations in proprotion /// to the likelyhood of outcome. For example, {A A B B} and a lower index of 3 will generate: /// {A A B} {A A B} {A B B} {A B B} /// </remarks> /// <typeparam name="T">The type of the values within the list.</typeparam> public class Combinations<T> : IMetaCollection<T> { #region Constructors /// <summary> /// No default constructor, must provided a list of values and size. /// </summary> protected Combinations() { ; } /// <summary> /// Create a combination set from the provided list of values. /// The upper index is calculated as values.Count, the lower index is specified. /// Collection type defaults to MetaCollectionType.WithoutRepetition /// </summary> /// <param name="values">List of values to select combinations from.</param> /// <param name="lowerIndex">The size of each combination set to return.</param> public Combinations(IList<T> values, int lowerIndex) { Initialize(values, lowerIndex, GenerateOption.WithoutRepetition); } /// <summary> /// Create a combination set from the provided list of values. /// The upper index is calculated as values.Count, the lower index is specified. /// </summary> /// <param name="values">List of values to select combinations from.</param> /// <param name="lowerIndex">The size of each combination set to return.</param> /// <param name="type">The type of Combinations set to generate.</param> public Combinations(IList<T> values, int lowerIndex, GenerateOption type) { Initialize(values, lowerIndex, type); } #endregion #region IEnumerable Interface /// <summary> /// Gets an enumerator for collecting the list of combinations. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<IList<T>> GetEnumerator() { return new Enumerator(this); } /// <summary> /// Gets an enumerator for collecting the list of combinations. /// </summary> /// <returns>The enumerator.returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } #endregion #region Enumerator Inner Class /// <summary> /// The enumerator that enumerates each meta-collection of the enclosing Combinations class. /// </summary> public class Enumerator : IEnumerator<IList<T>> { #region Constructors /// <summary> /// Construct a enumerator with the parent object. /// </summary> /// <param name="source">The source combinations object.</param> public Enumerator(Combinations<T> source) { myParent = source; myPermutationsEnumerator = (Permutations<bool>.Enumerator)myParent.myPermutations.GetEnumerator(); } #endregion #region IEnumerator interface /// <summary> /// Resets the combinations enumerator to the first combination. /// </summary> public void Reset() { myPermutationsEnumerator.Reset(); } /// <summary> /// Advances to the next combination of items from the set. /// </summary> /// <returns>True if successfully moved to next combination, False if no more unique combinations exist.</returns> /// <remarks> /// The heavy lifting is done by the permutations object, the combination is generated /// by creating a new list of those items that have a true in the permutation parrellel array. /// </remarks> public bool MoveNext() { bool ret = myPermutationsEnumerator.MoveNext(); myCurrentList = null; return ret; } /// <summary> /// The current combination /// </summary> public IList<T> Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// The current combination /// </summary> object System.Collections.IEnumerator.Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// Cleans up non-managed resources, of which there are none used here. /// </summary> public void Dispose() { ; } #endregion #region Heavy Lifting Members /// <summary> /// The only complex function of this entire wrapper, ComputeCurrent() creates /// a list of original values from the bool permutation provided. /// The exception for accessing current (InvalidOperationException) is generated /// by the call to .Current on the underlying enumeration. /// </summary> /// <remarks> /// To compute the current list of values, the underlying permutation object /// which moves with this enumerator, is scanned differently based on the type. /// The items have only two values, true and false, which have different meanings: /// /// For type WithoutRepetition, the output is a straightforward subset of the input array. /// E.g. 6 choose 3 without repetition /// Input array: {A B C D E F} /// Permutations: {0 1 0 0 1 1} /// Generates set: {A C D } /// Note: size of permutation is equal to upper index. /// /// For type WithRepetition, the output is defined by runs of characters and when to /// move to the next element. /// E.g. 6 choose 5 with repetition /// Input array: {A B C D E F} /// Permutations: {0 1 0 0 1 1 0 0 1 1} /// Generates set: {A B B D D } /// Note: size of permutation is equal to upper index - 1 + lower index. /// </remarks> private void ComputeCurrent() { if(myCurrentList == null) { myCurrentList = new List<T>(); int index = 0; IList<bool> currentPermutation = (IList<bool>)myPermutationsEnumerator.Current; for(int i = 0; i < currentPermutation.Count; ++i) { if(currentPermutation[i] == false) { myCurrentList.Add(myParent.myValues[index]); if(myParent.Type == GenerateOption.WithoutRepetition) { ++index; } } else { ++index; } } } } #endregion #region Data /// <summary> /// Parent object this is an enumerator for. /// </summary> private Combinations<T> myParent; /// <summary> /// The current list of values, this is lazy evaluated by the Current property. /// </summary> private List<T> myCurrentList; /// <summary> /// An enumertor of the parents list of lexicographic orderings. /// </summary> private Permutations<bool>.Enumerator myPermutationsEnumerator; #endregion } #endregion #region IMetaList Interface /// <summary> /// The number of unique combinations that are defined in this meta-collection. /// This value is mathematically defined as Choose(M, N) where M is the set size /// and N is the subset size. This is M! / (N! * (M-N)!). /// </summary> public long Count { get { return myPermutations.Count; } } /// <summary> /// The type of Combinations set that is generated. /// </summary> public GenerateOption Type { get { return myMetaCollectionType; } } /// <summary> /// The upper index of the meta-collection, equal to the number of items in the initial set. /// </summary> public int UpperIndex { get { return myValues.Count; } } /// <summary> /// The lower index of the meta-collection, equal to the number of items returned each iteration. /// </summary> public int LowerIndex { get { return myLowerIndex; } } #endregion #region Heavy Lifting Members /// <summary> /// Initialize the combinations by settings a copy of the values from the /// </summary> /// <param name="values">List of values to select combinations from.</param> /// <param name="lowerIndex">The size of each combination set to return.</param> /// <param name="type">The type of Combinations set to generate.</param> /// <remarks> /// Copies the array and parameters and then creates a map of booleans that will /// be used by a permutations object to refence the subset. This map is slightly /// different based on whether the type is with or without repetition. /// /// When the type is WithoutRepetition, then a map of upper index elements is /// created with lower index false's. /// E.g. 8 choose 3 generates: /// Map: {1 1 1 1 1 0 0 0} /// Note: For sorting reasons, false denotes inclusion in output. /// /// When the type is WithRepetition, then a map of upper index - 1 + lower index /// elements is created with the falses indicating that the 'current' element should /// be included and the trues meaning to advance the 'current' element by one. /// E.g. 8 choose 3 generates: /// Map: {1 1 1 1 1 1 1 1 0 0 0} (7 trues, 3 falses). /// </remarks> private void Initialize(IList<T> values, int lowerIndex, GenerateOption type) { myMetaCollectionType = type; myLowerIndex = lowerIndex; myValues = new List<T>(); myValues.AddRange(values); List<bool> myMap = new List<bool>(); if(type == GenerateOption.WithoutRepetition) { for(int i = 0; i < myValues.Count; ++i) { if(i >= myValues.Count - myLowerIndex) { myMap.Add(false); } else { myMap.Add(true); } } } else { for(int i = 0; i < values.Count - 1; ++i) { myMap.Add(true); } for(int i = 0; i < myLowerIndex; ++i) { myMap.Add(false); } } myPermutations = new Permutations<bool>(myMap); } #endregion #region Data /// <summary> /// Copy of values object is intialized with, required for enumerator reset. /// </summary> private List<T> myValues; /// <summary> /// Permutations object that handles permutations on booleans for combination inclusion. /// </summary> private Permutations<bool> myPermutations; /// <summary> /// The type of the combination collection. /// </summary> private GenerateOption myMetaCollectionType; /// <summary> /// The lower index defined in the constructor. /// </summary> private int myLowerIndex; #endregion } }
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Signum.Utilities.ExpressionTrees { /// <summary> /// Implementation of SimpleExpressionVisitor that does the replacement /// * MethodExpanderAttribute /// * MemberXXXExpression static field /// * ExpressionExtensions.Evaluate method /// /// It also simplifies and skip evaluating short circuited subexpresions /// Evaluates constant subexpressions /// </summary> public class ExpressionCleaner : ExpressionVisitor { Func<Expression, Expression> partialEval; bool shortCircuit; public ExpressionCleaner(Func<Expression, Expression> partialEval, bool shortCircuit) { this.partialEval = partialEval; this.shortCircuit = shortCircuit; } public static Expression? Clean(Expression? expr) { return Clean(expr, ExpressionEvaluator.PartialEval, true); } public static Expression? Clean(Expression? expr, Func<Expression, Expression> partialEval, bool shortCircuit) { ExpressionCleaner ee = new ExpressionCleaner(partialEval, shortCircuit); var result = ee.Visit(expr); return partialEval(result); } protected override Expression VisitInvocation(InvocationExpression iv) { if (iv.Expression is LambdaExpression) return Visit(ExpressionReplacer.Replace(iv)); else return base.VisitInvocation(iv); //Just calling a delegate in the projector } protected override Expression VisitMethodCall(MethodCallExpression m) { MethodCallExpression expr = (MethodCallExpression)base.VisitMethodCall(m); Expression? binded = BindMethodExpression(expr, false); if (binded != null) return Visit(binded); return expr; } public static Expression? BindMethodExpression(MethodCallExpression m, bool allowPolymorphics) { if (m.Method.DeclaringType == typeof(ExpressionExtensions) && m.Method.Name == "Evaluate") { LambdaExpression lambda = (LambdaExpression)ExpressionEvaluator.Eval(m.Arguments[0])!; return Expression.Invoke(lambda, m.Arguments.Skip(1).ToArray()); } if (m.Method.HasAttributeInherit<PolymorphicExpansionAttribute>() && !allowPolymorphics) return null; MethodExpanderAttribute? attribute = m.Method.GetCustomAttribute<MethodExpanderAttribute>(); if (attribute != null) { if (attribute.ExpanderType.IsGenericTypeDefinition) { if (!typeof(GenericMethodExpander).IsAssignableFrom(attribute.ExpanderType)) throw new InvalidOperationException("Expansion failed, '{0}' does not implement IMethodExpander or GenericMethodExpander".FormatWith(attribute.ExpanderType.TypeName())); Expression[] args = m.Object == null ? m.Arguments.ToArray() : m.Arguments.PreAnd(m.Object).ToArray(); var type = attribute.ExpanderType.MakeGenericType(m.Method.GetGenericArguments()); GenericMethodExpander expander = (GenericMethodExpander)Activator.CreateInstance(type)!; return Expression.Invoke(expander.GenericLambdaExpression, args); } else { if(!typeof(IMethodExpander).IsAssignableFrom(attribute.ExpanderType)) throw new InvalidOperationException("Expansion failed, '{0}' does not implement IMethodExpander or GenericMethodExpander".FormatWith(attribute.ExpanderType.TypeName())); IMethodExpander expander = (IMethodExpander)Activator.CreateInstance(attribute.ExpanderType)!; Expression exp = expander.Expand( m.Object, m.Arguments.ToArray(), m.Method); return exp; } } LambdaExpression? lambdaExpression = GetFieldExpansion(m.Object?.Type, m.Method); if (lambdaExpression != null) { Expression[] args = m.Object == null ? m.Arguments.ToArray() : m.Arguments.PreAnd(m.Object).ToArray(); return Expression.Invoke(lambdaExpression, args); } return null; } protected override Expression VisitMember(MemberExpression m) { MemberExpression exp = (MemberExpression)base.VisitMember(m); Expression? binded = BindMemberExpression(exp, false); if (binded != null) return Visit(binded); return exp; } public static Expression? BindMemberExpression(MemberExpression m, bool allowPolymorphics) { PropertyInfo? pi = m.Member as PropertyInfo; if (pi == null) return null; if (pi.HasAttributeInherit<PolymorphicExpansionAttribute>() && !allowPolymorphics) return null; LambdaExpression? lambda = GetFieldExpansion(m.Expression?.Type, pi); if (lambda == null) return null; if (m.Expression == null) return lambda.Body; else return Expression.Invoke(lambda, m.Expression); } public static bool HasExpansions(Type type, MemberInfo mi) { return GetFieldExpansion(type, mi) != null || mi is MethodInfo && mi.HasAttribute<MethodExpanderAttribute>(); } public static LambdaExpression? GetFieldExpansion(Type? decType, MemberInfo mi) { if (decType == null || decType == mi.DeclaringType || IsStatic(mi)) return GetExpansion(mi); else { for (MemberInfo? m = GetMember(decType, mi); m != null; m = BaseMember(m)) { var result = GetExpansion(m); if (result != null) return result; } return null; } } static bool IsStatic(MemberInfo mi) { if (mi is MethodInfo mti) return mti.IsStatic; if (mi is PropertyInfo pi) return (pi.GetGetMethod() ?? pi.GetSetMethod())!.IsStatic; return false; } static LambdaExpression? GetExpansion(MemberInfo mi) { ExpressionFieldAttribute? efa = mi.GetCustomAttribute<ExpressionFieldAttribute>(); if (efa == null) return null; if (efa.Name == "auto") throw new InvalidOperationException($"The {nameof(ExpressionFieldAttribute)} for {mi.DeclaringType!.TypeName()}.{mi.MemberName()} has the default value 'auto'.\r\nMaybe Signum.MSBuildTask is not running in assemby {mi.DeclaringType!.Assembly.GetName().Name}?"); Type type = mi.DeclaringType!; FieldInfo? fi = type.GetField(efa.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (fi == null) throw new InvalidOperationException("Expression field '{0}' not found on '{1}'".FormatWith(efa.Name, type.TypeName())); var obj = fi.GetValue(null); if (obj == null) throw new InvalidOperationException("Expression field '{0}' is null".FormatWith(efa.Name)); if (!(obj is LambdaExpression result)) throw new InvalidOperationException("Expression field '{0}' does not contain a lambda expression".FormatWith(efa.Name, type.TypeName())); return result; } static readonly BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; static MemberInfo? GetMember(Type decType, MemberInfo mi) { if (mi is MethodInfo) { Type[] types = ((MethodInfo)mi).GetParameters().Select(a => a.ParameterType).ToArray(); var result = decType.GetMethod(mi.Name, flags, null, types, null); if (result != null) return result; if (mi.DeclaringType!.IsInterface) return decType.GetMethod(mi.DeclaringType.FullName + "." + mi.Name, flags, null, types, null); return null; } if (mi is PropertyInfo pi) { Type[] types = pi.GetIndexParameters().Select(a => a.ParameterType).ToArray(); var result = decType.GetProperty(mi.Name, flags, null, pi.PropertyType, types, null) ; if (result != null) return result; if(mi.DeclaringType!.IsInterface) return decType.GetProperty(mi.DeclaringType.FullName + "." + mi.Name, flags, null, pi.PropertyType, types, null); return null; } throw new InvalidOperationException("Invalid Member type"); } static MemberInfo? BaseMember(MemberInfo mi) { MemberInfo? result; if (mi is MethodInfo mti) result = mti.GetBaseDefinition(); else if (mi is PropertyInfo pi) result = pi.GetBaseDefinition(); else throw new InvalidOperationException("Invalid Member type"); if (result == mi) return null; return result; } #region Simplifier bool GetBool(Expression exp) { return (bool)((ConstantExpression)exp).Value; } protected override Expression VisitBinary(BinaryExpression b) { if (!shortCircuit) return base.VisitBinary(b); if (b.NodeType == ExpressionType.Coalesce) { Expression left = partialEval(this.Visit(b.Left)); if (left.NodeType == ExpressionType.Constant) { var ce = (ConstantExpression)left; if (ce.Value == null) return Visit(b.Right); if (ce.Type.IsNullable()) return Expression.Constant(ce.Value, ce.Type.UnNullify()); else return ce; } Expression right = this.Visit(b.Right); Expression conversion = this.Visit(b.Conversion); return Expression.Coalesce(left, right, conversion as LambdaExpression); } if (b.Type != typeof(bool)) return base.VisitBinary(b); if (b.NodeType == ExpressionType.And || b.NodeType == ExpressionType.AndAlso) { Expression left = partialEval(this.Visit(b.Left)); if (left.NodeType == ExpressionType.Constant) return GetBool(left) ? Visit(b.Right) : Expression.Constant(false); Expression right = partialEval(this.Visit(b.Right)); if (right.NodeType == ExpressionType.Constant) return GetBool(right) ? left : Expression.Constant(false); return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } else if (b.NodeType == ExpressionType.Or || b.NodeType == ExpressionType.OrElse) { Expression left = partialEval(this.Visit(b.Left)); if (left.NodeType == ExpressionType.Constant) return GetBool(left) ? Expression.Constant(true) : Visit(b.Right); Expression right = partialEval(this.Visit(b.Right)); if (right.NodeType == ExpressionType.Constant) return GetBool(right) ? Expression.Constant(true) : left; return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } // rel == 'a' is compiled as (int)rel == 123 if(b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual) { { if (IsConvertCharToInt(b.Left) is Expression l && IsConvertCharToIntOrConstant(b.Right) is Expression r) return Expression.MakeBinary(b.NodeType, Visit(l), Visit(r)); } { if (IsConvertCharToIntOrConstant(b.Left) is Expression l && IsConvertCharToInt(b.Right) is Expression r) return Expression.MakeBinary(b.NodeType, Visit(l), Visit(r)); } } if (b.Left.Type != typeof(bool)) return base.VisitBinary(b); if (b.NodeType == ExpressionType.Equal) { Expression left = partialEval(this.Visit(b.Left)); if (left.NodeType == ExpressionType.Constant) return GetBool(left) ? Visit(b.Right) : Visit(Expression.Not(b.Right)); Expression right = partialEval(this.Visit(b.Right)); if (right.NodeType == ExpressionType.Constant) return GetBool(right) ? left : Expression.Not(left); return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } else if (b.NodeType == ExpressionType.NotEqual) { Expression left = partialEval(this.Visit(b.Left)); if (left.NodeType == ExpressionType.Constant) return GetBool(left) ? Visit(Expression.Not(b.Right)) : Visit(b.Right); Expression right = partialEval(this.Visit(b.Right)); if (right.NodeType == ExpressionType.Constant) return GetBool(right) ? Expression.Not(left) : left; return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } return base.VisitBinary(b); } static Expression? IsConvertCharToInt(Expression exp) { if (exp is UnaryExpression ue && ue.NodeType == ExpressionType.Convert && ue.Operand.Type == typeof(char)) { return ue.Operand; } return null; } static Expression? IsConvertCharToIntOrConstant(Expression exp) { var result = IsConvertCharToInt(exp); if (result != null) return result; if (exp is ConstantExpression ceInt && ceInt.Type == typeof(int)) return Expression.Constant((char)(int)ceInt.Value, typeof(char)); if (exp is ConstantExpression ceChar && ceChar.Type == typeof(char)) return ceChar; return null; } protected override Expression VisitConditional(ConditionalExpression c) { if (!shortCircuit) return base.VisitConditional(c); Expression test = partialEval(this.Visit(c.Test)); if (test.NodeType == ExpressionType.Constant) { if (GetBool(test)) return this.Visit(c.IfTrue); else return this.Visit(c.IfFalse); } Expression ifTrue = this.Visit(c.IfTrue); Expression ifFalse = this.Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Parameters supplied to the Update Virtual Machine Image operation. /// </summary> public partial class VirtualMachineVMImageUpdateParameters { private IList<DataDiskConfigurationUpdateParameters> _dataDiskConfigurations; /// <summary> /// Optional. Optional. The Data Disk Configurations. /// </summary> public IList<DataDiskConfigurationUpdateParameters> DataDiskConfigurations { get { return this._dataDiskConfigurations; } set { this._dataDiskConfigurations = value; } } private string _description; /// <summary> /// Optional. Specifies the description of the OS image. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _eula; /// <summary> /// Optional. Specifies the End User License Agreement that is /// associated with the image. The value for this element is a string, /// but it is recommended that the value be a URL that points to a /// EULA. /// </summary> public string Eula { get { return this._eula; } set { this._eula = value; } } private string _iconUri; /// <summary> /// Optional. Specifies the URI to the icon that is displayed for the /// image in the Management Portal. /// </summary> public string IconUri { get { return this._iconUri; } set { this._iconUri = value; } } private string _imageFamily; /// <summary> /// Optional. Specifies a value that can be used to group OS images. /// </summary> public string ImageFamily { get { return this._imageFamily; } set { this._imageFamily = value; } } private string _label; /// <summary> /// Required. Specifies the friendly name of the image to be updated. /// You cannot use this operation to update images provided by the /// Azure platform. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _language; /// <summary> /// Optional. Specifies the language of the image. /// </summary> public string Language { get { return this._language; } set { this._language = value; } } private OSDiskConfigurationUpdateParameters _oSDiskConfiguration; /// <summary> /// Optional. Optional. The OS Disk Configuration. /// </summary> public OSDiskConfigurationUpdateParameters OSDiskConfiguration { get { return this._oSDiskConfiguration; } set { this._oSDiskConfiguration = value; } } private Uri _privacyUri; /// <summary> /// Optional. Specifies the URI that points to a document that contains /// the privacy policy related to the OS image. /// </summary> public Uri PrivacyUri { get { return this._privacyUri; } set { this._privacyUri = value; } } private System.DateTime? _publishedDate; /// <summary> /// Optional. Specifies the date when the OS image was added to the /// image repository. /// </summary> public System.DateTime? PublishedDate { get { return this._publishedDate; } set { this._publishedDate = value; } } private string _recommendedVMSize; /// <summary> /// Optional. Specifies the size to use for the virtual machine that is /// created from the OS image. /// </summary> public string RecommendedVMSize { get { return this._recommendedVMSize; } set { this._recommendedVMSize = value; } } private bool? _showInGui; /// <summary> /// Optional. Optional. True or False. /// </summary> public bool? ShowInGui { get { return this._showInGui; } set { this._showInGui = value; } } private string _smallIconUri; /// <summary> /// Optional. Specifies the URI to the small icon that is displayed /// when the image is presented in the Azure Management Portal. /// </summary> public string SmallIconUri { get { return this._smallIconUri; } set { this._smallIconUri = value; } } /// <summary> /// Initializes a new instance of the /// VirtualMachineVMImageUpdateParameters class. /// </summary> public VirtualMachineVMImageUpdateParameters() { this.DataDiskConfigurations = new LazyList<DataDiskConfigurationUpdateParameters>(); } /// <summary> /// Initializes a new instance of the /// VirtualMachineVMImageUpdateParameters class with required /// arguments. /// </summary> public VirtualMachineVMImageUpdateParameters(string label) : this() { if (label == null) { throw new ArgumentNullException("label"); } this.Label = label; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using AutoMapper; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using System.Collections; using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.New, "AzureRmApplicationGateway", SupportsShouldProcess = true), OutputType(typeof(PSApplicationGateway))] public class NewAzureApplicationGatewayCommand : ApplicationGatewayBaseCmdlet { [Alias("ResourceName")] [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name.")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ValidateNotNullOrEmpty] public virtual string ResourceGroupName { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "location.")] [ValidateNotNullOrEmpty] public virtual string Location { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The SKU of application gateway")] [ValidateNotNullOrEmpty] public virtual PSApplicationGatewaySku Sku { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The SSL policy of application gateway")] public virtual PSApplicationGatewaySslPolicy SslPolicy { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of IPConfiguration (subnet)")] [ValidateNotNullOrEmpty] public List<PSApplicationGatewayIPConfiguration> GatewayIPConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of ssl certificates")] public List<PSApplicationGatewaySslCertificate> SslCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of authentication certificates")] public List<PSApplicationGatewayAuthenticationCertificate> AuthenticationCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of frontend IP config")] public List<PSApplicationGatewayFrontendIPConfiguration> FrontendIPConfigurations { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of frontend port")] public List<PSApplicationGatewayFrontendPort> FrontendPorts { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of probe")] public List<PSApplicationGatewayProbe> Probes { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of backend address pool")] public List<PSApplicationGatewayBackendAddressPool> BackendAddressPools { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of backend http settings")] public List<PSApplicationGatewayBackendHttpSettings> BackendHttpSettingsCollection { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of http listener")] public List<PSApplicationGatewayHttpListener> HttpListeners { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of UrlPathMap")] public List<PSApplicationGatewayUrlPathMap> UrlPathMaps { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of request routing rule")] public List<PSApplicationGatewayRequestRoutingRule> RequestRoutingRules { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of redirect configuration")] public List<PSApplicationGatewayRedirectConfiguration> RedirectConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Firewall configuration")] public virtual PSApplicationGatewayWebApplicationFirewallConfiguration WebApplicationFirewallConfiguration { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, HelpMessage = "Do not ask for confirmation if you want to overrite a resource")] public SwitchParameter Force { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); WriteWarning("The output object type of this cmdlet will be modified in a future release."); var present = this.IsApplicationGatewayPresent(this.ResourceGroupName, this.Name); ConfirmAction( Force.IsPresent, string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResource, Name), Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResourceMessage, Name, () => { var applicationGateway = CreateApplicationGateway(); WriteObject(applicationGateway); }, () => present); } private PSApplicationGateway CreateApplicationGateway() { var applicationGateway = new PSApplicationGateway(); applicationGateway.Name = this.Name; applicationGateway.ResourceGroupName = this.ResourceGroupName; applicationGateway.Location = this.Location; applicationGateway.Sku = this.Sku; if (this.SslPolicy != null) { applicationGateway.SslPolicy = new PSApplicationGatewaySslPolicy(); applicationGateway.SslPolicy = this.SslPolicy; } if (this.GatewayIPConfigurations != null) { applicationGateway.GatewayIPConfigurations = this.GatewayIPConfigurations; } if (this.SslCertificates != null) { applicationGateway.SslCertificates = this.SslCertificates; } if (this.AuthenticationCertificates != null) { applicationGateway.AuthenticationCertificates = this.AuthenticationCertificates; } if (this.FrontendIPConfigurations != null) { applicationGateway.FrontendIPConfigurations = this.FrontendIPConfigurations; } if (this.FrontendPorts != null) { applicationGateway.FrontendPorts = this.FrontendPorts; } if (this.Probes != null) { applicationGateway.Probes = this.Probes; } if (this.BackendAddressPools != null) { applicationGateway.BackendAddressPools = this.BackendAddressPools; } if (this.BackendHttpSettingsCollection != null) { applicationGateway.BackendHttpSettingsCollection = this.BackendHttpSettingsCollection; } if (this.HttpListeners != null) { applicationGateway.HttpListeners = this.HttpListeners; } if (this.UrlPathMaps != null) { applicationGateway.UrlPathMaps = this.UrlPathMaps; } if (this.RequestRoutingRules != null) { applicationGateway.RequestRoutingRules = this.RequestRoutingRules; } if (this.RedirectConfigurations != null) { applicationGateway.RedirectConfigurations = this.RedirectConfigurations; } if (this.WebApplicationFirewallConfiguration != null) { applicationGateway.WebApplicationFirewallConfiguration = this.WebApplicationFirewallConfiguration; } // Normalize the IDs ApplicationGatewayChildResourceHelper.NormalizeChildResourcesId(applicationGateway); // Map to the sdk object var appGwModel = Mapper.Map<MNM.ApplicationGateway>(applicationGateway); appGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true); // Execute the Create ApplicationGateway call this.ApplicationGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, appGwModel); var getApplicationGateway = this.GetApplicationGateway(this.ResourceGroupName, this.Name); return getApplicationGateway; } } }
// // 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; namespace Microsoft.WindowsAzure.Management.WebSites { /// <summary> /// In addition to standard HTTP status codes, the Windows Azure Web Sites /// Management REST API returns extended error codes and error messages. /// The extended codes do not replace the standard HTTP status codes, but /// provide additional, actionable information that can be used in /// conjunction with the standard HTTP status codes. For example, an HTTP /// 404 error can occur for numerous reasons, so having the additional /// information in the extended message can assist with problem /// resolution. (For more information on the standard HTTP codes returned /// by the REST API, see Service Management Status and Error Codes.) (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn166968.aspx for /// more information) /// </summary> public static partial class WebSiteExtendedErrorCodes { /// <summary> /// Access is denied. /// </summary> public const string AccessDenied = "01001"; /// <summary> /// Command resource object is not present in the request body. /// </summary> public const string CommandResourceNotPresent = "01002"; /// <summary> /// Invalid name {0}. /// </summary> public const string InvalidName = "01003"; /// <summary> /// Cannot understand command verb {0}. /// </summary> public const string UnknownCommandVerb = "01004"; /// <summary> /// The service is currently in read only mode. /// </summary> public const string IsInReadOnlyMode = "01005"; /// <summary> /// The {0} parameter is not specified. /// </summary> public const string ParameterIsNotSpecified = "01006"; /// <summary> /// Parameter {0} has invalid value. /// </summary> public const string InvalidParameterValue = "01007"; /// <summary> /// {0} object is not present in the request body. /// </summary> public const string InvalidRequest = "01008"; /// <summary> /// The from value in the query string is bigger than or equal to the /// to value. /// </summary> public const string IncorrectDateTimeRange = "01009"; /// <summary> /// Required parameter {0} is missing. /// </summary> public const string RequiredParameterMissing = "01010"; /// <summary> /// Name of the web quota cannot change. /// </summary> public const string ResourceNameCannotChange = "01011"; /// <summary> /// The value of the query string parameter cannot be converted to /// Boolean. /// </summary> public const string FailedToConvertParameterValue = "01012"; /// <summary> /// Parameter with name {0} already exists in the request. /// </summary> public const string ParameterNameAlreadyExists = "01013"; /// <summary> /// Parameter name cannot be empty. /// </summary> public const string ParameterNameIsEmpty = "01014"; /// <summary> /// Not ready. /// </summary> public const string NotReady = "01015"; /// <summary> /// Ready. /// </summary> public const string Ready = "01016"; /// <summary> /// Update is not allowed for the {0} field. /// </summary> public const string UpdateForFieldNotAllowed = "01017"; /// <summary> /// Web Service does not support Command {0}. Only supported command(s) /// is {1}. /// </summary> public const string NotSupportedCommand = "01018"; /// <summary> /// Invalid data ({0}). /// </summary> public const string InvalidData = "01019"; /// <summary> /// There was a conflict. {0} /// </summary> public const string GenericConflict = "01020"; /// <summary> /// Internal server error occurred. {0} /// </summary> public const string InternalServerError = "01021"; /// <summary> /// Number of sites exceeds the maximum allowed. /// </summary> public const string NumberOfSitesLimit = "03001"; /// <summary> /// NumberOfWorkers exceeds the maximum allowed. /// </summary> public const string NumberOfWorkersLimit = "03002"; /// <summary> /// There is not enough space on the disk. /// </summary> public const string NoStorageVolumeAvailable = "03003"; /// <summary> /// WebSpace with name {0} already exists for subscription {1}. /// </summary> public const string WebSpaceAlreadyExists = "03004"; /// <summary> /// Cannot find webspace {0} for subscription {1} /// </summary> public const string WebSpaceNotFound = "03005"; /// <summary> /// Web space contains resources. /// </summary> public const string WebSpaceContainsResources = "03006"; /// <summary> /// The file storage capacity exceeds the limit. /// </summary> public const string FileStorageLimit = "03007"; /// <summary> /// Failed to delete web space {0}: {1} /// </summary> public const string WebSpaceDeleteError = "03008"; /// <summary> /// Not enough available Standard Instance servers to satisfy this /// request. /// </summary> public const string NoWorkersAvailable = "03009"; /// <summary> /// Failed to create web space {0} on storage volume {1}: {2} /// </summary> public const string WebSpaceCreateError = "03010"; /// <summary> /// Directory already exists for site {0}. /// </summary> public const string DirectoryAlreadyExists = "04001"; /// <summary> /// Failed to delete directory {0}. /// </summary> public const string DirectoryDeleteError = "04002"; /// <summary> /// Invalid host name {0}. /// </summary> public const string InvalidHostName = "04003"; /// <summary> /// NumberOfWorkers value must be more than zero. /// </summary> public const string InvalidNumberOfWorkers = "04004"; /// <summary> /// Hostname '{0}' already exists. /// </summary> public const string HostNameAlreadyExists = "04005"; /// <summary> /// No CNAME pointing from {0} to a site in a default DNS zone (or too /// many). /// </summary> public const string InvalidCustomHostNameValidation = "04006"; /// <summary> /// There are no hostnames which could be used for validation. /// </summary> public const string InvalidCustomHostNameValidationNoBaseHostName = "04007"; /// <summary> /// Site with name {0} already exists. /// </summary> public const string SiteAlreadyExists = "04008"; /// <summary> /// Cannot find site {0}. /// </summary> public const string SiteNotFound = "04009"; /// <summary> /// The external URL "{0}" specified on request header "{1}" is invalid. /// </summary> public const string InvalidExternalUriHeader = "04010"; /// <summary> /// Failed to delete file {0}. /// </summary> public const string FileDeleteError = "04011"; /// <summary> /// Number of workers for this site exceeds the maximum allowed. /// </summary> public const string NumberOfWorkersPerSiteLimit = "04012"; /// <summary> /// WebSiteManager.CreateWebSite: Creating Site using storageVolume {0}. /// </summary> public const string TraceWebSiteStorageVolume = "04013"; /// <summary> /// Cannot delete repository with name {0}. /// </summary> public const string RepositoryDeleteError = "05001"; /// <summary> /// Development site already exists in the repository for site {0}. /// </summary> public const string RepositoryDevSiteAlreadyExists = "05002"; /// <summary> /// Development site does not exist in the repository for site {0}. /// </summary> public const string RepositoryDevSiteNotExist = "05003"; /// <summary> /// Site {0} already has repository created for it. /// </summary> public const string RepositorySiteAlreadyExists = "05004"; /// <summary> /// Repository does not exist for site {0}. /// </summary> public const string RepositorySiteNotExist = "05005"; /// <summary> /// Failed to create a development site. /// </summary> public const string TraceFailedToCreateDevSite = "05006"; /// <summary> /// User {0} has been rejected. /// </summary> public const string AuthenticatedFailed = "06001"; /// <summary> /// User {0} has been successfully authenticated. /// </summary> public const string AuthenticatedPassed = "06002"; /// <summary> /// User {0} has been rejected. /// </summary> public const string AuthorizationFailed = "06003"; /// <summary> /// User {0} has been authorized. /// </summary> public const string AuthorizationPassed = "06004"; /// <summary> /// Publishing credentials have to be trimmed from white characters. /// </summary> public const string PublishingCredentialsNotTrimmed = "06005"; /// <summary> /// Publishing password cannot be empty. /// </summary> public const string PublishingPasswordIsEmpty = "06006"; /// <summary> /// Publishing password must be specified. /// </summary> public const string PublishingPasswordNotSpecified = "06007"; /// <summary> /// Publishing username {0} is already used. Specify a different /// publishing username. /// </summary> public const string PublishingUserNameAlreadyExists = "06008"; /// <summary> /// Publishing user name cannot be empty. /// </summary> public const string PublishingUserNameIsEmpty = "06009"; /// <summary> /// An error occurred when adding the {0} entry: {1} /// </summary> public const string ErrorAdding = "51001"; /// <summary> /// An error occurred when deleting the {0} entry: {1} /// </summary> public const string ErrorDeleting = "51002"; /// <summary> /// An error occurred when updating the {0} entry: {1} /// </summary> public const string ErrorUpdating = "51003"; /// <summary> /// Cannot find {0} with name {1}. /// </summary> public const string CannotFindEntity = "51004"; /// <summary> /// Subscription with specified name already exists. /// </summary> public const string SubscriptionConflict = "52001"; /// <summary> /// Subscripton Name cannot be null or empty. /// </summary> public const string SubscriptionNonEmpty = "52002"; /// <summary> /// Subscription {0} not found. /// </summary> public const string SubscriptionNotFound = "52003"; /// <summary> /// Subscription {0} is Suspended. /// </summary> public const string SubscriptionSuspended = "52004"; /// <summary> /// Subscription contains WebSpaces. /// </summary> public const string NonEmptySubscription = "52005"; /// <summary> /// WebSpace with specified name already exists. /// </summary> public const string WebSpaceConflict = "53001"; /// <summary> /// WebSpace Name cannot be null or empty. /// </summary> public const string WebSpaceNonEmpty = "53002"; /// <summary> /// WebSpace contains web sites. /// </summary> public const string NonEmptyWebSpace = "53003"; /// <summary> /// An Error occurred when picking Stamp for WebSpace {0}. /// </summary> public const string ErrorPickingStamp = "53004"; /// <summary> /// Web site with given name {0} already exists in the specified /// Subscription and Webspace. /// </summary> public const string WebSiteConflict = "54001"; /// <summary> /// WebSiteName cannot be null or empty. /// </summary> public const string WebSiteNonEmpty = "54002"; /// <summary> /// Specified Host Name {0} is already taken by another site. /// </summary> public const string HostNameConflict = "54003"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CTYPES using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Numerics; using System.Reflection.Emit; using System.Runtime.InteropServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using System.Text; namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { /// <summary> /// Meta class for structures. Validates _fields_ on creation, provides factory /// methods for creating instances from addresses and translating to parameters. /// </summary> [PythonType, PythonHidden] public class StructType : PythonType, INativeType { internal Field[] _fields; private int? _size, _alignment, _pack; private static readonly Field[] _emptyFields = new Field[0]; // fields were never initialized before a type was created public StructType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members) : base(context, name, bases, members) { foreach (PythonType pt in ResolutionOrder) { StructType st = pt as StructType; if (st != this && st != null) { st.EnsureFinal(); } if (pt is UnionType ut) { ut.EnsureFinal(); } } if (members.TryGetValue("_pack_", out object pack)) { if (!(pack is int) || ((int)pack < 0)) { throw PythonOps.ValueError("pack must be a non-negative integer"); } _pack = (int)pack; } if (members.TryGetValue("_fields_", out object fields)) { __setattr__(context, "_fields_", fields); } // TODO: _anonymous_ } private StructType(Type underlyingSystemType) : base(underlyingSystemType) { } public static ArrayType/*!*/ operator *(StructType type, int count) { return MakeArrayType(type, count); } public static ArrayType/*!*/ operator *(int count, StructType type) { return MakeArrayType(type, count); } public _Structure from_address(CodeContext/*!*/ context, int address) { return from_address(context, new IntPtr(address)); } public _Structure from_address(CodeContext/*!*/ context, BigInteger address) { return from_address(context, new IntPtr((long)address)); } public _Structure from_address(CodeContext/*!*/ context, IntPtr ptr) { _Structure res = (_Structure)CreateInstance(context); res.SetAddress(ptr); return res; } public _Structure from_buffer(CodeContext/*!*/ context, ArrayModule.array array, int offset=0) { ValidateArraySizes(array, offset, ((INativeType)this).Size); _Structure res = (_Structure)CreateInstance(context); IntPtr addr = array.GetArrayAddress(); res._memHolder = new MemoryHolder(addr.Add(offset), ((INativeType)this).Size); res._memHolder.AddObject("ffffffff", array); return res; } public _Structure from_buffer_copy(CodeContext/*!*/ context, ArrayModule.array array, int offset=0) { ValidateArraySizes(array, offset, ((INativeType)this).Size); _Structure res = (_Structure)CreateInstance(Context.SharedContext); res._memHolder = new MemoryHolder(((INativeType)this).Size); res._memHolder.CopyFrom(array.GetArrayAddress().Add(offset), new IntPtr(((INativeType)this).Size)); GC.KeepAlive(array); return res; } /// <summary> /// Converts an object into a function call parameter. /// /// Structures just return themselves. /// </summary> public object from_param(object obj) { if (!Builtin.isinstance(obj, this)) { throw PythonOps.TypeError("expected {0} instance got {1}", Name, PythonTypeOps.GetName(obj)); } return obj; } public object in_dll(object library, string name) { throw new NotImplementedException("in dll"); } public new virtual void __setattr__(CodeContext/*!*/ context, string name, object value) { if (name == "_fields_") { lock (this) { if (_fields != null) { throw PythonOps.AttributeError("_fields_ is final"); } SetFields(value); } } base.__setattr__(context, name, value); } #region INativeType Members int INativeType.Size { get { EnsureSizeAndAlignment(); return _size.Value; } } int INativeType.Alignment { get { EnsureSizeAndAlignment(); return _alignment.Value; } } object INativeType.GetValue(MemoryHolder/*!*/ owner, object readingFrom, int offset, bool raw) { _Structure res = (_Structure)CreateInstance(this.Context.SharedContext); res._memHolder = owner.GetSubBlock(offset); return res; } object INativeType.SetValue(MemoryHolder/*!*/ address, int offset, object value) { try { return SetValueInternal(address, offset, value); } catch (ArgumentTypeException e) { throw PythonOps.RuntimeError("({0}) <type 'exceptions.TypeError'>: {1}", Name, e.Message); } catch (ArgumentException e) { throw PythonOps.RuntimeError("({0}) <type 'exceptions.ValueError'>: {1}", Name, e.Message); } } internal object SetValueInternal(MemoryHolder address, int offset, object value) { IList<object> init = value as IList<object>; if (init != null) { if (init.Count > _fields.Length) { throw PythonOps.TypeError("too many initializers"); } for (int i = 0; i < init.Count; i++) { _fields[i].SetValue(address, offset, init[i]); } } else { CData data = value as CData; if (data != null) { data._memHolder.CopyTo(address, offset, data.Size); return data._memHolder.EnsureObjects(); } else { throw new NotImplementedException("set value"); } } return null; } Type/*!*/ INativeType.GetNativeType() { EnsureFinal(); return GetMarshalTypeFromSize(_size.Value); } MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { Type argumentType = argIndex.Type; argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CheckCDataType")); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Ldobj, ((INativeType)this).GetNativeType()); return null; } Type/*!*/ INativeType.GetPythonType() { return typeof(object); } void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) { value.Emit(method); EmitCDataCreation(this, method, constantPool, constantPoolArgument); } string INativeType.TypeFormat { get { if (_pack != null || _fields == _emptyFields || _fields == null) { return "B"; } StringBuilder res = new StringBuilder(); res.Append("T{"); foreach (Field f in _fields) { res.Append(f.NativeType.TypeFormat); res.Append(':'); res.Append(f.FieldName); res.Append(':'); } res.Append('}'); return res.ToString(); } } #endregion internal static PythonType MakeSystemType(Type underlyingSystemType) { return PythonType.SetPythonType(underlyingSystemType, new StructType(underlyingSystemType)); } private void SetFields(object fields) { lock (this) { IList<object> list = GetFieldsList(fields); int? bitCount = null; int? curBitCount = null; INativeType lastType = null; List<Field> allFields = GetBaseSizeAlignmentAndFields(out int size, out int alignment); IList<object> anonFields = GetAnonymousFields(this); for (int fieldIndex = 0; fieldIndex < list.Count; fieldIndex++) { object o = list[fieldIndex]; GetFieldInfo(this, o, out string fieldName, out INativeType cdata, out bitCount); int prevSize = UpdateSizeAndAlignment(cdata, bitCount, lastType, ref size, ref alignment, ref curBitCount); Field newField = new Field(fieldName, cdata, prevSize, allFields.Count, bitCount, curBitCount - bitCount); allFields.Add(newField); AddSlot(fieldName, newField); if (anonFields != null && anonFields.Contains(fieldName)) { AddAnonymousFields(this, allFields, cdata, newField); } lastType = cdata; } CheckAnonymousFields(allFields, anonFields); if (bitCount != null) { size += lastType.Size; } _fields = allFields.ToArray(); _size = PythonStruct.Align(size, alignment); _alignment = alignment; } } internal static void CheckAnonymousFields(List<Field> allFields, IList<object> anonFields) { if (anonFields != null) { foreach (string s in anonFields) { bool found = false; foreach (Field f in allFields) { if (f.FieldName == s) { found = true; break; } } if (!found) { throw PythonOps.AttributeError("anonymous field {0} is not defined in this structure", s); } } } } internal static IList<object> GetAnonymousFields(PythonType type) { object anonymous; IList<object> anonFields = null; if (type.TryGetBoundAttr(type.Context.SharedContext, type, "_anonymous_", out anonymous)) { anonFields = anonymous as IList<object>; if (anonFields == null) { throw PythonOps.TypeError("_anonymous_ must be a sequence"); } } return anonFields; } internal static void AddAnonymousFields(PythonType type, List<Field> allFields, INativeType cdata, Field newField) { Field[] childFields; if (cdata is StructType) { childFields = ((StructType)cdata)._fields; } else if (cdata is UnionType) { childFields = ((UnionType)cdata)._fields; } else { throw PythonOps.TypeError("anonymous field must be struct or union"); } foreach (Field existingField in childFields) { Field anonField = new Field( existingField.FieldName, existingField.NativeType, checked(existingField.offset + newField.offset), allFields.Count ); type.AddSlot(existingField.FieldName, anonField); allFields.Add(anonField); } } private List<Field> GetBaseSizeAlignmentAndFields(out int size, out int alignment) { size = 0; alignment = 1; List<Field> allFields = new List<Field>(); INativeType lastType = null; int? totalBitCount = null; foreach (PythonType pt in BaseTypes) { StructType st = pt as StructType; if (st != null) { foreach (Field f in st._fields) { allFields.Add(f); UpdateSizeAndAlignment(f.NativeType, f.BitCount, lastType, ref size, ref alignment, ref totalBitCount); if (f.NativeType == this) { throw StructureCannotContainSelf(); } lastType = f.NativeType; } } } return allFields; } private int UpdateSizeAndAlignment(INativeType cdata, int? bitCount, INativeType lastType, ref int size, ref int alignment, ref int? totalBitCount) { int prevSize = size; if (bitCount != null) { if (lastType != null && lastType.Size != cdata.Size) { totalBitCount = null; prevSize = size += lastType.Size; } size = PythonStruct.Align(size, cdata.Alignment); if (totalBitCount != null) { if ((bitCount + totalBitCount + 7) / 8 <= cdata.Size) { totalBitCount = bitCount + totalBitCount; } else { size += lastType.Size; prevSize = size; totalBitCount = bitCount; } } else { totalBitCount = bitCount; } } else { if (totalBitCount != null) { size += lastType.Size; prevSize = size; totalBitCount = null; } if (_pack != null) { alignment = _pack.Value; prevSize = size = PythonStruct.Align(size, _pack.Value); size += cdata.Size; } else { alignment = Math.Max(alignment, cdata.Alignment); prevSize = size = PythonStruct.Align(size, cdata.Alignment); size += cdata.Size; } } return prevSize; } internal void EnsureFinal() { if (_fields == null) { SetFields(PythonTuple.EMPTY); if (_fields.Length == 0) { // track that we were initialized w/o fields. _fields = _emptyFields; } } } /// <summary> /// If our size/alignment hasn't been initialized then grabs the size/alignment /// from all of our base classes. If later new _fields_ are added we'll be /// initialized and these values will be replaced. /// </summary> private void EnsureSizeAndAlignment() { Debug.Assert(_size.HasValue == _alignment.HasValue); // these are always iniitalized together if (_size == null) { lock (this) { if (_size == null) { int size, alignment; GetBaseSizeAlignmentAndFields(out size, out alignment); _size = size; _alignment = alignment; } } } } } } } #endif
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if NETFRAMEWORK_4_0 using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Security.Principal { // Summary: // Represents a security identifier (SID) and provides marshaling and comparison // operations for SIDs. public sealed class SecurityIdentifier { // Summary: // Returns the maximum size, in bytes, of the binary representation of the security // identifier. // // Returns: // The maximum size, in bytes, of the binary representation of the security // identifier. public static readonly int MaxBinaryLength; // // Summary: // Returns the minimum size, in bytes, of the binary representation of the security // identifier. // // Returns: // The minimum size, in bytes, of the binary representation of the security // identifier. public static readonly int MinBinaryLength; // Summary: // Initializes a new instance of the System.Security.Principal.SecurityIdentifier // class by using an integer that represents the binary form of a security identifier // (SID). // // Parameters: // binaryForm: // An integer that represents the binary form of a SID. public SecurityIdentifier(IntPtr binaryForm) { } // // Summary: // Initializes a new instance of the System.Security.Principal.SecurityIdentifier // class by using the specified security identifier (SID) in Security Descriptor // Definition Language (SDDL) format. // // Parameters: // sddlForm: // SDDL string for the SID used to created the System.Security.Principal.SecurityIdentifier // object. public SecurityIdentifier(string sddlForm) { Contract.Requires(sddlForm != null); } // // Summary: // Initializes a new instance of the System.Security.Principal.SecurityIdentifier // class by using a specified binary representation of a security identifier // (SID). // // Parameters: // binaryForm: // The byte array that represents the SID. // // offset: // The byte offset to use as the starting index in binaryForm. public SecurityIdentifier(byte[] binaryForm, int offset) { Contract.Requires(binaryForm != null); Contract.Requires(offset >= 0); Contract.Requires((binaryForm.Length - offset) >= MinBinaryLength); Contract.Requires(offset < binaryForm.Length); // This is implied by the other two, as MinBinaryLength >= 0 } // // Summary: // Initializes a new instance of the System.Security.Principal.SecurityIdentifier // class by using the specified well known security identifier (SID) type and // domain SID. // // Parameters: // sidType: // A System.Security.Principal.WellKnownSidType value.This value must not be // System.Security.Principal.WellKnownSidType.WinLogonIdsSid. // // domainSid: // The domain SID. This value is required for the following System.Security.Principal.WellKnownSidType // values. This parameter is ignored for any other System.Security.Principal.WellKnownSidType // values.System.Security.Principal.WellKnownSidType.WinAccountAdministratorSidSystem.Security.Principal.WellKnownSidType.WinAccountGuestSidSystem.Security.Principal.WellKnownSidType.WinAccountKrbtgtSidSystem.Security.Principal.WellKnownSidType.WinAccountDomainAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountDomainUsersSidSystem.Security.Principal.WellKnownSidType.WinAccountDomainGuestsSidSystem.Security.Principal.WellKnownSidType.WinAccountComputersSidSystem.Security.Principal.WellKnownSidType.WinAccountControllersSidSystem.Security.Principal.WellKnownSidType.WinAccountCertAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountSchemaAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountEnterpriseAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountPolicyAdminsSidSystem.Security.Principal.WellKnownSidType.WinAccountRasAndIasServersSid public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid) { Contract.Requires(sidType != WellKnownSidType.LogonIdsSid); Contract.Requires(sidType >= WellKnownSidType.NullSid); Contract.Requires(sidType <= WellKnownSidType.WinBuiltinTerminalServerLicenseServersSid); } // Summary: // Compares two System.Security.Principal.SecurityIdentifier objects to determine // whether they are not equal. They are considered not equal if they have different // canonical name representations than the one returned by the System.Security.Principal.SecurityIdentifier.Value // property or if one of the objects is null and the other is not. // // Parameters: // left: // The left System.Security.Principal.SecurityIdentifier operand to use for // the inequality comparison. This parameter can be null. // // right: // The right System.Security.Principal.SecurityIdentifier operand to use for // the inequality comparison. This parameter can be null. // // Returns: // true if left and right are not equal; otherwise, false. extern public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right); // // Summary: // Compares two System.Security.Principal.SecurityIdentifier objects to determine // whether they are equal. They are considered equal if they have the same canonical // representation as the one returned by the System.Security.Principal.SecurityIdentifier.Value // property or if they are both null. // // Parameters: // left: // The left System.Security.Principal.SecurityIdentifier operand to use for // the equality comparison. This parameter can be null. // // right: // The right System.Security.Principal.SecurityIdentifier operand to use for // the equality comparison. This parameter can be null. // // Returns: // true if left and right are equal; otherwise, false. extern public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right); // Summary: // Returns the account domain security identifier (SID) portion from the SID // represented by the System.Security.Principal.SecurityIdentifier object if // the SID represents a Windows account SID. If the SID does not represent a // Windows account SID, this property returns System.ArgumentNullException. // // Returns: // The account domain SID portion from the SID represented by the System.Security.Principal.SecurityIdentifier // object if the SID represents a Windows account SID; otherwise, it returns // System.ArgumentNullException. // It can return null extern public SecurityIdentifier AccountDomainSid { get; } // // Summary: // Returns the length, in bytes, of the security identifier (SID) represented // by the System.Security.Principal.SecurityIdentifier object. // // Returns: // The length, in bytes, of the SID represented by the System.Security.Principal.SecurityIdentifier // object. public int BinaryLength { get { Contract.Ensures(Contract.Result<int>() > 0); Contract.Ensures(Contract.Result<int>() >= MinBinaryLength); Contract.Ensures(Contract.Result<int>() <= MaxBinaryLength); return default(int); } } // Summary: // Compares the current System.Security.Principal.SecurityIdentifier object // with the specified System.Security.Principal.SecurityIdentifier object. // // Parameters: // sid: // The System.Security.Principal.SecurityIdentifier object with which to compare // the current System.Security.Principal.SecurityIdentifier object. // // Returns: // A signed number indicating the relative values of this instance and sid.Return // Value Description Less than zero This instance is less than sid. Zero This // instance is equal to sid. Greater than zero This instance is greater than // sid. // public int CompareTo(SecurityIdentifier sid); // // Summary: // Indicates whether the specified System.Security.Principal.SecurityIdentifier // object is equal to the current System.Security.Principal.SecurityIdentifier // object. // // Parameters: // sid: // The System.Security.Principal.SecurityIdentifier object to compare. // // Returns: // true if the value of sid is equal to the value of the current System.Security.Principal.SecurityIdentifier // object. extern public bool Equals(SecurityIdentifier sid); // // Summary: // Copies the binary representation of the specified security identifier (SID) // represented by the System.Security.Principal.SecurityIdentifier class to // a byte array. // // Parameters: // binaryForm: // The byte array to receive the copied SID. // // offset: // The byte offset to use as the starting index in binaryForm. public void GetBinaryForm(byte[] binaryForm, int offset) { Contract.Requires(binaryForm != null); Contract.Requires(binaryForm.Rank == 1); Contract.Requires(offset >= 0); } // // Summary: // Returns a value that indicates whether the security identifier (SID) represented // by this System.Security.Principal.SecurityIdentifier object is a valid Windows // account SID. // // Returns: // true if the SID represented by this System.Security.Principal.SecurityIdentifier // object is a valid Windows account SID; otherwise, false. extern public bool IsAccountSid(); // // Summary: // Returns a value that indicates whether the security identifier (SID) represented // by this System.Security.Principal.SecurityIdentifier object is from the same // domain as the specified SID. // // Parameters: // sid: // The SID to compare with this System.Security.Principal.SecurityIdentifier // object. // // Returns: // true if the SID represented by this System.Security.Principal.SecurityIdentifier // object is in the same domain as the sid SID; otherwise, false. extern public bool IsEqualDomainSid(SecurityIdentifier sid); // // Summary: // Returns a value that indicates whether the System.Security.Principal.SecurityIdentifier // object matches the specified well known security identifier (SID) type. // // Parameters: // type: // A System.Security.Principal.WellKnownSidType value to compare with the System.Security.Principal.SecurityIdentifier // object. // // Returns: // true if type is the SID type for the System.Security.Principal.SecurityIdentifier // object; otherwise, false. extern public bool IsWellKnown(WellKnownSidType type); } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace System.ComponentModel { /// <summary> /// This type description provider provides type information through /// reflection. Unless someone has provided a custom type description /// provider for a type or instance, or unless an instance implements /// ICustomTypeDescriptor, any query for type information will go through /// this class. There should be a single instance of this class associated /// with "object", as it can provide all type information for any type. /// </summary> internal sealed class ReflectTypeDescriptionProvider { // This is where we store the various converters for the intrinsic types. // private static volatile Dictionary<object, object> s_intrinsicConverters; // For converters, etc that are bound to class attribute data, rather than a class // type, we have special key sentinel values that we put into the hash table. // private static object s_intrinsicNullableKey = new object(); private static object s_syncObject = new object(); /// <summary> /// Creates a new ReflectTypeDescriptionProvider. The type is the /// type we will obtain type information for. /// </summary> internal ReflectTypeDescriptionProvider() { } /// <summary> /// This is a table we create for intrinsic types. /// There should be entries here ONLY for intrinsic /// types, as all other types we should be able to /// add attributes directly as metadata. /// </summary> private static Dictionary<object, object> IntrinsicTypeConverters { get { Debug.Assert(Monitor.IsEntered(s_syncObject)); // It is not worth taking a lock for this -- worst case of a collision // would build two tables, one that garbage collects very quickly. // if (ReflectTypeDescriptionProvider.s_intrinsicConverters == null) { Dictionary<object, object> temp = new Dictionary<object, object>(); // Add the intrinsics // temp[typeof(bool)] = typeof(BooleanConverter); temp[typeof(byte)] = typeof(ByteConverter); temp[typeof(SByte)] = typeof(SByteConverter); temp[typeof(char)] = typeof(CharConverter); temp[typeof(double)] = typeof(DoubleConverter); temp[typeof(string)] = typeof(StringConverter); temp[typeof(int)] = typeof(Int32Converter); temp[typeof(short)] = typeof(Int16Converter); temp[typeof(long)] = typeof(Int64Converter); temp[typeof(float)] = typeof(SingleConverter); temp[typeof(UInt16)] = typeof(UInt16Converter); temp[typeof(UInt32)] = typeof(UInt32Converter); temp[typeof(UInt64)] = typeof(UInt64Converter); temp[typeof(object)] = typeof(TypeConverter); temp[typeof(void)] = typeof(TypeConverter); temp[typeof(DateTime)] = typeof(DateTimeConverter); temp[typeof(DateTimeOffset)] = typeof(DateTimeOffsetConverter); temp[typeof(Decimal)] = typeof(DecimalConverter); temp[typeof(TimeSpan)] = typeof(TimeSpanConverter); temp[typeof(Guid)] = typeof(GuidConverter); temp[typeof(Array)] = typeof(ArrayConverter); temp[typeof(ICollection)] = typeof(CollectionConverter); temp[typeof(Enum)] = typeof(EnumConverter); // Special cases for things that are not bound to a specific type // temp[ReflectTypeDescriptionProvider.s_intrinsicNullableKey] = typeof(NullableConverter); ReflectTypeDescriptionProvider.s_intrinsicConverters = temp; } return ReflectTypeDescriptionProvider.s_intrinsicConverters; } } /// <summary> /// Helper method to create type converters. This checks to see if the /// type implements a Type constructor, and if it does it invokes that ctor. /// Otherwise, it just tries to create the type. /// </summary> private static object CreateInstance(Type objectType, Type parameterType, ref bool noTypeConstructor) { ConstructorInfo typeConstructor = null; noTypeConstructor = true; foreach (ConstructorInfo constructor in objectType.GetTypeInfo().DeclaredConstructors) { if (!constructor.IsPublic) { continue; } // This is the signature we look for when creating types that are generic, but // want to know what type they are dealing with. Enums are a good example of this; // there is one enum converter that can work with all enums, but it needs to know // the type of enum it is dealing with. // ParameterInfo[] parameters = constructor.GetParameters(); if (parameters.Length != 1 || !parameters[0].ParameterType.Equals(typeof(Type))) { continue; } typeConstructor = constructor; break; } if (typeConstructor != null) { noTypeConstructor = false; return typeConstructor.Invoke(new object[] { parameterType }); } return Activator.CreateInstance(objectType); } private static TypeConverterAttribute GetTypeConverterAttributeIfAny(Type type) { foreach (TypeConverterAttribute attribute in type.GetTypeInfo().GetCustomAttributes<TypeConverterAttribute>(false)) { return attribute; } return null; } /// <summary> /// Gets a type converter for the specified type. /// </summary> internal static TypeConverter GetConverter(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } // Check the cached TypeConverter dictionary for an exact match of the given type. object ans = SearchIntrinsicTable_ExactTypeMatch(type); if (ans != null) return (TypeConverter)ans; // Obtaining attributes follows a very critical order: we must take care that // we merge attributes the right way. Consider this: // // [A4] // interface IBase; // // [A3] // interface IDerived; // // [A2] // class Base : IBase; // // [A1] // class Derived : Base, IDerived // // We are retrieving attributes in the following order: A1 - A4. // Interfaces always lose to types, and interfaces and types // must be looked up in the same order. TypeConverterAttribute converterAttribute = ReflectTypeDescriptionProvider.GetTypeConverterAttributeIfAny(type); if (converterAttribute == null) { Type baseType = type.GetTypeInfo().BaseType; while (baseType != null && baseType != typeof(object)) { converterAttribute = ReflectTypeDescriptionProvider.GetTypeConverterAttributeIfAny(baseType); if (converterAttribute != null) { break; } baseType = baseType.GetTypeInfo().BaseType; } } if (converterAttribute == null) { IEnumerable<Type> interfaces = type.GetTypeInfo().ImplementedInterfaces; foreach (Type iface in interfaces) { // only do this for public interfaces. // if ((iface.GetTypeInfo().Attributes & (TypeAttributes.Public | TypeAttributes.NestedPublic)) != 0) { converterAttribute = GetTypeConverterAttributeIfAny(iface); if (converterAttribute != null) { break; } } } } if (converterAttribute != null) { Type converterType = ReflectTypeDescriptionProvider.GetTypeFromName(converterAttribute.ConverterTypeName, type); if (converterType != null && typeof(TypeConverter).GetTypeInfo().IsAssignableFrom(converterType.GetTypeInfo())) { bool noTypeConstructor = true; object instance = (TypeConverter)ReflectTypeDescriptionProvider.CreateInstance(converterType, type, ref noTypeConstructor); if (noTypeConstructor) { lock (s_syncObject) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters[type] = instance; } } return (TypeConverter)instance; } } // We did not get a converter. Traverse up the base class chain until // we find one in the stock hashtable. // return (TypeConverter)ReflectTypeDescriptionProvider.SearchIntrinsicTable(type); } /// <summary> /// Retrieve a type from a name, if the name is not a fully qualified assembly name, then /// look for this type name in the same assembly as the "type" parameter is defined in. /// </summary> private static Type GetTypeFromName(string typeName, Type type) { if (string.IsNullOrEmpty(typeName)) { return null; } int commaIndex = typeName.IndexOf(','); Type t = null; if (commaIndex == -1) { t = type.GetTypeInfo().Assembly.GetType(typeName); } if (t == null) { t = Type.GetType(typeName); } return t; } /// <summary> /// Searches the provided intrinsic hashtable for a match with the object type. /// At the beginning, the hashtable contains types for the various converters. /// As this table is searched, the types for these objects /// are replaced with instances, so we only create as needed. This method /// does the search up the base class hierarchy and will create instances /// for types as needed. These instances are stored back into the table /// for the base type, and for the original component type, for fast access. /// </summary> private static object SearchIntrinsicTable(Type callingType) { object hashEntry = null; // We take a lock on this table. Nothing in this code calls out to // other methods that lock, so it should be fairly safe to grab this // lock. Also, this allows multiple intrinsic tables to be searched // at once. // lock (ReflectTypeDescriptionProvider.s_syncObject) { Type baseType = callingType; while (baseType != null && baseType != typeof(object)) { if (ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(baseType, out hashEntry) && hashEntry != null) { break; } baseType = baseType.GetTypeInfo().BaseType; } TypeInfo callingTypeInfo = callingType.GetTypeInfo(); // Now make a scan through each value in the table, looking for interfaces. // If we find one, see if the object implements the interface. // if (hashEntry == null) { foreach (object key in ReflectTypeDescriptionProvider.IntrinsicTypeConverters.Keys) { Type keyType = key as Type; if (keyType != null) { TypeInfo keyTypeInfo = keyType.GetTypeInfo(); if (keyTypeInfo.IsInterface && keyTypeInfo.IsAssignableFrom(callingTypeInfo)) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(key, out hashEntry); string converterTypeString = hashEntry as string; if (converterTypeString != null) { hashEntry = Type.GetType(converterTypeString); if (hashEntry != null) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters[callingType] = hashEntry; } } if (hashEntry != null) { break; } } } } } // Special case converter // if (hashEntry == null) { if (callingTypeInfo.IsGenericType && callingTypeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)) { // Check if it is a nullable value ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(ReflectTypeDescriptionProvider.s_intrinsicNullableKey, out hashEntry); } } // Interfaces do not derive from object, so we // must handle the case of no hash entry here. // if (hashEntry == null) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters.TryGetValue(typeof(object), out hashEntry); } // If the entry is a type, create an instance of it and then // replace the entry. This way we only need to create once. // We can only do this if the object doesn't want a type // in its constructor. // Type type = hashEntry as Type; if (type != null) { bool noTypeConstructor = true; hashEntry = ReflectTypeDescriptionProvider.CreateInstance(type, callingType, ref noTypeConstructor); if (noTypeConstructor) { ReflectTypeDescriptionProvider.IntrinsicTypeConverters[callingType] = hashEntry; } } } return hashEntry; } private static object SearchIntrinsicTable_ExactTypeMatch(Type callingType) { object hashEntry = null; // We take a lock on this table. Nothing in this code calls out to // other methods that lock, so it should be fairly safe to grab this // lock. Also, this allows multiple intrinsic tables to be searched // at once. // lock (s_syncObject) { if (callingType != null && !IntrinsicTypeConverters.TryGetValue(callingType, out hashEntry)) return null; // If the entry is a type, create an instance of it and then // replace the entry. This way we only need to create once. // We can only do this if the object doesn't want a type // in its constructor. Type type = hashEntry as Type; if (type != null) { bool noTypeConstructor = true; hashEntry = CreateInstance(type, callingType, ref noTypeConstructor); if (noTypeConstructor) IntrinsicTypeConverters[callingType] = hashEntry; } } return hashEntry; } } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Capabilities; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.OAuth; using Microsoft.VisualStudio.Services.WebApi; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(ConfigurationManager))] public interface IConfigurationManager : IAgentService { bool IsConfigured(); Task ConfigureAsync(CommandSettings command); Task UnconfigureAsync(CommandSettings command); AgentSettings LoadSettings(); } public sealed class ConfigurationManager : AgentService, IConfigurationManager { private IConfigurationStore _store; private IAgentServer _agentServer; private ITerminal _term; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); Trace.Verbose("Creating _store"); _store = hostContext.GetService<IConfigurationStore>(); Trace.Verbose("store created"); _term = hostContext.GetService<ITerminal>(); } public bool IsConfigured() { bool result = _store.IsConfigured(); Trace.Info($"Is configured: {result}"); return result; } public AgentSettings LoadSettings() { Trace.Info(nameof(LoadSettings)); if (!IsConfigured()) { throw new InvalidOperationException("Not configured"); } AgentSettings settings = _store.GetSettings(); Trace.Info("Settings Loaded"); return settings; } public async Task ConfigureAsync(CommandSettings command) { ArgUtil.Equal(RunMode.Normal, HostContext.RunMode, nameof(HostContext.RunMode)); Trace.Info(nameof(ConfigureAsync)); if (IsConfigured()) { throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError")); } // Populate proxy setting from commandline args var vstsProxy = HostContext.GetService<IVstsAgentWebProxy>(); bool saveProxySetting = false; string proxyUrl = command.GetProxyUrl(); if (!string.IsNullOrEmpty(proxyUrl)) { if (!Uri.IsWellFormedUriString(proxyUrl, UriKind.Absolute)) { throw new ArgumentOutOfRangeException(nameof(proxyUrl)); } Trace.Info("Reset proxy base on commandline args."); string proxyUserName = command.GetProxyUserName(); string proxyPassword = command.GetProxyPassword(); (vstsProxy as VstsAgentWebProxy).SetupProxy(proxyUrl, proxyUserName, proxyPassword); saveProxySetting = true; } // Populate cert setting from commandline args var agentCertManager = HostContext.GetService<IAgentCertificateManager>(); bool saveCertSetting = false; bool skipCertValidation = command.GetSkipCertificateValidation(); string caCert = command.GetCACertificate(); string clientCert = command.GetClientCertificate(); string clientCertKey = command.GetClientCertificatePrivateKey(); string clientCertArchive = command.GetClientCertificateArchrive(); string clientCertPassword = command.GetClientCertificatePassword(); // We require all Certificate files are under agent root. // So we can set ACL correctly when configure as service if (!string.IsNullOrEmpty(caCert)) { caCert = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), caCert); ArgUtil.File(caCert, nameof(caCert)); } if (!string.IsNullOrEmpty(clientCert) && !string.IsNullOrEmpty(clientCertKey) && !string.IsNullOrEmpty(clientCertArchive)) { // Ensure all client cert pieces are there. clientCert = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCert); clientCertKey = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCertKey); clientCertArchive = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), clientCertArchive); ArgUtil.File(clientCert, nameof(clientCert)); ArgUtil.File(clientCertKey, nameof(clientCertKey)); ArgUtil.File(clientCertArchive, nameof(clientCertArchive)); } else if (!string.IsNullOrEmpty(clientCert) || !string.IsNullOrEmpty(clientCertKey) || !string.IsNullOrEmpty(clientCertArchive)) { // Print out which args are missing. ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCert, Constants.Agent.CommandLine.Args.SslClientCert); ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCertKey, Constants.Agent.CommandLine.Args.SslClientCertKey); ArgUtil.NotNullOrEmpty(Constants.Agent.CommandLine.Args.SslClientCertArchive, Constants.Agent.CommandLine.Args.SslClientCertArchive); } if (skipCertValidation || !string.IsNullOrEmpty(caCert) || !string.IsNullOrEmpty(clientCert)) { Trace.Info("Reset agent cert setting base on commandline args."); (agentCertManager as AgentCertificateManager).SetupCertificate(skipCertValidation, caCert, clientCert, clientCertKey, clientCertArchive, clientCertPassword); saveCertSetting = true; } AgentSettings agentSettings = new AgentSettings(); // TEE EULA agentSettings.AcceptTeeEula = false; switch (Constants.Agent.Platform) { case Constants.OSPlatform.OSX: case Constants.OSPlatform.Linux: // Write the section header. WriteSection(StringUtil.Loc("EulasSectionHeader")); // Verify the EULA exists on disk in the expected location. string eulaFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), Constants.Path.TeeDirectory, "license.html"); ArgUtil.File(eulaFile, nameof(eulaFile)); // Write elaborate verbiage about the TEE EULA. _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile)); _term.WriteLine(); // Prompt to acccept the TEE EULA. agentSettings.AcceptTeeEula = command.GetAcceptTeeEula(); break; case Constants.OSPlatform.Windows: // Warn and continue if .NET 4.6 is not installed. if (!NetFrameworkUtil.Test(new Version(4, 6), Trace)) { WriteSection(StringUtil.Loc("PrerequisitesSectionHeader")); // Section header. _term.WriteLine(StringUtil.Loc("MinimumNetFrameworkTfvc")); // Warning. } break; default: throw new NotSupportedException(); } // Create the configuration provider as per agent type. string agentType; if (command.DeploymentGroup) { agentType = Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration; } else if (command.DeploymentPool) { agentType = Constants.Agent.AgentConfigurationProvider.SharedDeploymentAgentConfiguration; } else { agentType = Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; } var extensionManager = HostContext.GetService<IExtensionManager>(); IConfigurationProvider agentProvider = (extensionManager.GetExtensions<IConfigurationProvider>()) .FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); bool isHostedServer = false; // Loop getting url and creds until you can connect ICredentialProvider credProvider = null; VssCredentials creds = null; WriteSection(StringUtil.Loc("ConnectSectionHeader")); while (true) { // Get the URL agentProvider.GetServerUrl(agentSettings, command); // Get the credentials credProvider = GetCredentialProvider(command, agentSettings.ServerUrl); creds = credProvider.GetVssCredentials(HostContext); Trace.Info("cred retrieved"); try { // Determine the service deployment type based on connection data. (Hosted/OnPremises) isHostedServer = await IsHostedServer(agentSettings.ServerUrl, creds); // Get the collection name for deployment group agentProvider.GetCollectionName(agentSettings, command, isHostedServer); // Validate can connect. await agentProvider.TestConnectionAsync(agentSettings, creds, isHostedServer); Trace.Info("Test Connection complete."); break; } catch (Exception e) when (!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToConnect")); } } _agentServer = HostContext.GetService<IAgentServer>(); // We want to use the native CSP of the platform for storage, so we use the RSACSP directly RSAParameters publicKey; var keyManager = HostContext.GetService<IRSAKeyManager>(); using (var rsa = keyManager.CreateKey()) { publicKey = rsa.ExportParameters(false); } // Loop getting agent name and pool name WriteSection(StringUtil.Loc("RegisterAgentSectionHeader")); while (true) { try { await agentProvider.GetPoolId(agentSettings, command); break; } catch (Exception e) when (!command.Unattended) { _term.WriteError(e); _term.WriteError(agentProvider.GetFailedToFindPoolErrorString()); } } TaskAgent agent; while (true) { agentSettings.AgentName = command.GetAgentName(); // Get the system capabilities. // TODO: Hook up to ctrl+c cancellation token. _term.WriteLine(StringUtil.Loc("ScanToolCapabilities")); Dictionary<string, string> systemCapabilities = await HostContext.GetService<ICapabilitiesManager>().GetCapabilitiesAsync(agentSettings, CancellationToken.None); _term.WriteLine(StringUtil.Loc("ConnectToServer")); agent = await agentProvider.GetAgentAsync(agentSettings); if (agent != null) { if (command.GetReplace()) { // Update existing agent with new PublicKey, agent version and SystemCapabilities. agent = UpdateExistingAgent(agent, publicKey, systemCapabilities); try { agent = await agentProvider.UpdateAgentAsync(agentSettings, agent, command); _term.WriteLine(StringUtil.Loc("AgentReplaced")); break; } catch (Exception e) when (!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("FailedToReplaceAgent")); } } else if (command.Unattended) { // if not replace and it is unattended config. agentProvider.ThrowTaskAgentExistException(agentSettings); } } else { // Create a new agent. agent = CreateNewAgent(agentSettings.AgentName, publicKey, systemCapabilities); try { agent = await agentProvider.AddAgentAsync(agentSettings, agent, command); _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully")); break; } catch (Exception e) when (!command.Unattended) { _term.WriteError(e); _term.WriteError(StringUtil.Loc("AddAgentFailed")); } } } // Add Agent Id to settings agentSettings.AgentId = agent.Id; // respect the serverUrl resolve by server. // in case of agent configured using collection url instead of account url. string agentServerUrl; if (agent.Properties.TryGetValidatedValue<string>("ServerUrl", out agentServerUrl) && !string.IsNullOrEmpty(agentServerUrl)) { Trace.Info($"Agent server url resolve by server: '{agentServerUrl}'."); // we need make sure the Schema/Host/Port component of the url remain the same. UriBuilder inputServerUrl = new UriBuilder(agentSettings.ServerUrl); UriBuilder serverReturnedServerUrl = new UriBuilder(agentServerUrl); if (Uri.Compare(inputServerUrl.Uri, serverReturnedServerUrl.Uri, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { inputServerUrl.Path = serverReturnedServerUrl.Path; Trace.Info($"Replace server returned url's scheme://host:port component with user input server url's scheme://host:port: '{inputServerUrl.Uri.AbsoluteUri}'."); agentSettings.ServerUrl = inputServerUrl.Uri.AbsoluteUri; } else { agentSettings.ServerUrl = agentServerUrl; } } // See if the server supports our OAuth key exchange for credentials if (agent.Authorization != null && agent.Authorization.ClientId != Guid.Empty && agent.Authorization.AuthorizationUrl != null) { // We use authorizationUrl as the oauth endpoint url by default. // For TFS, we need make sure the Schema/Host/Port component of the oauth endpoint url also match configuration url. (Incase of customer's agent configure URL and TFS server public URL are different) // Which means, we will keep use the original authorizationUrl in the VssOAuthJwtBearerClientCredential (authorizationUrl is the audience), // But might have different Url in VssOAuthCredential (connection url) // We can't do this for VSTS, since its SPS/TFS urls are different. UriBuilder configServerUrl = new UriBuilder(agentSettings.ServerUrl); UriBuilder oauthEndpointUrlBuilder = new UriBuilder(agent.Authorization.AuthorizationUrl); if (!isHostedServer && Uri.Compare(configServerUrl.Uri, oauthEndpointUrlBuilder.Uri, UriComponents.SchemeAndServer, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0) { oauthEndpointUrlBuilder.Scheme = configServerUrl.Scheme; oauthEndpointUrlBuilder.Host = configServerUrl.Host; oauthEndpointUrlBuilder.Port = configServerUrl.Port; Trace.Info($"Set oauth endpoint url's scheme://host:port component to match agent configure url's scheme://host:port: '{oauthEndpointUrlBuilder.Uri.AbsoluteUri}'."); } var credentialData = new CredentialData { Scheme = Constants.Configuration.OAuth, Data = { { "clientId", agent.Authorization.ClientId.ToString("D") }, { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri }, { "oauthEndpointUrl", oauthEndpointUrlBuilder.Uri.AbsoluteUri }, }, }; // Save the negotiated OAuth credential data _store.SaveCredential(credentialData); } else { switch (Constants.Agent.Platform) { case Constants.OSPlatform.OSX: case Constants.OSPlatform.Linux: // Save the provided admin cred for compat with previous agent. _store.SaveCredential(credProvider.CredentialData); break; case Constants.OSPlatform.Windows: // Not supported against TFS 2015. _term.WriteError(StringUtil.Loc("Tfs2015NotSupported")); return; default: throw new NotSupportedException(); } } // Testing agent connection, detect any protential connection issue, like local clock skew that cause OAuth token expired. _term.WriteLine(StringUtil.Loc("TestAgentConnection")); var credMgr = HostContext.GetService<ICredentialManager>(); VssCredentials credential = credMgr.LoadCredentials(); VssConnection conn = VssUtil.CreateConnection(new Uri(agentSettings.ServerUrl), credential); var agentSvr = HostContext.GetService<IAgentServer>(); try { await agentSvr.ConnectAsync(conn); } catch (VssOAuthTokenRequestException ex) when (ex.Message.Contains("Current server time is")) { // there are two exception messages server send that indicate clock skew. // 1. The bearer token expired on {jwt.ValidTo}. Current server time is {DateTime.UtcNow}. // 2. The bearer token is not valid until {jwt.ValidFrom}. Current server time is {DateTime.UtcNow}. Trace.Error("Catch exception during test agent connection."); Trace.Error(ex); throw new Exception(StringUtil.Loc("LocalClockSkewed")); } // We will Combine() what's stored with root. Defaults to string a relative path agentSettings.WorkFolder = command.GetWork(); // notificationPipeName for Hosted agent provisioner. agentSettings.NotificationPipeName = command.GetNotificationPipeName(); agentSettings.NotificationSocketAddress = command.GetNotificationSocketAddress(); _store.SaveSettings(agentSettings); if (saveProxySetting) { Trace.Info("Save proxy setting to disk."); (vstsProxy as VstsAgentWebProxy).SaveProxySetting(); } if (saveCertSetting) { Trace.Info("Save agent cert setting to disk."); (agentCertManager as AgentCertificateManager).SaveCertificateSetting(); } _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow)); bool saveRuntimeOptions = false; var runtimeOptions = new AgentRuntimeOptions(); #if OS_WINDOWS if (command.GitUseSChannel) { saveRuntimeOptions = true; runtimeOptions.GitUseSecureChannel = true; } #endif if (saveRuntimeOptions) { Trace.Info("Save agent runtime options to disk."); _store.SaveAgentRuntimeOptions(runtimeOptions); } #if OS_WINDOWS // config windows service bool runAsService = command.GetRunAsService(); if (runAsService) { Trace.Info("Configuring to run the agent as service"); var serviceControlManager = HostContext.GetService<IWindowsServiceControlManager>(); serviceControlManager.ConfigureService(agentSettings, command); } // config auto logon else if (command.GetRunAsAutoLogon()) { Trace.Info("Agent is going to run as process setting up the 'AutoLogon' capability for the agent."); var autoLogonConfigManager = HostContext.GetService<IAutoLogonManager>(); await autoLogonConfigManager.ConfigureAsync(command); //Important: The machine may restart if the autologon user is not same as the current user //if you are adding code after this, keep that in mind } #elif OS_LINUX || OS_OSX // generate service config script for OSX and Linux, GenerateScripts() will no-opt on windows. var serviceControlManager = HostContext.GetService<ILinuxServiceControlManager>(); serviceControlManager.GenerateScripts(agentSettings); #endif } public async Task UnconfigureAsync(CommandSettings command) { ArgUtil.Equal(RunMode.Normal, HostContext.RunMode, nameof(HostContext.RunMode)); string currentAction = string.Empty; try { //stop, uninstall service and remove service config file if (_store.IsServiceConfigured()) { currentAction = StringUtil.Loc("UninstallingService"); _term.WriteLine(currentAction); #if OS_WINDOWS var serviceControlManager = HostContext.GetService<IWindowsServiceControlManager>(); serviceControlManager.UnconfigureService(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); #elif OS_LINUX // unconfig system D service first throw new Exception(StringUtil.Loc("UnconfigureServiceDService")); #elif OS_OSX // unconfig osx service first throw new Exception(StringUtil.Loc("UnconfigureOSXService")); #endif } else { #if OS_WINDOWS //running as process, unconfigure autologon if it was configured if (_store.IsAutoLogonConfigured()) { currentAction = StringUtil.Loc("UnconfigAutologon"); _term.WriteLine(currentAction); var autoLogonConfigManager = HostContext.GetService<IAutoLogonManager>(); autoLogonConfigManager.Unconfigure(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } else { Trace.Info("AutoLogon was not configured on the agent."); } #endif } //delete agent from the server currentAction = StringUtil.Loc("UnregisteringAgent"); _term.WriteLine(currentAction); bool isConfigured = _store.IsConfigured(); bool hasCredentials = _store.HasCredentials(); if (isConfigured && hasCredentials) { AgentSettings settings = _store.GetSettings(); var credentialManager = HostContext.GetService<ICredentialManager>(); // Get the credentials var credProvider = GetCredentialProvider(command, settings.ServerUrl); VssCredentials creds = credProvider.GetVssCredentials(HostContext); Trace.Info("cred retrieved"); bool isDeploymentGroup = (settings.MachineGroupId > 0) || (settings.DeploymentGroupId > 0); Trace.Info("Agent configured for deploymentGroup : {0}", isDeploymentGroup.ToString()); string agentType = isDeploymentGroup ? Constants.Agent.AgentConfigurationProvider.DeploymentAgentConfiguration : Constants.Agent.AgentConfigurationProvider.BuildReleasesAgentConfiguration; var extensionManager = HostContext.GetService<IExtensionManager>(); IConfigurationProvider agentProvider = (extensionManager.GetExtensions<IConfigurationProvider>()).FirstOrDefault(x => x.ConfigurationProviderType == agentType); ArgUtil.NotNull(agentProvider, agentType); // Determine the service deployment type based on connection data. (Hosted/OnPremises) bool isHostedServer = await IsHostedServer(settings.ServerUrl, creds); await agentProvider.TestConnectionAsync(settings, creds, isHostedServer); TaskAgent agent = await agentProvider.GetAgentAsync(settings); if (agent == null) { _term.WriteLine(StringUtil.Loc("Skipping") + currentAction); } else { await agentProvider.DeleteAgentAsync(settings); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } } else { _term.WriteLine(StringUtil.Loc("MissingConfig")); } //delete credential config files currentAction = StringUtil.Loc("DeletingCredentials"); _term.WriteLine(currentAction); if (hasCredentials) { _store.DeleteCredential(); var keyManager = HostContext.GetService<IRSAKeyManager>(); keyManager.DeleteKey(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } else { _term.WriteLine(StringUtil.Loc("Skipping") + currentAction); } //delete settings config file currentAction = StringUtil.Loc("DeletingSettings"); _term.WriteLine(currentAction); if (isConfigured) { // delete proxy setting (HostContext.GetService<IVstsAgentWebProxy>() as VstsAgentWebProxy).DeleteProxySetting(); // delete agent cert setting (HostContext.GetService<IAgentCertificateManager>() as AgentCertificateManager).DeleteCertificateSetting(); // delete agent runtime option _store.DeleteAgentRuntimeOptions(); _store.DeleteSettings(); _term.WriteLine(StringUtil.Loc("Success") + currentAction); } else { _term.WriteLine(StringUtil.Loc("Skipping") + currentAction); } } catch (Exception) { _term.WriteLine(StringUtil.Loc("Failed") + currentAction); throw; } } private ICredentialProvider GetCredentialProvider(CommandSettings command, string serverUrl) { Trace.Info(nameof(GetCredentialProvider)); var credentialManager = HostContext.GetService<ICredentialManager>(); // Get the default auth type. // Use PAT as long as the server uri scheme is Https and looks like a FQDN // Otherwise windows use Integrated, linux/mac use negotiate. string defaultAuth = string.Empty; Uri server = new Uri(serverUrl); if (server.Scheme == Uri.UriSchemeHttps && server.Host.Contains('.')) { defaultAuth = Constants.Configuration.PAT; } else { defaultAuth = Constants.Agent.Platform == Constants.OSPlatform.Windows ? Constants.Configuration.Integrated : Constants.Configuration.Negotiate; } string authType = command.GetAuth(defaultValue: defaultAuth); // Create the credential. Trace.Info("Creating credential for auth: {0}", authType); var provider = credentialManager.GetCredentialProvider(authType); provider.EnsureCredential(HostContext, command, serverUrl); return provider; } private TaskAgent UpdateExistingAgent(TaskAgent agent, RSAParameters publicKey, Dictionary<string, string> systemCapabilities) { ArgUtil.NotNull(agent, nameof(agent)); agent.Authorization = new TaskAgentAuthorization { PublicKey = new TaskAgentPublicKey(publicKey.Exponent, publicKey.Modulus), }; // update - update instead of delete so we don't lose user capabilities etc... agent.Version = Constants.Agent.Version; agent.OSDescription = RuntimeInformation.OSDescription; foreach (KeyValuePair<string, string> capability in systemCapabilities) { agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty; } return agent; } private TaskAgent CreateNewAgent(string agentName, RSAParameters publicKey, Dictionary<string, string> systemCapabilities) { TaskAgent agent = new TaskAgent(agentName) { Authorization = new TaskAgentAuthorization { PublicKey = new TaskAgentPublicKey(publicKey.Exponent, publicKey.Modulus), }, MaxParallelism = 1, Version = Constants.Agent.Version, OSDescription = RuntimeInformation.OSDescription, }; foreach (KeyValuePair<string, string> capability in systemCapabilities) { agent.SystemCapabilities[capability.Key] = capability.Value ?? string.Empty; } return agent; } private void WriteSection(string message) { _term.WriteLine(); _term.WriteLine($">> {message}:"); _term.WriteLine(); } private async Task<bool> IsHostedServer(string serverUrl, VssCredentials credentials) { // Determine the service deployment type based on connection data. (Hosted/OnPremises) var locationServer = HostContext.GetService<ILocationServer>(); VssConnection connection = VssUtil.CreateConnection(new Uri(serverUrl), credentials); await locationServer.ConnectAsync(connection); try { var connectionData = await locationServer.GetConnectionDataAsync(); Trace.Info($"Server deployment type: {connectionData.DeploymentType}"); return connectionData.DeploymentType.HasFlag(DeploymentFlags.Hosted); } catch (Exception ex) { // Since the DeploymentType is Enum, deserialization exception means there is a new Enum member been added. // It's more likely to be Hosted since OnPremises is always behind and customer can update their agent if are on-prem Trace.Error(ex); return true; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.Location.Steps { /// <summary> /// Location Steps (matches) /// </summary> public static partial class MatchesTests { /// <summary> /// Invalid Location Step - Missing axis . Expected error. /// /::bookstore /// </summary> [Fact] public static void MatchesTest151() { var xml = "books.xml"; var testExpression = @"/::bookstore"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Missing Node test. Expected error. /// /child:: /// </summary> [Fact] public static void MatchesTest152() { var xml = "books.xml"; var testExpression = @"/child::"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Using an invalid axis. Expected error. /// /bookstore/sibling::book /// </summary> [Fact] public static void MatchesTest153() { var xml = "books.xml"; var testExpression = @"/bookstore/sibling::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple axis. Location step can have only one axis. Test expression uses multiple axis. Expected error. /// /bookstore/child::ancestor::book /// </summary> [Fact] public static void MatchesTest154() { var xml = "books.xml"; var testExpression = @"/bookstore/child::ancestor::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple node tests using | - Multiple node-tests are not allowed. Test uses | to union two node tests. Error expected. /// /bookstore/child::(book | magazine) /// </summary> [Fact] public static void MatchesTest155() { var xml = "books.xml"; var testExpression = @"/bookstore/child::(book | magazine)"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple node tests using | - Multiple node-tests are not allowed. Test uses 'and' to combine two node tests. Error expected. /// /bookstore/book and magazine /// </summary> [Fact] public static void MatchesTest156() { var xml = "books.xml"; var testExpression = @"/bookstore/book and magazine"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Invalid Location Step - Multiple node tests using 'or' - Multiple node-tests are not allowed. Test uses 'or' to combine two node tests. Error expected. /// /bookstore/book or magazine /// </summary> [Fact] public static void MatchesTest157() { var xml = "books.xml"; var testExpression = @"/bookstore/book or magazine"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Valid Location step - Single predicate /// /bookstore/* [name()='book'] /// </summary> [Fact] public static void MatchesTest158() { var xml = "books.xml"; var startingNodePath = "/bookstore/book"; var testExpression = @"/bookstore/* [name()='book']"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Valid Location Step - Multiple predicates /// /bookstore/* [name()='book' or name()='magazine'][name()='magazine'] /// </summary> [Fact] public static void MatchesTest159() { var xml = "books.xml"; var startingNodePath = "/bookstore/magazine"; var testExpression = @"/bookstore/* [name()='book' or name()='magazine'][name()='magazine']"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Valid Location Step - No predicates /// /bookstore/book /// </summary> [Fact] public static void MatchesTest1510() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[5]"; var testExpression = @"/bookstore/book"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Check order of predicates - Test to check if the predicates are applied in the correct order. Should select the 3rd book node in the XML doc. /// /bookstore/book [position() = 1 or position() = 3 or position() = 6][position() = 2] /// </summary> [Fact] public static void MatchesTest1511() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[3]"; var testExpression = @"/bookstore/book [position() = 1 or position() = 3 or position() = 6][position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected Error : Abbreviated Axis specifier '.' is a valid location step, but not allowed in matches /// /. /// </summary> [Fact] public static void MatchesTest1512() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"/."; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected Error : Abbreviated Axis specifier '..' is a valid location step, but not allowed in matches /// /bookstore/book/.. /// </summary> [Fact] public static void MatchesTest1513() { var xml = "books.xml"; var startingNodePath = "/bookstore"; var testExpression = @"/bookstore/book/.."; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Invalid Expression '..' with node test. Node test is not allowed with an abbreviated axis specifier /// /bookstore/*/title/.. book /// </summary> [Fact] public static void MatchesTest1514() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"/bookstore/*/title/.. book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Invalid Expression '.' with node test. Predicates are not allowed with abbreviated axis specifiers. /// /bookstore/*/title/.[name()='book'] /// </summary> [Fact] public static void MatchesTest1515() { var xml = "books.xml"; var startingNodePath = "/bookstore/book"; var testExpression = @"/bookstore/*/title/.[name()='book']"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } } }
// // Log.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2005-2007 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.Text; using System.Collections.Generic; using System.Threading; namespace Hyena { public delegate void LogNotifyHandler (LogNotifyArgs args); public class LogNotifyArgs : EventArgs { private LogEntry entry; public LogNotifyArgs (LogEntry entry) { this.entry = entry; } public LogEntry Entry { get { return entry; } } } public enum LogEntryType { Debug, Warning, Error, Information } public class LogEntry { private LogEntryType type; private string message; private string details; private DateTime timestamp; internal LogEntry (LogEntryType type, string message, string details) { this.type = type; this.message = message; this.details = details; this.timestamp = DateTime.Now; } public LogEntryType Type { get { return type; } } public string Message { get { return message; } } public string Details { get { return details; } } public DateTime TimeStamp { get { return timestamp; } } } public static class Log { public static event LogNotifyHandler Notify; private static Dictionary<uint, DateTime> timers = new Dictionary<uint, DateTime> (); private static uint next_timer_id = 1; private static bool debugging = false; public static bool Debugging { get { return debugging; } set { debugging = value; } } public static void Commit (LogEntryType type, string message, string details, bool showUser) { if (type == LogEntryType.Debug && !Debugging) { return; } if (type != LogEntryType.Information || (type == LogEntryType.Information && !showUser)) { switch (type) { case LogEntryType.Error: ConsoleCrayon.ForegroundColor = ConsoleColor.Red; break; case LogEntryType.Warning: ConsoleCrayon.ForegroundColor = ConsoleColor.DarkYellow; break; case LogEntryType.Information: ConsoleCrayon.ForegroundColor = ConsoleColor.Green; break; case LogEntryType.Debug: ConsoleCrayon.ForegroundColor = ConsoleColor.Blue; break; } var thread_name = String.Empty; if (Debugging) { var thread = Thread.CurrentThread; thread_name = String.Format ("{0} ", thread.ManagedThreadId); } Console.Write ("[{5}{0} {1:00}:{2:00}:{3:00}.{4:000}]", TypeString (type), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond, thread_name); ConsoleCrayon.ResetColor (); if (details != null) { Console.WriteLine (" {0} - {1}", message, details); } else { Console.WriteLine (" {0}", message); } } if (showUser) { OnNotify (new LogEntry (type, message, details)); } } private static string TypeString (LogEntryType type) { switch (type) { case LogEntryType.Debug: return "Debug"; case LogEntryType.Warning: return "Warn "; case LogEntryType.Error: return "Error"; case LogEntryType.Information: return "Info "; } return null; } private static void OnNotify (LogEntry entry) { LogNotifyHandler handler = Notify; if (handler != null) { handler (new LogNotifyArgs (entry)); } } #region Timer Methods public static uint DebugTimerStart (string message) { return TimerStart (message, false); } public static uint InformationTimerStart (string message) { return TimerStart (message, true); } private static uint TimerStart (string message, bool isInfo) { if (!Debugging && !isInfo) { return 0; } if (isInfo) { Information (message); } else { Debug (message); } return TimerStart (isInfo); } public static uint DebugTimerStart () { return TimerStart (false); } public static uint InformationTimerStart () { return TimerStart (true); } private static uint TimerStart (bool isInfo) { if (!Debugging && !isInfo) { return 0; } uint timer_id = next_timer_id++; timers.Add (timer_id, DateTime.Now); return timer_id; } public static void DebugTimerPrint (uint id) { if (!Debugging) { return; } TimerPrint (id, "Operation duration: {0}", false); } public static void DebugTimerPrint (uint id, string message) { if (!Debugging) { return; } TimerPrint (id, message, false); } public static void InformationTimerPrint (uint id) { TimerPrint (id, "Operation duration: {0}", true); } public static void InformationTimerPrint (uint id, string message) { TimerPrint (id, message, true); } private static void TimerPrint (uint id, string message, bool isInfo) { if (!Debugging && !isInfo) { return; } DateTime finish = DateTime.Now; if (!timers.ContainsKey (id)) { return; } TimeSpan duration = finish - timers[id]; string d_message; if (duration.TotalSeconds < 60) { d_message = duration.TotalSeconds.ToString (); } else { d_message = duration.ToString (); } if (isInfo) { InformationFormat (message, d_message); } else { DebugFormat (message, d_message); } } #endregion #region Public Debug Methods public static void Debug (string message, string details) { if (Debugging) { Commit (LogEntryType.Debug, message, details, false); } } public static void Debug (string message) { if (Debugging) { Debug (message, null); } } public static void DebugFormat (string format, params object [] args) { if (Debugging) { Debug (String.Format (format, args)); } } #endregion #region Public Information Methods public static void Information (string message) { Information (message, null); } public static void Information (string message, string details) { Information (message, details, false); } public static void Information (string message, string details, bool showUser) { Commit (LogEntryType.Information, message, details, showUser); } public static void Information (string message, bool showUser) { Information (message, null, showUser); } public static void InformationFormat (string format, params object [] args) { Information (String.Format (format, args)); } #endregion #region Public Warning Methods public static void Warning (string message) { Warning (message, null); } public static void Warning (string message, string details) { Warning (message, details, false); } public static void Warning (string message, string details, bool showUser) { Commit (LogEntryType.Warning, message, details, showUser); } public static void Warning (string message, bool showUser) { Warning (message, null, showUser); } public static void WarningFormat (string format, params object [] args) { Warning (String.Format (format, args)); } #endregion #region Public Error Methods public static void Error (string message) { Error (message, null); } public static void Error (string message, string details) { Error (message, details, false); } public static void Error (string message, string details, bool showUser) { Commit (LogEntryType.Error, message, details, showUser); } public static void Error (string message, bool showUser) { Error (message, null, showUser); } public static void ErrorFormat (string format, params object [] args) { Error (String.Format (format, args)); } #endregion #region Public Exception Methods public static void DebugException (Exception e) { if (Debugging) { Exception (e); } } public static void Exception (Exception e) { Exception (null, e); } public static void Exception (string message, Exception e) { Stack<Exception> exception_chain = new Stack<Exception> (); StringBuilder builder = new StringBuilder (); while (e != null) { exception_chain.Push (e); e = e.InnerException; } while (exception_chain.Count > 0) { e = exception_chain.Pop (); builder.AppendFormat ("{0}: {1} (in `{2}')", e.GetType (), e.Message, e.Source).AppendLine (); builder.Append (e.StackTrace); if (exception_chain.Count > 0) { builder.AppendLine (); } } // FIXME: We should save these to an actual log file Log.Warning (message ?? "Caught an exception", builder.ToString (), false); } #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 Microsoft.Win32.SafeHandles; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// Tests for the constructors for NamedPipeServerStream /// </summary> public class NamedPipeTest_CreateServer : NamedPipeTestBase { [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void NullPipeName_Throws_ArgumentNullException(PipeDirection direction) { Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null)); Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction)); Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 2)); Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 3, PipeTransmissionMode.Byte)); Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 3, PipeTransmissionMode.Byte, PipeOptions.None)); Assert.Throws<ArgumentNullException>("pipeName", () => new NamedPipeServerStream(null, direction, 3, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void ZeroLengthPipeName_Throws_ArgumentException(PipeDirection direction) { Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("")); Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction)); Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 2)); Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 3, PipeTransmissionMode.Byte)); Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 3, PipeTransmissionMode.Byte, PipeOptions.None)); Assert.Throws<ArgumentException>(() => new NamedPipeServerStream("", direction, 3, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] [PlatformSpecific(PlatformID.Windows)] // "anonymous" only reserved on Windows public static void ReservedPipeName_Throws_ArgumentOutOfRangeException(PipeDirection direction) { const string reservedName = "anonymous"; Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName)); Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction)); Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1)); Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1, PipeTransmissionMode.Byte)); Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None)); Assert.Throws<ArgumentOutOfRangeException>("pipeName", () => new NamedPipeServerStream(reservedName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0));} [Fact] public static void Create_PipeName() { new NamedPipeServerStream(GetUniquePipeName()).Dispose(); } [Fact] public static void Create_PipeName_Direction_MaxInstances() { new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.Out, 1).Dispose(); } [Fact] [PlatformSpecific(PlatformID.Windows)] // can't access SafePipeHandle on Unix until after connection created public static void CreateWithNegativeOneServerInstances_DefaultsToMaxServerInstances() { // When passed -1 as the maxnumberofserverisntances, the NamedPipeServerStream.Windows class // will translate that to the platform specific maximum number (255) using (var server = new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var server2 = new NamedPipeServerStream(PipeDirection.InOut, false, true, server.SafePipeHandle)) using (var server3 = new NamedPipeServerStream(PipeDirection.InOut, false, true, server.SafePipeHandle)) { } } [Fact] public static void InvalidPipeDirection_Throws_ArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123)); Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123, 1)); Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123, 1, PipeTransmissionMode.Byte)); Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("temp1", (PipeDirection)123, 1, PipeTransmissionMode.Byte, PipeOptions.None)); Assert.Throws<ArgumentOutOfRangeException>("direction", () => new NamedPipeServerStream("tempx", (PipeDirection)123, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0)); } [Theory] [InlineData(0)] [InlineData(-2)] public static void InvalidServerInstances_Throws_ArgumentOutOfRangeException(int numberOfServerInstances) { Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances)); Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances, PipeTransmissionMode.Byte)); Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None)); Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", PipeDirection.In, numberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void ServerInstancesOver254_Throws_ArgumentOutOfRangeException(PipeDirection direction) { Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255)); Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255, PipeTransmissionMode.Byte)); Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255, PipeTransmissionMode.Byte, PipeOptions.None)); Assert.Throws<ArgumentOutOfRangeException>("maxNumberOfServerInstances", () => new NamedPipeServerStream("temp3", direction, 255, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void InvalidTransmissionMode_Throws_ArgumentOutOfRangeException(PipeDirection direction) { Assert.Throws<ArgumentOutOfRangeException>("transmissionMode", () => new NamedPipeServerStream("temp1", direction, 1, (PipeTransmissionMode)123)); Assert.Throws<ArgumentOutOfRangeException>("transmissionMode", () => new NamedPipeServerStream("temp1", direction, 1, (PipeTransmissionMode)123, PipeOptions.None)); Assert.Throws<ArgumentOutOfRangeException>("transmissionMode", () => new NamedPipeServerStream("tempx", direction, 1, (PipeTransmissionMode)123, PipeOptions.None, 0, 0)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void InvalidPipeOptions_Throws_ArgumentOutOfRangeException(PipeDirection direction) { Assert.Throws<ArgumentOutOfRangeException>("options", () => new NamedPipeServerStream("temp1", direction, 1, PipeTransmissionMode.Byte, (PipeOptions)255)); Assert.Throws<ArgumentOutOfRangeException>("options", () => new NamedPipeServerStream("tempx", direction, 1, PipeTransmissionMode.Byte, (PipeOptions)255, 0, 0)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void InvalidBufferSize_Throws_ArgumentOutOfRangeException(PipeDirection direction) { Assert.Throws<ArgumentOutOfRangeException>("inBufferSize", () => new NamedPipeServerStream("temp2", direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("outBufferSize", () => new NamedPipeServerStream("temp2", direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, -123)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void NullPipeHandle_Throws_ArgumentNullException(PipeDirection direction) { Assert.Throws<ArgumentNullException>("safePipeHandle", () => new NamedPipeServerStream(direction, false, true, null)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void InvalidPipeHandle_Throws_ArgumentException(PipeDirection direction) { SafePipeHandle pipeHandle = new SafePipeHandle(new IntPtr(-1), true); Assert.Throws<ArgumentException>("safePipeHandle", () => new NamedPipeServerStream(direction, false, true, pipeHandle)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] public static void BadHandleKind_Throws_IOException(PipeDirection direction) { using (FileStream fs = new FileStream(Path.Combine(Path.GetTempPath(), "_BadHandleKind_Throws_IOException_" + Path.GetRandomFileName()), FileMode.Create, FileAccess.Write, FileShare.None, 8, FileOptions.DeleteOnClose)) { SafeFileHandle safeHandle = fs.SafeFileHandle; bool gotRef = false; try { safeHandle.DangerousAddRef(ref gotRef); IntPtr handle = safeHandle.DangerousGetHandle(); SafePipeHandle fakePipeHandle = new SafePipeHandle(handle, ownsHandle: false); Assert.Throws<IOException>(() => new NamedPipeServerStream(direction, false, true, fakePipeHandle)); } finally { if (gotRef) safeHandle.DangerousRelease(); } } } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] [PlatformSpecific(PlatformID.Windows)] // accessing SafePipeHandle on Unix fails for a non-connected stream public static void Windows_CreateFromDisposedServerHandle_Throws_ObjectDisposedException(PipeDirection direction) { // The pipe is closed when we try to make a new Stream with it var pipe = new NamedPipeServerStream(GetUniquePipeName(), direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); SafePipeHandle handle = pipe.SafePipeHandle; pipe.Dispose(); Assert.Throws<ObjectDisposedException>(() => new NamedPipeServerStream(direction, true, true, pipe.SafePipeHandle).Dispose()); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void Unix_GetHandleOfNewServerStream_Throws_InvalidOperationException() { using (var pipe = new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.Out, 1, PipeTransmissionMode.Byte)) { Assert.Throws<InvalidOperationException>(() => pipe.SafePipeHandle); } } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.InOut)] [InlineData(PipeDirection.Out)] [PlatformSpecific(PlatformID.Windows)] // accessing SafePipeHandle on Unix fails for a non-connected stream public static void Windows_CreateFromAlreadyBoundHandle_Throws_ArgumentException(PipeDirection direction) { // The pipe is already bound using (var pipe = new NamedPipeServerStream(GetUniquePipeName(), direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { Assert.Throws<ArgumentException>(() => new NamedPipeServerStream(direction, true, true, pipe.SafePipeHandle)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // NumberOfServerInstances > 1 isn't supported and has undefined behavior on Unix public static void ServerCountOverMaxServerInstances_Throws_IOException() { string uniqueServerName = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(uniqueServerName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { Assert.Throws<IOException>(() => new NamedPipeServerStream(uniqueServerName)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // NumberOfServerInstances > 1 isn't supported and has undefined behavior on Unix public static void Windows_ServerCloneWithDifferentDirection_Throws_UnauthorizedAccessException() { string uniqueServerName = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(uniqueServerName, PipeDirection.In, 2, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { Assert.Throws<UnauthorizedAccessException>(() => new NamedPipeServerStream(uniqueServerName, PipeDirection.Out)); } } } }
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 MBCorpHeatlhTestRestAPI.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; } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Metadata.Builders; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using UnicornStore.AspNet.Models.Identity; namespace UnicornStore.AspNet.Migrations.Identity { [ContextType(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { public override IModel Model { get { var builder = new BasicModelBuilder() .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 0); b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 1); b.Property<string>("Name") .Annotation("OriginalValueIndex", 2); b.Property<string>("NormalizedName") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 1); b.Property<int>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 2) .Annotation("SqlServer:ValueGeneration", "Default"); b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("ClaimType") .Annotation("OriginalValueIndex", 0); b.Property<string>("ClaimValue") .Annotation("OriginalValueIndex", 1); b.Property<int>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 2) .Annotation("SqlServer:ValueGeneration", "Default"); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 0); b.Property<string>("ProviderDisplayName") .Annotation("OriginalValueIndex", 1); b.Property<string>("ProviderKey") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 2); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 3); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.Property<string>("RoleId") .Annotation("OriginalValueIndex", 0); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 1); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("UnicornStore.AspNet.Models.Identity.ApplicationUser", b => { b.Property<int>("AccessFailedCount") .Annotation("OriginalValueIndex", 0); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken() .Annotation("OriginalValueIndex", 1); b.Property<string>("Email") .Annotation("OriginalValueIndex", 2); b.Property<bool>("EmailConfirmed") .Annotation("OriginalValueIndex", 3); b.Property<string>("Id") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 4); b.Property<bool>("LockoutEnabled") .Annotation("OriginalValueIndex", 5); b.Property<DateTimeOffset?>("LockoutEnd") .Annotation("OriginalValueIndex", 6); b.Property<string>("NormalizedEmail") .Annotation("OriginalValueIndex", 7); b.Property<string>("NormalizedUserName") .Annotation("OriginalValueIndex", 8); b.Property<string>("PasswordHash") .Annotation("OriginalValueIndex", 9); b.Property<string>("PhoneNumber") .Annotation("OriginalValueIndex", 10); b.Property<bool>("PhoneNumberConfirmed") .Annotation("OriginalValueIndex", 11); b.Property<string>("SecurityStamp") .Annotation("OriginalValueIndex", 12); b.Property<bool>("TwoFactorEnabled") .Annotation("OriginalValueIndex", 13); b.Property<string>("UserName") .Annotation("OriginalValueIndex", 14); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("UnicornStore.AspNet.Models.Identity.PreApproval", b => { b.Property<string>("ApprovedBy") .Annotation("OriginalValueIndex", 0); b.Property<DateTime>("ApprovedOn") .Annotation("OriginalValueIndex", 1); b.Property<string>("Role") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 2); b.Property<string>("UserEmail") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 3); b.Key("UserEmail", "Role"); b.Annotation("Relational:TableName", "AspNetPreApprovals"); }); builder.Entity("UnicornStore.AspNet.Models.Identity.UserAddress", b => { b.Property<string>("Addressee") .Annotation("OriginalValueIndex", 0); b.Property<string>("CityOrTown") .Annotation("OriginalValueIndex", 1); b.Property<string>("Country") .Annotation("OriginalValueIndex", 2); b.Property<string>("LineOne") .Annotation("OriginalValueIndex", 3); b.Property<string>("LineTwo") .Annotation("OriginalValueIndex", 4); b.Property<string>("StateOrProvince") .Annotation("OriginalValueIndex", 5); b.Property<int>("UserAddressId") .GenerateValueOnAdd() .Annotation("OriginalValueIndex", 6) .Annotation("SqlServer:ValueGeneration", "Default"); b.Property<string>("UserId") .Annotation("OriginalValueIndex", 7); b.Property<string>("ZipOrPostalCode") .Annotation("OriginalValueIndex", 8); b.Key("UserAddressId"); b.Annotation("Relational:TableName", "AspNetUserAddresses"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("UnicornStore.AspNet.Models.Identity.ApplicationUser", "UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("UnicornStore.AspNet.Models.Identity.ApplicationUser", "UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", b => { b.ForeignKey("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", "RoleId"); b.ForeignKey("UnicornStore.AspNet.Models.Identity.ApplicationUser", "UserId"); }); builder.Entity("UnicornStore.AspNet.Models.Identity.UserAddress", b => { b.ForeignKey("UnicornStore.AspNet.Models.Identity.ApplicationUser", "UserId"); }); return builder.Model; } } } }
using System; namespace GLSLSyntaxAST.Preprocessor { internal class InputScanner { internal InputScanner(string[] sources, int bias, int finale) { mSources = sources; currentSource = 0; currentChar = 0; stringBias = bias; mFinale = finale; // loc[0] loc = new SourceLocation[mSources.Length]; loc[currentSource].stringBias = -stringBias; loc[currentSource].line = 1; loc[currentSource].column = 0; } // return of -1 means end of strings, // anything else is the next character // retrieve the next character and advance one character internal int get() { if (currentSource >= mSources.Length) return -1; if (mSources [currentSource].Length == 0) return -1; int ret = mSources[currentSource][currentChar]; ++loc[currentSource].column; if (ret == '\n') { ++loc[currentSource].line; loc[currentSource].column = 0; } advance(); return ret; } // advance one character void advance() { ++currentChar; var length = mSources [currentSource].Length; if (currentChar >= length) { ++currentSource; if (currentSource < mSources.Length) { loc[currentSource].stringBias = loc[currentSource - 1].stringBias + 1; loc[currentSource].line = 1; loc[currentSource].column = 0; } while (currentSource < mSources.Length && length == 0) { ++currentSource; if (currentSource < mSources.Length) { loc[currentSource].stringBias = loc[currentSource - 1].stringBias + 1; loc[currentSource].line = 1; loc[currentSource].column = 0; } } currentChar = 0; } } internal void unget() { if (currentChar > 0) { --currentChar; --loc[currentSource].column; if (loc[currentSource].column < 0) { // We've moved back past a new line. Find the // previous newline (or start of the file) to compute // the column count on the now current line. int ch = currentChar; while(ch > 0) { if (mSources[currentSource][ch] == '\n') { break; } --ch; } loc[currentSource].column = currentChar - ch; } } else { var strLength = mSources [currentSource].Length; do { --currentSource; } while (currentSource > 0 && strLength == 0); if (strLength == 0) { // set to 0 if we've backed up to the start of an empty string currentChar = 0; } else currentChar = strLength - 1; } if (peek() == '\n') --loc[currentSource].line; } internal int peek() { if (currentSource >= mSources.Length) return -1; return mSources[currentSource][currentChar]; } internal void setLine(int newLine) { loc[currentSource].line = newLine; } internal void setString(int newString) { loc[currentSource].stringBias = newString; } string [] mSources; // array of strings int currentSource; int currentChar; // This is for reporting what string/line an error occurred on, and can be overridden by #line. // It remembers the last state of each source string as it is left for the next one, so unget() // can restore that state. SourceLocation[] loc; // an array int stringBias; // the first string that is the user's string number 0 int mFinale; // number of internal strings after user's last string internal SourceLocation getSourceLoc() { return loc[Math.Max(0, Math.Min(currentSource, mSources.Length - mFinale - 1))]; } // Returns true if there was non-white space (e.g., a comment, newline) before the #version // or no #version was found; otherwise, returns false. There is no error case, it always // succeeds, but will leave version == 0 if no #version was found. // // Sets notFirstToken based on whether tokens (beyond white space and comments) // appeared before the #version. // // N.B. does not attempt to leave input in any particular known state. The assumption // is that scanning will start anew, following the rules for the chosen version/profile, // and with a corresponding parsing context. // // read past any white space void consumeWhiteSpace(ref bool foundNonSpaceTab) { int c = peek(); // don't accidentally consume anything other than whitespace while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { if (c == '\r' || c == '\n') foundNonSpaceTab = true; get(); c = peek(); } } // skip whitespace, then skip a comment, rinse, repeat void consumeWhitespaceComment(ref bool foundNonSpaceTab) { do { consumeWhiteSpace(ref foundNonSpaceTab); // if not starting a comment now, then done int c = peek(); if (c != '/' || c < 0) return; // skip potential comment foundNonSpaceTab = true; if (! consumeComment()) return; } while (true); } // return true if a comment was actually consumed bool consumeComment() { if (peek() != '/') return false; get(); // consume the '/' int c = peek(); if (c == '/') { // a '//' style comment get(); // consume the second '/' c = get(); do { while (c > 0 && c != '\\' && c != '\r' && c != '\n') c = get(); if (c <= 0 || c == '\r' || c == '\n') { while (c == '\r' || c == '\n') c = get(); // we reached the end of the comment break; } else { // it's a '\', so we need to keep going, after skipping what's escaped // read the skipped character c = get(); // if it's a two-character newline, skip both characters if (c == '\r' && peek() == '\n') get(); c = get(); } } while (true); // put back the last non-comment character if (c > 0) unget(); return true; } else if (c == '*') { // a '/*' style comment get(); // consume the '*' c = get(); do { while (c > 0 && c != '*') c = get(); if (c == '*') { c = get(); if (c == '/') break; // end of comment // not end of comment } else // end of input break; } while (true); return true; } else { // it's not a comment, put the '/' back unget(); return false; } } internal bool scanVersion(out int version, out Profile profile, out bool notFirstToken) { // This function doesn't have to get all the semantics correct, // just find the #version if there is a correct one present. // The preprocessor will have the responsibility of getting all the semantics right. bool versionNotFirst = false; // means not first WRT comments and white space, nothing more notFirstToken = false; // means not first WRT to real tokens version = 0; // means not found profile = Profile.NoProfile; bool foundNonSpaceTab = false; bool lookingInMiddle = false; int c; do { if (lookingInMiddle) { notFirstToken = true; // make forward progress by finishing off the current line plus extra new lines if (peek() == '\n' || peek() == '\r') { while (peek() == '\n' || peek() == '\r') get(); } else do { c = get(); } while (c > 0 && c != '\n' && c != '\r'); while (peek() == '\n' || peek() == '\r') get(); if (peek() < 0) return true; } lookingInMiddle = true; // Nominal start, skipping the desktop allowed comments and white space, but tracking if // something else was found for ES: consumeWhitespaceComment(ref foundNonSpaceTab); if (foundNonSpaceTab) versionNotFirst = true; // "#" if (get() != '#') { versionNotFirst = true; continue; } // whitespace do { c = get(); } while (c == ' ' || c == '\t'); // "version" if ( c != 'v' || get() != 'e' || get() != 'r' || get() != 's' || get() != 'i' || get() != 'o' || get() != 'n') { versionNotFirst = true; continue; } // whitespace do { c = get(); } while (c == ' ' || c == '\t'); // version number while (c >= '0' && c <= '9') { version = 10 * version + (c - '0'); c = get(); } if (version == 0) { versionNotFirst = true; continue; } // whitespace while (c == ' ' || c == '\t') c = get(); // profile const int MAX_PROFILE_LENGTH = 13; // not including any 0 var profileString = new char[MAX_PROFILE_LENGTH]; int profileLength; for (profileLength = 0; profileLength < MAX_PROFILE_LENGTH; ++profileLength) { if (c < 0 || c == ' ' || c == '\t' || c == '\n' || c == '\r') break; profileString[profileLength] = (char)c; c = get(); } if (c > 0 && c != ' ' && c != '\t' && c != '\n' && c != '\r') { versionNotFirst = true; continue; } var profileValue = new string(profileString, 0 , profileLength); if (profileLength == 2 && profileValue == "es") profile = Profile.EsProfile; else if (profileLength == 4 && profileValue == "core") profile = Profile.CoreProfile; else if (profileLength == 13 && profileValue == "compatibility") profile = Profile.CompatibilityProfile; return versionNotFirst; } while (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.Collections.Generic; using System.Linq; using System.Reflection.Metadata.Cil.Decoder; using System.Reflection.Metadata.Cil.Visitor; using System.Reflection.Metadata.Ecma335; namespace System.Reflection.Metadata.Cil { /// <summary> /// Class representing a type definition within an assembly. /// </summary> public struct CilTypeDefinition : ICilVisitable { private CilReaders _readers; private TypeDefinition _typeDefinition; private CilTypeLayout _layout; private string _name; private string _fullName; private string _namespace; private IEnumerable<CilMethodDefinition> _methodDefinitions; private Dictionary<int, int> _methodImplementationDictionary; private int _token; private IEnumerable<string> _genericParameters; private IEnumerable<CilField> _fieldDefinitions; private IEnumerable<CilTypeDefinition> _nestedTypes; private IEnumerable<CilCustomAttribute> _customAttributes; private IEnumerable<CilProperty> _properties; private IEnumerable<CilEventDefinition> _events; private CilEntity _baseType; private bool _isBaseTypeInitialized; private bool _isLayoutInitialized; private string _signature; internal static CilTypeDefinition Create(TypeDefinition typeDef, ref CilReaders readers, int token) { CilTypeDefinition type = new CilTypeDefinition(); type._typeDefinition = typeDef; type._token = token; type._readers = readers; type._isBaseTypeInitialized = false; type._isLayoutInitialized = false; return type; } #region Public APIs /// <summary> /// Type full name /// </summary> public string FullName { get { if(_fullName == null) { _fullName = SignatureDecoder.DecodeType(MetadataTokens.TypeDefinitionHandle(_token), _readers.Provider, 0).ToString(false); } return _fullName; } } /// <summary> /// Property that contains the type name. /// </summary> public string Name { get { return CilDecoder.GetCachedValue(_typeDefinition.Name, _readers, ref _name); } } /// <summary> /// Property containing the namespace name. /// </summary> public string Namespace { get { return CilDecoder.GetCachedValue(_typeDefinition.Namespace, _readers ,ref _namespace); } } public string Signature { get { if(_signature == null) { _signature = GetSignature(); } return _signature; } } public bool IsGeneric { get { return GenericParameters.Count() != 0; } } public bool IsNested { get { return !_typeDefinition.GetDeclaringType().IsNil; } } public bool IsInterface { get { return _typeDefinition.BaseType.IsNil; } } public bool HasBaseType { get { return !_typeDefinition.BaseType.IsNil; } } public CilEntity BaseType { get { if (IsInterface) throw new InvalidOperationException("The type definition is an interface, they don't have a base type"); if(!_isBaseTypeInitialized) { _isBaseTypeInitialized = true; _baseType = CilDecoder.DecodeEntityHandle(_typeDefinition.BaseType, ref _readers); } return _baseType; } } public TypeAttributes Attributes { get { return _typeDefinition.Attributes; } } public CilTypeLayout Layout { get { if (!_isLayoutInitialized) { _isLayoutInitialized = true; _layout = new CilTypeLayout(_typeDefinition.GetLayout()); } return _layout; } } public IEnumerable<InterfaceImplementation> InterfaceImplementations { get { throw new NotImplementedException("not implemented Interface Impl on Type Def"); } } public IEnumerable<CilEventDefinition> Events { get { if(_events == null) { _events = GetEvents(); } return _events; } } public IEnumerable<CilProperty> Properties { get { if(_properties == null) { _properties = GetProperties(); } return _properties; } } public IEnumerable<CilTypeDefinition> NestedTypes { get { if(_nestedTypes == null) { _nestedTypes = GetNestedTypes(); } return _nestedTypes; } } public IEnumerable<string> GenericParameters { get { if(_genericParameters == null) { _genericParameters = GetGenericParameters(); } return _genericParameters; } } /// <summary> /// Property containing all the method definitions within a type. /// </summary> public IEnumerable<CilMethodDefinition> MethodDefinitions { get { if (_methodDefinitions == null) { _methodDefinitions = GetMethodDefinitions(); } return _methodDefinitions; } } public IEnumerable<CilField> FieldDefinitions { get { if (_fieldDefinitions == null) { _fieldDefinitions = GetFieldDefinitions(); } return _fieldDefinitions; } } public IEnumerable<CilCustomAttribute> CustomAttributes { get { if(_customAttributes == null) { _customAttributes = GetCustomAttributes(); } return _customAttributes; } } /// <summary> /// Method that returns the token of a method declaration given the method token that overrides it. Returns 0 if the token doesn't represent an overriden method. /// </summary> /// <param name="methodBodyToken">Token of the method body that overrides a declaration.</param> /// <returns>token of the method declaration, 0 if there is no overriding of that method.</returns> public int GetOverridenMethodToken(int methodBodyToken) { MethodImplementationDictionary.TryGetValue(methodBodyToken, out int result); return result; } public void Accept(ICilVisitor visitor) { visitor.Visit(this); } #endregion #region Private Methods private IEnumerable<CilMethodDefinition> GetMethodDefinitions() { var handles = _typeDefinition.GetMethods(); foreach (var handle in handles) { var method = _readers.MdReader.GetMethodDefinition(handle); yield return CilMethodDefinition.Create(method, MetadataTokens.GetToken(handle), ref _readers, this); } } private void PopulateMethodImplementationDictionary() { var implementations = _typeDefinition.GetMethodImplementations(); Dictionary<int, int> dictionary = new Dictionary<int, int>(implementations.Count); foreach (var implementationHandle in implementations) { var implementation = _readers.MdReader.GetMethodImplementation(implementationHandle); int declarationToken = MetadataTokens.GetToken(implementation.MethodDeclaration); int bodyToken = MetadataTokens.GetToken(implementation.MethodBody); dictionary.Add(bodyToken, declarationToken); } _methodImplementationDictionary = dictionary; } private IEnumerable<string> GetGenericParameters() { foreach(var handle in _typeDefinition.GetGenericParameters()) { var parameter = _readers.MdReader.GetGenericParameter(handle); yield return _readers.MdReader.GetString(parameter.Name); } } private IEnumerable<CilField> GetFieldDefinitions() { foreach(var handle in _typeDefinition.GetFields()) { var field = _readers.MdReader.GetFieldDefinition(handle); var token = MetadataTokens.GetToken(handle); yield return CilField.Create(field, token, ref _readers, this); } } private IEnumerable<CilTypeDefinition> GetNestedTypes() { foreach(var handle in _typeDefinition.GetNestedTypes()) { if (handle.IsNil) { continue; } var typeDefinition = _readers.MdReader.GetTypeDefinition(handle); yield return Create(typeDefinition, ref _readers, MetadataTokens.GetToken(handle)); } } private IEnumerable<CilCustomAttribute> GetCustomAttributes() { foreach(var handle in _typeDefinition.GetCustomAttributes()) { var attribute = _readers.MdReader.GetCustomAttribute(handle); yield return new CilCustomAttribute(attribute, ref _readers); } } private IEnumerable<CilProperty> GetProperties() { foreach(var handle in _typeDefinition.GetProperties()) { var property = _readers.MdReader.GetPropertyDefinition(handle); int token = MetadataTokens.GetToken(handle); yield return CilProperty.Create(property, token,ref _readers, this); } } private IEnumerable<CilEventDefinition> GetEvents() { foreach (var handle in _typeDefinition.GetEvents()) { var eventDef = _readers.MdReader.GetEventDefinition(handle); yield return CilEventDefinition.Create(eventDef, MetadataTokens.GetToken(handle), ref _readers, this); } } private string GetSignature() { return string.Empty; } #endregion #region Internal Members internal Dictionary<int, int> MethodImplementationDictionary { get { if(_methodImplementationDictionary == null) { PopulateMethodImplementationDictionary(); } return _methodImplementationDictionary; } } internal int Token { get { return _token; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace NSubstitute.Acceptance.Specs { public class AutoValuesForSubs { private ISample _sample; public class PureVirtualClass { public virtual void Foo() { } } public class NonVirtualClass { public void Bar() { } } public sealed class SealedClass { } delegate ISample SampleFactory(); public interface ISample { int[] GetNumbers(); IEnumerable<object> GetObjects(); string Name { get; set; } List<string> ListOfStrings { get; set; } int? GetNullableNumber(); PureVirtualClass VirtualClass { get; set; } NonVirtualClass NonVirtualClass { get; set; } SealedClass SealedClass { get; set; } IQueryable<int> Queryable(); } [SetUp] public void SetUp() { _sample = Substitute.For<ISample>(); } [Test] public void Should_auto_return_empty_array() { Assert.That(_sample.GetNumbers().Length, Is.EqualTo(0)); } [Test] public void Should_auto_return_empty_enumerable() { Assert.That(_sample.GetObjects(), Is.Not.Null); Assert.That(_sample.GetObjects().Count(), Is.EqualTo(0)); } [Test] public void Should_auto_return_empty_string() { Assert.That(_sample.Name.Length, Is.EqualTo(0)); } [Test] public void Should_return_null_for_nullables() { Assert.That(_sample.GetNullableNumber(), Is.Null); } [Test] public void Should_return_same_empty_value_for_auto_values_for_reference_types() { var autoArrayValue = _sample.GetNumbers(); Assert.That(_sample.GetNumbers(), Is.SameAs(autoArrayValue)); } [Test] public void Should_return_substitute_for_pure_virtual_class() { Assert.That(_sample.VirtualClass, Is.Not.Null); } [Test] public void Should_return_default_value_for_non_virtual_class() { Assert.That(_sample.NonVirtualClass, Is.Null); } [Test] public void Should_return_default_value_for_sealed_class() { Assert.That(_sample.SealedClass, Is.Null); } [Test] [Pending, Explicit] public void Should_auto_return_empty_string_list() { Assert.That(_sample.ListOfStrings, Is.Not.Null); Assert.That(_sample.ListOfStrings.Count(), Is.EqualTo(0)); } [Test] public void Should_auto_return_a_substitute_from_a_function_that_returns_an_interface() { var x = Substitute.For<Func<ISample>>(); var returnedFromFunc = x(); Assert.That(returnedFromFunc, Is.Not.Null); AssertObjectIsASubstitute(returnedFromFunc); } [Test] public void Should_auto_return_an_empty_string_from_a_func_that_returns_a_string() { var x = Substitute.For<Func<ISample, string>>(); Assert.That(x(_sample).Length, Is.EqualTo(0)); } #if NET45 || NETSTANDARD1_5 [Test] public void Should_auto_return_for_iqueryable() { var sample = Substitute.For<ISample>(); Assert.IsEmpty(sample.Queryable().Select(x => x + 1).ToList()); Assert.NotNull(sample.Queryable().Expression); } #endif [Test] public void Should_auto_return_a_substitute_from_a_func_that_returns_a_pure_virtual_class() { var x = Substitute.For<Func<PureVirtualClass>>(); var returnedFromFunc = x(); Assert.That(returnedFromFunc, Is.Not.Null); AssertObjectIsASubstitute(returnedFromFunc); } [Test] public void Should_not_auto_return_a_substitute_from_a_func_that_returns_a_non_virtual_class() { var x = Substitute.For<Func<NonVirtualClass>>(); var returnedFromFunc = x(); Assert.That(returnedFromFunc, Is.Null); } [Test] public void Should_auto_return_a_substitute_from_a_delegate_that_returns_an_interface() { var x = Substitute.For<SampleFactory>(); var returnedFromFunc = x(); Assert.That(returnedFromFunc, Is.Not.Null); AssertObjectIsASubstitute(returnedFromFunc); } #if (NET4 || NET45 || NETSTANDARD1_5) [Test] public void Should_auto_return_a_value_from_a_task() { var sub = Substitute.For<IFooWithTasks>(); Assert.That(sub.GetIntAsync().Result, Is.EqualTo(0)); } [Test] public void Should_auto_return_an_autosub_from_a_task() { var sub = Substitute.For<IFooWithTasks>(); var sample = sub.GetSample().Result; AssertObjectIsASubstitute(sample); sample.Name = "test"; Assert.That(sample.Name, Is.EqualTo("test")); } public interface IFooWithTasks { System.Threading.Tasks.Task<ISample> GetSample(); System.Threading.Tasks.Task<int> GetIntAsync(); } #endif #if NET45 || NETSTANDARD1_5 [Test] public void Should_auto_return_an_observable() { var sub = Substitute.For<IFooWithObservable>(); int sample = -42; sub.GetInts().Subscribe(new AnonymousObserver<int>(x => sample = x)); Assert.That(sample, Is.EqualTo(0)); } [Test] public void Should_auto_return_an_autosub_from_an_observable() { var sub = Substitute.For<IFooWithObservable>(); ISample sample = null; sub.GetSamples().Subscribe(new AnonymousObserver<ISample>(x => sample = x)); AssertObjectIsASubstitute(sample); sample.Name = "test"; Assert.That(sample.Name, Is.EqualTo("test")); } [Test] public void Multiple_calls_to_observable_method() { var sub = Substitute.For<IFooWithObservable>(); ISample sample1 = null; ISample sample2 = null; sub.GetSamples().Subscribe(new AnonymousObserver<ISample>(x => sample1 = x)); sub.GetSamples().Subscribe(new AnonymousObserver<ISample>(x => sample2 = x)); AssertObjectIsASubstitute(sample1); AssertObjectIsASubstitute(sample2); Assert.That(sample1, Is.SameAs(sample2)); } public interface IFooWithObservable { IObservable<int> GetInts(); IObservable<ISample> GetSamples(); } //Copied from NSubstitute.Specs.AnonymousObserver (PR #137) private class AnonymousObserver<T> : IObserver<T> { Action<T> _onNext; Action<Exception> _onError; Action _onCompleted; public AnonymousObserver(Action<T> onNext, Action<Exception> onError = null, Action onCompleted = null) { _onNext = onNext ?? (_ => { }); _onError = onError ?? (_ => { }); _onCompleted = onCompleted ?? (() => {}); } public void OnNext(T value) { _onNext(value); } public void OnError(Exception error) { _onError(error); } public void OnCompleted() { _onCompleted(); } } #endif private static void AssertObjectIsASubstitute<T>(T obj) where T : class { Assert.That(obj.ReceivedCalls(), Is.Empty); } } }
// // PreferenceDialog.cs // // Author: // Stephane Delcroix <[email protected]> // Ruben Vermeersch <[email protected]> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2006-2010 Stephane Delcroix // Copyright (C) 2010 Ruben Vermeersch // // 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.Linq; using FSpot.Settings; using Gtk; using Mono.Unix; using Hyena; namespace FSpot.UI.Dialog { public class PreferenceDialog : BuilderDialog { #pragma warning disable 649 [GtkBeans.Builder.Object] FileChooserButton photosdir_chooser; [GtkBeans.Builder.Object] RadioButton writemetadata_radio; [GtkBeans.Builder.Object] RadioButton dontwrite_radio; [GtkBeans.Builder.Object] CheckButton always_sidecar_check; [GtkBeans.Builder.Object] ComboBox theme_combo; [GtkBeans.Builder.Object] ComboBox screenprofile_combo; [GtkBeans.Builder.Object] ComboBox printprofile_combo; #pragma warning restore 649 #region public API (ctor) public PreferenceDialog (Window parent) : base ("PreferenceDialog.ui", "preference_dialog") { TransientFor = parent; //Photos Folder photosdir_chooser.SetCurrentFolderUri (FSpotConfiguration.PhotoUri); SafeUri storage_path = new SafeUri (Preferences.Get<string> (Preferences.StoragePath)); //If the user has set a photo directory on the commandline then don't let it be changed in Preferences if (storage_path.Equals(FSpotConfiguration.PhotoUri)) photosdir_chooser.CurrentFolderChanged += HandlePhotosdirChanged; else photosdir_chooser.Sensitive = false; //Write Metadata LoadPreference (Preferences.MetadataEmbedInImage); LoadPreference (Preferences.MetadataAlwaysUseSidecar); //Screen profile ListStore sprofiles = new ListStore (typeof (string), typeof (int)); sprofiles.AppendValues (Catalog.GetString ("None"), 0); if (FSpot.ColorManagement.XProfile != null) sprofiles.AppendValues (Catalog.GetString ("System profile"), -1); sprofiles.AppendValues (null, 0); //Pick the display profiles from the full list, avoid _x_profile_ var dprofs = from profile in FSpot.ColorManagement.Profiles where (profile.Value.DeviceClass == Cms.IccProfileClass.Display && profile.Key != "_x_profile_") select profile; foreach (var p in dprofs) sprofiles.AppendValues (p.Key, 1); CellRendererText profilecellrenderer = new CellRendererText (); profilecellrenderer.Ellipsize = Pango.EllipsizeMode.End; screenprofile_combo.Model = sprofiles; screenprofile_combo.PackStart (profilecellrenderer, true); screenprofile_combo.RowSeparatorFunc = ProfileSeparatorFunc; screenprofile_combo.SetCellDataFunc (profilecellrenderer, ProfileCellFunc); LoadPreference (Preferences.ColorManagementDisplayProfile); //Print profile ListStore pprofiles = new ListStore (typeof (string), typeof (int)); pprofiles.AppendValues (Catalog.GetString ("None"), 0); pprofiles.AppendValues (null, 0); var pprofs = from profile in FSpot.ColorManagement.Profiles where (profile.Value.DeviceClass == Cms.IccProfileClass.Output && profile.Key != "_x_profile_") select profile; foreach (var p in pprofs) pprofiles.AppendValues (p.Key, 1); printprofile_combo.Model = pprofiles; printprofile_combo.PackStart (profilecellrenderer, true); printprofile_combo.RowSeparatorFunc = ProfileSeparatorFunc; printprofile_combo.SetCellDataFunc (profilecellrenderer, ProfileCellFunc); LoadPreference (Preferences.ColorManagementDisplayOutputProfile); //Theme chooser ListStore themes = new ListStore (typeof (string), typeof (string)); themes.AppendValues (Catalog.GetString ("Standard theme"), null); themes.AppendValues (null, null); //Separator string gtkrc = System.IO.Path.Combine ("gtk-2.0", "gtkrc"); string [] search = {System.IO.Path.Combine (FSpotConfiguration.HomeDirectory, ".themes"), "/usr/share/themes"}; foreach (string path in search) if (Directory.Exists (path)) foreach (string dir in Directory.GetDirectories (path)) if (File.Exists (System.IO.Path.Combine (dir, gtkrc))) themes.AppendValues (System.IO.Path.GetFileName (dir), System.IO.Path.Combine (dir, gtkrc)); CellRenderer themecellrenderer = new CellRendererText (); theme_combo.Model = themes; theme_combo.PackStart (themecellrenderer, true); theme_combo.RowSeparatorFunc = ThemeSeparatorFunc; theme_combo.SetCellDataFunc (themecellrenderer, ThemeCellFunc); LoadPreference (Preferences.GtkRc); ConnectEvents (); } #endregion #region preferences void OnPreferencesChanged (object sender, NotifyEventArgs args) { LoadPreference (args.Key); } void LoadPreference (string key) { string pref; int i; switch (key) { case Preferences.StoragePath: photosdir_chooser.SetCurrentFolder (Preferences.Get<string> (key)); break; case Preferences.MetadataEmbedInImage: bool embed_active = Preferences.Get<bool> (key); if (writemetadata_radio.Active != embed_active) { if (embed_active) { writemetadata_radio.Active = true; } else { dontwrite_radio.Active = true; } } always_sidecar_check.Sensitive = embed_active; break; case Preferences.MetadataAlwaysUseSidecar: bool always_use_sidecar = Preferences.Get<bool> (key); always_sidecar_check.Active = always_use_sidecar; break; case Preferences.GtkRc: pref = Preferences.Get<string> (key); if (string.IsNullOrEmpty (pref)) { theme_combo.Active = 0; break; } i = 0; foreach (object [] row in theme_combo.Model as ListStore) { if (pref == (string)row [1]) { theme_combo.Active = i; break; } i++; } break; case Preferences.ColorManagementDisplayProfile: pref = Preferences.Get<string> (key); if (string.IsNullOrEmpty (pref)) { screenprofile_combo.Active = 0; break; } if (pref == "_x_profile_" && FSpot.ColorManagement.XProfile != null) { screenprofile_combo.Active = 1; break; } i = 0; foreach (object [] row in screenprofile_combo.Model as ListStore) { if (pref == (string)row [0]) { screenprofile_combo.Active = i; break; } i++; } break; case Preferences.ColorManagementDisplayOutputProfile: pref = Preferences.Get<string> (key); if (string.IsNullOrEmpty (pref)) { printprofile_combo.Active = 0; break; } i = 0; foreach (object [] row in printprofile_combo.Model as ListStore) { if (pref == (string)row [0]) { printprofile_combo.Active = i; break; } i++; } break; } } #endregion #region event handlers void ConnectEvents () { Preferences.SettingChanged += OnPreferencesChanged; screenprofile_combo.Changed += HandleScreenProfileComboChanged; printprofile_combo.Changed += HandlePrintProfileComboChanged; theme_combo.Changed += HandleThemeComboChanged; writemetadata_radio.Toggled += HandleWritemetadataGroupChanged; always_sidecar_check.Toggled += HandleAlwaysSidecareCheckToggled; } void HandlePhotosdirChanged (object sender, EventArgs args) { photosdir_chooser.CurrentFolderChanged -= HandlePhotosdirChanged; Preferences.Set (Preferences.StoragePath, photosdir_chooser.Filename); photosdir_chooser.CurrentFolderChanged += HandlePhotosdirChanged; FSpotConfiguration.PhotoUri = new SafeUri (photosdir_chooser.Uri, true); } void HandleWritemetadataGroupChanged (object sender, EventArgs args) { Preferences.Set (Preferences.MetadataEmbedInImage, writemetadata_radio.Active); } void HandleAlwaysSidecareCheckToggled (object sender, EventArgs args) { Preferences.Set (Preferences.MetadataAlwaysUseSidecar, always_sidecar_check.Active); } void HandleThemeComboChanged (object sender, EventArgs e) { ComboBox combo = sender as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) { string gtkrc = (string)combo.Model.GetValue (iter, 1); if (!string.IsNullOrEmpty (gtkrc)) Preferences.Set (Preferences.GtkRc, gtkrc); else Preferences.Set (Preferences.GtkRc, string.Empty); } Gtk.Rc.DefaultFiles = FSpotConfiguration.DefaultRcFiles; Gtk.Rc.AddDefaultFile (Preferences.Get<string> (Preferences.GtkRc)); Gtk.Rc.ReparseAllForSettings (Gtk.Settings.Default, true); } void HandleScreenProfileComboChanged (object sender, EventArgs e) { ComboBox combo = sender as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) { switch ((int)combo.Model.GetValue (iter, 1)) { case 0: Preferences.Set (Preferences.ColorManagementDisplayProfile, string.Empty); break; case -1: Preferences.Set (Preferences.ColorManagementDisplayProfile, "_x_profile_"); break; case 1: Preferences.Set (Preferences.ColorManagementDisplayProfile, (string)combo.Model.GetValue (iter, 0)); break; } } } void HandlePrintProfileComboChanged (object sender, EventArgs e) { ComboBox combo = sender as ComboBox; if (combo == null) return; TreeIter iter; if (combo.GetActiveIter (out iter)) { switch ((int)combo.Model.GetValue (iter, 1)) { case 0: Preferences.Set (Preferences.ColorManagementDisplayOutputProfile, string.Empty); break; case 1: Preferences.Set (Preferences.ColorManagementDisplayOutputProfile, (string)combo.Model.GetValue (iter, 0)); break; } } } #endregion #region Gtk widgetry void ThemeCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 0); (cell as CellRendererText).Text = name; } bool ThemeSeparatorFunc (TreeModel tree_model, TreeIter iter) { return tree_model.GetValue (iter, 0) == null; } void ProfileCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter) { string name = (string)tree_model.GetValue (iter, 0); (cell as CellRendererText).Text = name; } bool ProfileSeparatorFunc (TreeModel tree_model, TreeIter iter) { return tree_model.GetValue (iter, 0) == null; } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Numerics; using SharpGLTF.IO; using SharpGLTF.Schema2; using SkiaSharp; using ValveResourceFormat.Blocks; using ValveResourceFormat.ResourceTypes.ModelAnimation; using ValveResourceFormat.Serialization; using ValveResourceFormat.Utils; namespace ValveResourceFormat.IO { using static VBIB; using VMaterial = ResourceTypes.Material; using VMesh = ResourceTypes.Mesh; using VModel = ResourceTypes.Model; using VWorldNode = ResourceTypes.WorldNode; using VWorld = ResourceTypes.World; using VEntityLump = ResourceTypes.EntityLump; using VAnimation = ResourceTypes.ModelAnimation.Animation; public class GltfModelExporter { private const string GENERATOR = "VRF - https://vrf.steamdb.info/"; // NOTE: Swaps Y and Z axes - gltf up axis is Y (source engine up is Z) // Also divides by 100, gltf units are in meters, source engine units are in inches // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#coordinate-system-and-units private readonly Matrix4x4 TRANSFORMSOURCETOGLTF = Matrix4x4.CreateScale(0.0254f) * Matrix4x4.CreateFromYawPitchRoll(0, (float)Math.PI / -2f, (float)Math.PI / -2f); public IProgress<string> ProgressReporter { get; set; } public IFileLoader FileLoader { get; set; } public bool ExportMaterials { get; set; } = true; private string DstDir; private readonly IDictionary<string, Node> LoadedUnskinnedMeshDictionary = new Dictionary<string, Node>(); /// <summary> /// Export a Valve VWRLD to GLTF. /// </summary> /// <param name="resourceName">The name of the resource being exported.</param> /// <param name="fileName">Target file name.</param> /// <param name="world">The world resource to export.</param> public void ExportToFile(string resourceName, string fileName, VWorld world) { if (FileLoader == null) { throw new InvalidOperationException(nameof(FileLoader) + " must be set first."); } DstDir = Path.GetDirectoryName(fileName); var exportedModel = CreateModelRoot(resourceName, out var scene); // First the WorldNodes foreach (var worldNodeName in world.GetWorldNodeNames()) { if (worldNodeName == null) { continue; } var worldResource = FileLoader.LoadFile(worldNodeName + ".vwnod_c"); if (worldResource == null) { continue; } var worldNode = (VWorldNode)worldResource.DataBlock; var worldNodeModels = LoadWorldNodeModels(worldNode); foreach (var (Model, Name, Transform) in worldNodeModels) { var meshes = LoadModelMeshes(Model, Name); for (var i = 0; i < meshes.Length; i++) { var node = AddMeshNode(exportedModel, scene, Model, meshes[i].Name, meshes[i].Mesh, Model.GetSkeleton(i)); if (node == null) { continue; } // Swap Rotate upright, scale inches to meters. node.WorldMatrix = Transform * TRANSFORMSOURCETOGLTF; } } } // Then the Entities foreach (var lumpName in world.GetEntityLumpNames()) { if (lumpName == null) { continue; } var entityLumpResource = FileLoader.LoadFile(lumpName + "_c"); if (entityLumpResource == null) { continue; } var entityLump = (VEntityLump)entityLumpResource.DataBlock; LoadEntityMeshes(exportedModel, scene, entityLump); } WriteModelFile(exportedModel, fileName); } private void LoadEntityMeshes(ModelRoot exportedModel, Scene scene, VEntityLump entityLump) { foreach (var entity in entityLump.GetEntities()) { var modelName = entity.GetProperty<string>("model"); if (string.IsNullOrEmpty(modelName)) { // Only worrying about models for now continue; // TODO: Think about adding lights with KHR_lights_punctual } var modelResource = FileLoader.LoadFile(modelName + "_c"); if (modelResource == null) { continue; } // TODO: skybox/skydome var model = (VModel)modelResource.DataBlock; var skinName = entity.GetProperty<string>("skin"); if (skinName == "0" || skinName == "default") { skinName = null; } var transform = EntityTransformHelper.CalculateTransformationMatrix(entity); // Add meshes and their skeletons var meshes = LoadModelMeshes(model, Path.GetFileNameWithoutExtension(modelName)); for (var i = 0; i < meshes.Length; i++) { var meshName = meshes[i].Name; if (skinName != null) { meshName += "." + skinName; } var node = AddMeshNode(exportedModel, scene, model, meshName, meshes[i].Mesh, model.GetSkeleton(i), skinName != null ? GetSkinPathFromModel(model, skinName) : null); if (node == null) { continue; } // Swap Rotate upright, scale inches to meters. node.WorldMatrix = transform * TRANSFORMSOURCETOGLTF; } } foreach (var childEntityName in entityLump.GetChildEntityNames()) { if (childEntityName == null) { continue; } var childEntityLumpResource = FileLoader.LoadFile(childEntityName + "_c"); if (childEntityLumpResource == null) { continue; } var childEntityLump = (VEntityLump)childEntityLumpResource.DataBlock; LoadEntityMeshes(exportedModel, scene, childEntityLump); } } private static string GetSkinPathFromModel(VModel model, string skinName) { var materialGroupForSkin = model.Data.GetArray<IKeyValueCollection>("m_materialGroups") .ToList() .SingleOrDefault(m => m.GetProperty<string>("m_name") == skinName); if (materialGroupForSkin == null) { return null; } // Given these are at the model level, and otherwise pull materials from drawcalls // on the mesh, not sure how they correlate if there's more than one here // So just take the first one and hope for the best return materialGroupForSkin.GetArray<string>("m_materials")[0]; } /// <summary> /// Export a Valve VWNOD to GLTF. /// </summary> /// <param name="resourceName">The name of the resource being exported.</param> /// <param name="fileName">Target file name.</param> /// <param name="worldNode">The worldNode resource to export.</param> public void ExportToFile(string resourceName, string fileName, VWorldNode worldNode) { if (FileLoader == null) { throw new InvalidOperationException(nameof(FileLoader) + " must be set first."); } DstDir = Path.GetDirectoryName(fileName); var exportedModel = CreateModelRoot(resourceName, out var scene); var worldNodeModels = LoadWorldNodeModels(worldNode); foreach (var (Model, Name, Transform) in worldNodeModels) { var meshes = LoadModelMeshes(Model, Name); for (var i = 0; i < meshes.Length; i++) { var node = AddMeshNode(exportedModel, scene, Model, meshes[i].Name, meshes[i].Mesh, Model.GetSkeleton(i)); if (node == null) { continue; } // Swap Rotate upright, scale inches to meters, after local transform. node.WorldMatrix = Transform * TRANSFORMSOURCETOGLTF; } } WriteModelFile(exportedModel, fileName); } private IList<(VModel Model, string ModelName, Matrix4x4 Transform)> LoadWorldNodeModels(VWorldNode worldNode) { var sceneObjects = worldNode.Data.GetArray("m_sceneObjects"); var models = new List<(VModel, string, Matrix4x4)>(); foreach (var sceneObject in sceneObjects) { var renderableModel = sceneObject.GetProperty<string>("m_renderableModel"); if (renderableModel == null) { continue; } var modelResource = FileLoader.LoadFile(renderableModel + "_c"); if (modelResource == null) { continue; } var model = (VModel)modelResource.DataBlock; var matrix = sceneObject.GetArray("m_vTransform").ToMatrix4x4(); models.Add((model, Path.GetFileNameWithoutExtension(renderableModel), matrix)); } return models; } /// <summary> /// Export a Valve VMDL to GLTF. /// </summary> /// <param name="resourceName">The name of the resource being exported.</param> /// <param name="fileName">Target file name.</param> /// <param name="model">The model resource to export.</param> public void ExportToFile(string resourceName, string fileName, VModel model) { if (FileLoader == null) { throw new InvalidOperationException(nameof(FileLoader) + " must be set first."); } DstDir = Path.GetDirectoryName(fileName); var exportedModel = CreateModelRoot(resourceName, out var scene); // Add meshes and their skeletons var meshes = LoadModelMeshes(model, resourceName); for (var i = 0; i < meshes.Length; i++) { var node = AddMeshNode(exportedModel, scene, model, meshes[i].Name, meshes[i].Mesh, model.GetSkeleton(i)); if (node == null) { continue; } // Swap Rotate upright, scale inches to meters. node.WorldMatrix = TRANSFORMSOURCETOGLTF; } WriteModelFile(exportedModel, fileName); } /// <summary> /// Create a combined list of referenced and embedded meshes. Importantly retains the /// refMeshes order so it can be used for getting skeletons. /// </summary> /// <param name="model">The model to get the meshes from.</param> /// <returns>A tuple of meshes and their names.</returns> private (VMesh Mesh, string Name)[] LoadModelMeshes(VModel model, string modelName) { var refMeshes = model.GetRefMeshes().ToArray(); var meshes = new (VMesh, string)[refMeshes.Length]; var embeddedMeshIndex = 0; var embeddedMeshes = model.GetEmbeddedMeshes().ToArray(); for (var i = 0; i < meshes.Length; i++) { var meshReference = refMeshes[i]; if (string.IsNullOrEmpty(meshReference)) { // If refmesh is null, take an embedded mesh meshes[i] = (embeddedMeshes[embeddedMeshIndex++], $"{modelName}.Embedded.{embeddedMeshIndex}"); } else { // Load mesh from file var meshResource = FileLoader.LoadFile(meshReference + "_c"); if (meshResource == null) { continue; } var nodeName = Path.GetFileNameWithoutExtension(meshReference); var mesh = new VMesh(meshResource); meshes[i] = (mesh, nodeName); } } return meshes; } /// <summary> /// Export a Valve VMESH to Gltf. /// </summary> /// <param name="resourceName">The name of the resource being exported.</param> /// <param name="fileName">Target file name.</param> /// <param name="mesh">The mesh resource to export.</param> public void ExportToFile(string resourceName, string fileName, VMesh mesh) { DstDir = Path.GetDirectoryName(fileName); var exportedModel = CreateModelRoot(resourceName, out var scene); var name = Path.GetFileName(resourceName); var node = AddMeshNode(exportedModel, scene, null, name, mesh, null); if (node != null) { // Swap Rotate upright, scale inches to meters. node.WorldMatrix = TRANSFORMSOURCETOGLTF; } WriteModelFile(exportedModel, fileName); } private Node AddMeshNode(ModelRoot exportedModel, Scene scene, VModel model, string name, VMesh mesh, Skeleton skeleton, string skinMaterialPath = null) { if (mesh.GetData().GetArray("m_sceneObjects").Length == 0) { return null; } if (LoadedUnskinnedMeshDictionary.TryGetValue(name, out var existingNode)) { // Make a new node that uses the existing mesh var newNode = scene.CreateNode(name); newNode.Mesh = existingNode.Mesh; return newNode; } var hasJoints = skeleton != null && skeleton.AnimationTextureSize > 0; var exportedMesh = CreateGltfMesh(name, mesh, exportedModel, hasJoints, skinMaterialPath); var hasVertexJoints = exportedMesh.Primitives.All(primitive => primitive.GetVertexAccessor("JOINTS_0") != null); if (hasJoints && hasVertexJoints && model != null) { var skeletonNode = scene.CreateNode(name); var joints = CreateGltfSkeleton(skeleton, skeletonNode); scene.CreateNode(name) .WithSkinnedMesh(exportedMesh, Matrix4x4.Identity, joints); // Add animations var animations = GetAllAnimations(model); foreach (var animation in animations) { var exportedAnimation = exportedModel.CreateAnimation(animation.Name); var rotationDict = new Dictionary<string, Dictionary<float, Quaternion>>(); var translationDict = new Dictionary<string, Dictionary<float, Vector3>>(); var time = 0f; foreach (var frame in animation.Frames) { foreach (var boneFrame in frame.Bones) { var bone = boneFrame.Key; if (!rotationDict.ContainsKey(bone)) { rotationDict[bone] = new Dictionary<float, Quaternion>(); translationDict[bone] = new Dictionary<float, Vector3>(); } rotationDict[bone].Add(time, boneFrame.Value.Angle); translationDict[bone].Add(time, boneFrame.Value.Position); } time += 1 / animation.Fps; } foreach (var bone in rotationDict.Keys) { var jointNode = joints.FirstOrDefault(n => n.Name == bone); if (jointNode != null) { exportedAnimation.CreateRotationChannel(jointNode, rotationDict[bone], true); exportedAnimation.CreateTranslationChannel(jointNode, translationDict[bone], true); } } } return skeletonNode; } var node = scene.CreateNode(name).WithMesh(exportedMesh); LoadedUnskinnedMeshDictionary.Add(name, node); return node; } private static ModelRoot CreateModelRoot(string resourceName, out Scene scene) { var exportedModel = ModelRoot.CreateModel(); exportedModel.Asset.Generator = GENERATOR; scene = exportedModel.UseScene(Path.GetFileName(resourceName)); return exportedModel; } private static void WriteModelFile(ModelRoot exportedModel, string filePath) { var settings = new WriteSettings(); settings.ImageWriting = ResourceWriteMode.SatelliteFile; settings.ImageWriteCallback = ImageWriteCallback; settings.JsonIndented = true; // See https://github.com/KhronosGroup/glTF/blob/0bc36d536946b13c4807098f9cf62ddff738e7a5/specification/2.0/README.md#buffers-and-buffer-views // Disable merging buffers if the buffer size is over 1GiB, otherwise this will // cause SharpGLTF to run past the int32 limitation and crash. var totalSize = exportedModel.LogicalBuffers.Sum(buffer => (long)buffer.Content.Length); settings.MergeBuffers = totalSize <= 1_074_000_000; if (!settings.MergeBuffers) { throw new NotSupportedException("VRF does not properly support big model (>1GiB) exports yet due to glTF limitations. See https://github.com/SteamDatabase/ValveResourceFormat/issues/379"); } exportedModel.Save(filePath, settings); } private static string ImageWriteCallback(WriteContext ctx, string uri, SharpGLTF.Memory.MemoryImage image) { if (File.Exists(image.SourcePath)) { // image.SourcePath is an absolute path, we must make it relative to ctx.CurrentDirectory var currDir = ctx.CurrentDirectory.FullName; // if the shared texture can be reached by the model in its directory, reuse the texture. if (image.SourcePath.StartsWith(currDir, StringComparison.OrdinalIgnoreCase)) { // we've found the shared texture!, return the uri relative to the model: return Path.GetFileName(image.SourcePath); } } // we were unable to reuse the shared texture, // default to write our own texture. image.SaveToFile(Path.Combine(ctx.CurrentDirectory.FullName, uri)); return uri; } private Mesh CreateGltfMesh(string meshName, VMesh vmesh, ModelRoot model, bool includeJoints, string skinMaterialPath = null) { ProgressReporter?.Report($"Creating mesh: {meshName}"); var data = vmesh.GetData(); var vbib = vmesh.VBIB; var mesh = model.CreateMesh(meshName); mesh.Name = meshName; foreach (var sceneObject in data.GetArray("m_sceneObjects")) { foreach (var drawCall in sceneObject.GetArray("m_drawCalls")) { var vertexBufferInfo = drawCall.GetArray("m_vertexBuffers")[0]; // In what situation can we have more than 1 vertex buffer per draw call? var vertexBufferIndex = (int)vertexBufferInfo.GetIntegerProperty("m_hBuffer"); var vertexBuffer = vbib.VertexBuffers[vertexBufferIndex]; var indexBufferInfo = drawCall.GetSubCollection("m_indexBuffer"); var indexBufferIndex = (int)indexBufferInfo.GetIntegerProperty("m_hBuffer"); var indexBuffer = vbib.IndexBuffers[indexBufferIndex]; // Create one primitive per draw call var primitive = mesh.CreatePrimitive(); // Avoid duplicate attribute names var attributeCounters = new Dictionary<string, int>(); // Set vertex attributes foreach (var attribute in vertexBuffer.InputLayoutFields) { attributeCounters.TryGetValue(attribute.SemanticName, out var attributeCounter); attributeCounters[attribute.SemanticName] = attributeCounter + 1; var accessorName = GetAccessorName(attribute.SemanticName, attributeCounter); var buffer = ReadAttributeBuffer(vertexBuffer, attribute); var numComponents = buffer.Length / vertexBuffer.ElementCount; if (attribute.SemanticName == "BLENDINDICES") { if (!includeJoints) { continue; } var byteBuffer = buffer.Select(f => (byte)f).ToArray(); var rawBufferData = new byte[buffer.Length]; System.Buffer.BlockCopy(byteBuffer, 0, rawBufferData, 0, rawBufferData.Length); var bufferView = mesh.LogicalParent.UseBufferView(rawBufferData); var accessor = mesh.LogicalParent.CreateAccessor(); accessor.SetVertexData(bufferView, 0, buffer.Length / 4, DimensionType.VEC4, EncodingType.UNSIGNED_BYTE); primitive.SetVertexAccessor(accessorName, accessor); continue; } if (attribute.SemanticName == "NORMAL" && VMesh.IsCompressedNormalTangent(drawCall)) { var vectors = ToVector4Array(buffer); var (normals, tangents) = DecompressNormalTangents(vectors); primitive.WithVertexAccessor("NORMAL", normals); primitive.WithVertexAccessor("TANGENT", tangents); continue; } if (attribute.SemanticName == "TEXCOORD" && numComponents != 2) { // We are ignoring some data, but non-2-component UVs cause failures in gltf consumers continue; } if (attribute.SemanticName == "BLENDWEIGHT" && numComponents != 4) { Console.Error.WriteLine($"This model has {attribute.SemanticName} with {numComponents} components, which in unsupported."); continue; } switch (numComponents) { case 4: { var vectors = ToVector4Array(buffer); // dropship.vmdl in HL:A has a tanget with value of <0, -0, 0> if (attribute.SemanticName == "NORMAL" || attribute.SemanticName == "TANGENT") { vectors = FixZeroLengthVectors(vectors); } primitive.WithVertexAccessor(accessorName, vectors); break; } case 3: { var vectors = ToVector3Array(buffer); // dropship.vmdl in HL:A has a normal with value of <0, 0, 0> if (attribute.SemanticName == "NORMAL" || attribute.SemanticName == "TANGENT") { vectors = FixZeroLengthVectors(vectors); } primitive.WithVertexAccessor(accessorName, vectors); break; } case 2: { var vectors = ToVector2Array(buffer); primitive.WithVertexAccessor(accessorName, vectors); break; } case 1: { primitive.WithVertexAccessor(accessorName, buffer); break; } default: throw new NotImplementedException($"Attribute \"{attribute.SemanticName}\" has {numComponents} components"); } } // For some reason soruce models can have joints but no weights, check if that is the case var jointAccessor = primitive.GetVertexAccessor("JOINTS_0"); if (jointAccessor != null && primitive.GetVertexAccessor("WEIGHTS_0") == null) { // If this occurs, give default weights var defaultWeights = Enumerable.Repeat(Vector4.UnitX, jointAccessor.Count).ToList(); primitive.WithVertexAccessor("WEIGHTS_0", defaultWeights); } // Set index buffer var startIndex = (int)drawCall.GetIntegerProperty("m_nStartIndex"); var indexCount = (int)drawCall.GetIntegerProperty("m_nIndexCount"); var indices = ReadIndices(indexBuffer, startIndex, indexCount); string primitiveType = drawCall.GetProperty<object>("m_nPrimitiveType") switch { string primitiveTypeString => primitiveTypeString, byte primitiveTypeByte => (primitiveTypeByte == 5) ? "RENDER_PRIM_TRIANGLES" : ("UNKNOWN_" + primitiveTypeByte), _ => throw new NotImplementedException("Unknown PrimitiveType in drawCall!") }; switch (primitiveType) { case "RENDER_PRIM_TRIANGLES": primitive.WithIndicesAccessor(PrimitiveType.TRIANGLES, indices); break; default: throw new NotImplementedException("Unknown PrimitiveType in drawCall! (" + primitiveType + ")"); } // Add material if (!ExportMaterials) { continue; } var materialPath = skinMaterialPath ?? drawCall.GetProperty<string>("m_material") ?? drawCall.GetProperty<string>("m_pMaterial"); var materialNameTrimmed = Path.GetFileNameWithoutExtension(materialPath); // Check if material already exists - makes an assumption that if material has the same name it is a duplicate var existingMaterial = model.LogicalMaterials.Where(m => m.Name == materialNameTrimmed).SingleOrDefault(); if (existingMaterial != null) { ProgressReporter?.Report($"Found existing material: {materialNameTrimmed}"); primitive.Material = existingMaterial; continue; } ProgressReporter?.Report($"Loading material: {materialPath}"); var materialResource = FileLoader.LoadFile(materialPath + "_c"); if (materialResource == null) { continue; } var renderMaterial = (VMaterial)materialResource.DataBlock; var bestMaterial = GenerateGLTFMaterialFromRenderMaterial(renderMaterial, model, materialNameTrimmed); primitive.WithMaterial(bestMaterial); } } return mesh; } private Node[] CreateGltfSkeleton(Skeleton skeleton, Node skeletonNode) { var joints = new List<(Node Node, List<int> Indices)>(); foreach (var root in skeleton.Roots) { joints.AddRange(CreateBonesRecursive(root, skeletonNode)); } var animationJoints = joints.Where(j => j.Indices.Any()).ToList(); var numJoints = animationJoints.Any() ? animationJoints.Where(j => j.Indices.Any()).Max(j => j.Indices.Max()) : 0; var result = new Node[numJoints + 1]; foreach (var joint in animationJoints) { foreach (var index in joint.Indices) { result[index] = joint.Node; } } // Fill null indices with some dummy node for (var i = 0; i < numJoints + 1; i++) { result[i] ??= skeletonNode.CreateNode(); } return result; } private IEnumerable<(Node Node, List<int> Indices)> CreateBonesRecursive(Bone bone, Node parent) { var node = parent.CreateNode(bone.Name) .WithLocalTransform(bone.BindPose); // Recurse into children return bone.Children .SelectMany(child => CreateBonesRecursive(child, node)) .Append((node, bone.SkinIndices)); } private Material GenerateGLTFMaterialFromRenderMaterial(VMaterial renderMaterial, ModelRoot model, string materialName) { var material = model .CreateMaterial(materialName) .WithDefault(); renderMaterial.IntParams.TryGetValue("F_TRANSLUCENT", out var isTranslucent); renderMaterial.IntParams.TryGetValue("F_ALPHA_TEST", out var isAlphaTest); if (renderMaterial.ShaderName == "vr_glass.vfx") isTranslucent = 1; material.Alpha = isTranslucent > 0 ? AlphaMode.BLEND : (isAlphaTest > 0 ? AlphaMode.MASK : AlphaMode.OPAQUE); if (isAlphaTest > 0 && renderMaterial.FloatParams.ContainsKey("g_flAlphaTestReference")) { material.AlphaCutoff = renderMaterial.FloatParams["g_flAlphaTestReference"]; } if (renderMaterial.IntParams.TryGetValue("F_RENDER_BACKFACES", out var doubleSided) && doubleSided > 0) { material.DoubleSided = true; } // assume non-metallic unless prompted float metalValue = 0; if (renderMaterial.FloatParams.TryGetValue("g_flMetalness", out var flMetalness)) { metalValue = flMetalness; } Vector4 baseColor = Vector4.One; if (renderMaterial.VectorParams.TryGetValue("g_vColorTint", out var vColorTint)) { baseColor = vColorTint; baseColor.W = 1; //Tint only affects color } material.WithPBRMetallicRoughness(baseColor, null, metallicFactor: metalValue); //share sampler for all textures var sampler = model.UseTextureSampler(TextureWrapMode.REPEAT, TextureWrapMode.REPEAT, TextureMipMapFilter.LINEAR_MIPMAP_LINEAR, TextureInterpolationFilter.LINEAR); foreach (var renderTexture in renderMaterial.TextureParams) { var texturePath = renderTexture.Value; var fileName = Path.GetFileNameWithoutExtension(texturePath); ProgressReporter?.Report($"Exporting texture: {texturePath}"); var textureResource = FileLoader.LoadFile(texturePath + "_c"); if (textureResource == null) { continue; } var exportedTexturePath = Path.Join(DstDir, fileName); exportedTexturePath = Path.ChangeExtension(exportedTexturePath, "png"); using (var bitmap = ((ResourceTypes.Texture)textureResource.DataBlock).GenerateBitmap()) { if (renderTexture.Key.StartsWith("g_tColor", StringComparison.Ordinal) && material.Alpha == AlphaMode.OPAQUE) { var bitmapSpan = bitmap.PeekPixels().GetPixelSpan<SKColor>(); // expensive transparency workaround for color maps for (var i = 0; i < bitmapSpan.Length; i++) { bitmapSpan[i] = bitmapSpan[i].WithAlpha(255); } } using var fs = File.Open(exportedTexturePath, FileMode.Create); bitmap.PeekPixels().Encode(fs, SKEncodedImageFormat.Png, 100); } var image = model.UseImage(exportedTexturePath); image.Name = fileName + $"_{model.LogicalImages.Count - 1}"; var tex = model.UseTexture(image); tex.Name = fileName + $"_{model.LogicalTextures.Count - 1}"; tex.Sampler = sampler; switch (renderTexture.Key) { case "g_tColor": case "g_tColor1": case "g_tColor2": case "g_tColorA": case "g_tColorB": case "g_tColorC": var channel = material.FindChannel("BaseColor"); if (channel?.Texture != null && renderTexture.Key != "g_tColor") { break; } channel?.SetTexture(0, tex); material.Extras = JsonContent.CreateFrom(new Dictionary<string, object> { ["baseColorTexture"] = new Dictionary<string, object> { { "index", image.LogicalIndex }, }, }); break; case "g_tNormal": material.FindChannel("Normal")?.SetTexture(0, tex); break; case "g_tAmbientOcclusion": material.FindChannel("Occlusion")?.SetTexture(0, tex); break; case "g_tEmissive": material.FindChannel("Emissive")?.SetTexture(0, tex); break; case "g_tShadowFalloff": // example: tongue_gman, materials/default/default_skin_shadowwarp_tga_f2855b6e.vtex case "g_tCombinedMasks": // example: models/characters/gman/materials/gman_head_mouth_mask_tga_bb35dc38.vtex case "g_tDiffuseFalloff": // example: materials/default/default_skin_diffusewarp_tga_e58a9ed.vtex case "g_tIris": // example: case "g_tIrisMask": // example: models/characters/gman/materials/gman_eye_iris_mask_tga_a5bb4a1e.vtex case "g_tTintColor": // example: models/characters/lazlo/eyemeniscus_vmat_g_ttintcolor_a00ef19e.vtex case "g_tAnisoGloss": // example: gordon_beard, models/characters/gordon/materials/gordon_hair_normal_tga_272a44e9.vtex case "g_tBentNormal": // example: gman_teeth, materials/default/default_skin_shadowwarp_tga_f2855b6e.vtex case "g_tFresnelWarp": // example: brewmaster_color, materials/default/default_fresnelwarprim_tga_d9279d65.vtex case "g_tMasks1": // example: brewmaster_color, materials/models/heroes/brewmaster/brewmaster_base_metalnessmask_psd_58eaa40f.vtex case "g_tMasks2": // example: brewmaster_color,materials/models/heroes/brewmaster/brewmaster_base_specmask_psd_63e9fb90.vtex default: Console.Error.WriteLine($"Warning: Unsupported Texture Type {renderTexture.Key}"); break; } } return material; } private List<VAnimation> GetAllAnimations(VModel model) { var animGroupPaths = model.GetReferencedAnimationGroupNames(); var animations = model.GetEmbeddedAnimations().ToList(); // Load animations from referenced animation groups foreach (var animGroupPath in animGroupPaths) { var animGroup = FileLoader.LoadFile(animGroupPath + "_c"); if (animGroup != default) { var data = animGroup.DataBlock.AsKeyValueCollection(); // Get the list of animation files var animArray = data.GetArray<string>("m_localHAnimArray").Where(a => a != null); // Get the key to decode the animations var decodeKey = data.GetSubCollection("m_decodeKey"); // Load animation files foreach (var animationFile in animArray) { var animResource = FileLoader.LoadFile(animationFile + "_c"); // Build animation classes animations.AddRange(VAnimation.FromResource(animResource, decodeKey)); } } } return animations.ToList(); } public static string GetAccessorName(string name, int index) { switch (name) { case "BLENDINDICES": return $"JOINTS_{index}"; case "BLENDWEIGHT": return $"WEIGHTS_{index}"; case "TEXCOORD": return $"TEXCOORD_{index}"; case "COLOR": return $"COLOR_{index}"; } if (index > 0) { throw new InvalidDataException($"Got attribute \"{name}\" more than once, but that is not supported"); } return name; } private static float[] ReadAttributeBuffer(OnDiskBufferData buffer, RenderInputLayoutField attribute) => Enumerable.Range(0, (int)buffer.ElementCount) .SelectMany(i => VBIB.ReadVertexAttribute(i, buffer, attribute)) .ToArray(); private static int[] ReadIndices(OnDiskBufferData indexBuffer, int start, int count) { var indices = new int[count]; var byteCount = count * (int)indexBuffer.ElementSizeInBytes; var byteStart = start * (int)indexBuffer.ElementSizeInBytes; if (indexBuffer.ElementSizeInBytes == 4) { System.Buffer.BlockCopy(indexBuffer.Data, byteStart, indices, 0, byteCount); } else if (indexBuffer.ElementSizeInBytes == 2) { var shortIndices = new ushort[count]; System.Buffer.BlockCopy(indexBuffer.Data, byteStart, shortIndices, 0, byteCount); indices = Array.ConvertAll(shortIndices, i => (int)i); } return indices; } private static (Vector3[] Normals, Vector4[] Tangents) DecompressNormalTangents(Vector4[] compressedNormalsTangents) { var normals = new Vector3[compressedNormalsTangents.Length]; var tangents = new Vector4[compressedNormalsTangents.Length]; for (var i = 0; i < normals.Length; i++) { // Undo-normalization var compressedNormal = compressedNormalsTangents[i] * 255f; var decompressedNormal = DecompressNormal(new Vector2(compressedNormal.X, compressedNormal.Y)); var decompressedTangent = DecompressTangent(new Vector2(compressedNormal.Z, compressedNormal.W)); // Swap Y and Z axes normals[i] = new Vector3(decompressedNormal.X, decompressedNormal.Z, decompressedNormal.Y); tangents[i] = new Vector4(decompressedTangent.X, decompressedTangent.Z, decompressedTangent.Y, decompressedTangent.W); } return (normals, tangents); } private static Vector3 DecompressNormal(Vector2 compressedNormal) { var inputNormal = compressedNormal; var outputNormal = Vector3.Zero; float x = inputNormal.X - 128.0f; float y = inputNormal.Y - 128.0f; float z; float zSignBit = x < 0 ? 1.0f : 0.0f; // z and t negative bits (like slt asm instruction) float tSignBit = y < 0 ? 1.0f : 0.0f; float zSign = -((2 * zSignBit) - 1); // z and t signs float tSign = -((2 * tSignBit) - 1); x = (x * zSign) - zSignBit; // 0..127 y = (y * tSign) - tSignBit; x -= 64; // -64..63 y -= 64; float xSignBit = x < 0 ? 1.0f : 0.0f; // x and y negative bits (like slt asm instruction) float ySignBit = y < 0 ? 1.0f : 0.0f; float xSign = -((2 * xSignBit) - 1); // x and y signs float ySign = -((2 * ySignBit) - 1); x = ((x * xSign) - xSignBit) / 63.0f; // 0..1 range y = ((y * ySign) - ySignBit) / 63.0f; z = 1.0f - x - y; float oolen = 1.0f / (float)Math.Sqrt((x * x) + (y * y) + (z * z)); // Normalize and x *= oolen * xSign; // Recover signs y *= oolen * ySign; z *= oolen * zSign; outputNormal.X = x; outputNormal.Y = y; outputNormal.Z = z; return outputNormal; } private static Vector4 DecompressTangent(Vector2 compressedTangent) { var outputNormal = DecompressNormal(compressedTangent); var tSign = compressedTangent.Y - 128.0f < 0 ? -1.0f : 1.0f; return new Vector4(outputNormal.X, outputNormal.Y, outputNormal.Z, tSign); } private static Vector3[] ToVector3Array(float[] buffer) { var vectorArray = new Vector3[buffer.Length / 3]; for (var i = 0; i < vectorArray.Length; i++) { vectorArray[i] = new Vector3(buffer[i * 3], buffer[(i * 3) + 1], buffer[(i * 3) + 2]); } return vectorArray; } private static Vector2[] ToVector2Array(float[] buffer) { var vectorArray = new Vector2[buffer.Length / 2]; for (var i = 0; i < vectorArray.Length; i++) { vectorArray[i] = new Vector2(buffer[i * 2], buffer[(i * 2) + 1]); } return vectorArray; } private static Vector4[] ToVector4Array(float[] buffer) { var vectorArray = new Vector4[buffer.Length / 4]; for (var i = 0; i < vectorArray.Length; i++) { vectorArray[i] = new Vector4(buffer[i * 4], buffer[(i * 4) + 1], buffer[(i * 4) + 2], buffer[(i * 4) + 3]); } return vectorArray; } // https://github.com/KhronosGroup/glTF-Validator/blob/master/lib/src/errors.dart private const float UnitLengthThresholdVec3 = 0.00674f; private static Vector4[] FixZeroLengthVectors(Vector4[] vectorArray) { for (var i = 0; i < vectorArray.Length; i++) { var vec = vectorArray[i]; if (Math.Abs(new Vector3(vec.X, vec.Y, vec.Z).Length() - 1.0f) > UnitLengthThresholdVec3) { vectorArray[i] = -Vector4.UnitZ; vectorArray[i].W = vec.W; Console.Error.WriteLine($"The exported model contains a non-zero unit vector which was replaced with {vectorArray[i]} for exporting purposes."); } } return vectorArray; } private static Vector3[] FixZeroLengthVectors(Vector3[] vectorArray) { for (var i = 0; i < vectorArray.Length; i++) { if (Math.Abs(vectorArray[i].Length() - 1.0f) > UnitLengthThresholdVec3) { vectorArray[i] = -Vector3.UnitZ; Console.Error.WriteLine($"The exported model contains a non-zero unit vector which was replaced with {vectorArray[i]} for exporting purposes."); } } return vectorArray; } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public static class LambdaUnaryNotTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotByteTest(bool useInterpreter) { foreach (byte value in new byte[] { 0, 1, byte.MaxValue }) { VerifyUnaryNotByte(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotIntTest(bool useInterpreter) { foreach (int value in new int[] { 0, 1, -1, int.MinValue, int.MaxValue }) { VerifyUnaryNotInt(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotLongTest(bool useInterpreter) { foreach (long value in new long[] { 0, 1, -1, long.MinValue, long.MaxValue }) { VerifyUnaryNotLong(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotSByteTest(bool useInterpreter) { foreach (sbyte value in new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }) { VerifyUnaryNotSByte(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotShortTest(bool useInterpreter) { foreach (short value in new short[] { 0, 1, -1, short.MinValue, short.MaxValue }) { VerifyUnaryNotShort(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotUIntTest(bool useInterpreter) { foreach (uint value in new uint[] { 0, 1, uint.MaxValue }) { VerifyUnaryNotUInt(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotULongTest(bool useInterpreter) { foreach (ulong value in new ulong[] { 0, 1, ulong.MaxValue }) { VerifyUnaryNotULong(value, useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLambdaUnaryNotUShortTest(bool useInterpreter) { foreach (ushort value in new ushort[] { 0, 1, ushort.MaxValue }) { VerifyUnaryNotUShort(value, useInterpreter); } } #endregion #region Test verifiers private static void VerifyUnaryNotByte(byte value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(byte), "p"); // parameter hard coded Expression<Func<byte>> e1 = Expression.Lambda<Func<byte>>( Expression.Invoke( Expression.Lambda<Func<byte, byte>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(byte)) }), Enumerable.Empty<ParameterExpression>()); Func<byte> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<byte, Func<byte>>> e2 = Expression.Lambda<Func<byte, Func<byte>>>( Expression.Lambda<Func<byte>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<byte, Func<byte>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<byte, byte>>> e3 = Expression.Lambda<Func<Func<byte, byte>>>( Expression.Invoke( Expression.Lambda<Func<Func<byte, byte>>>( Expression.Lambda<Func<byte, byte>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<byte, byte> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<byte, byte>>> e4 = Expression.Lambda<Func<Func<byte, byte>>>( Expression.Lambda<Func<byte, byte>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<byte, byte>> f4 = e4.Compile(useInterpreter); byte expected = (byte)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotInt(int value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(int), "p"); // parameter hard coded Expression<Func<int>> e1 = Expression.Lambda<Func<int>>( Expression.Invoke( Expression.Lambda<Func<int, int>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(int)) }), Enumerable.Empty<ParameterExpression>()); Func<int> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<int, Func<int>>> e2 = Expression.Lambda<Func<int, Func<int>>>( Expression.Lambda<Func<int>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<int, Func<int>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<int, int>>> e3 = Expression.Lambda<Func<Func<int, int>>>( Expression.Invoke( Expression.Lambda<Func<Func<int, int>>>( Expression.Lambda<Func<int, int>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int, int> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<int, int>>> e4 = Expression.Lambda<Func<Func<int, int>>>( Expression.Lambda<Func<int, int>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<int, int>> f4 = e4.Compile(useInterpreter); int expected = ~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotLong(long value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(long), "p"); // parameter hard coded Expression<Func<long>> e1 = Expression.Lambda<Func<long>>( Expression.Invoke( Expression.Lambda<Func<long, long>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(long)) }), Enumerable.Empty<ParameterExpression>()); Func<long> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<long, Func<long>>> e2 = Expression.Lambda<Func<long, Func<long>>>( Expression.Lambda<Func<long>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<long, Func<long>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<long, long>>> e3 = Expression.Lambda<Func<Func<long, long>>>( Expression.Invoke( Expression.Lambda<Func<Func<long, long>>>( Expression.Lambda<Func<long, long>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<long, long> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<long, long>>> e4 = Expression.Lambda<Func<Func<long, long>>>( Expression.Lambda<Func<long, long>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<long, long>> f4 = e4.Compile(useInterpreter); long expected = ~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotSByte(sbyte value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(sbyte), "p"); // parameter hard coded Expression<Func<sbyte>> e1 = Expression.Lambda<Func<sbyte>>( Expression.Invoke( Expression.Lambda<Func<sbyte, sbyte>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(sbyte)) }), Enumerable.Empty<ParameterExpression>()); Func<sbyte> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<sbyte, Func<sbyte>>> e2 = Expression.Lambda<Func<sbyte, Func<sbyte>>>( Expression.Lambda<Func<sbyte>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<sbyte, Func<sbyte>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<sbyte, sbyte>>> e3 = Expression.Lambda<Func<Func<sbyte, sbyte>>>( Expression.Invoke( Expression.Lambda<Func<Func<sbyte, sbyte>>>( Expression.Lambda<Func<sbyte, sbyte>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<sbyte, sbyte> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<sbyte, sbyte>>> e4 = Expression.Lambda<Func<Func<sbyte, sbyte>>>( Expression.Lambda<Func<sbyte, sbyte>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<sbyte, sbyte>> f4 = e4.Compile(useInterpreter); sbyte expected = (sbyte)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotShort(short value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(short), "p"); // parameter hard coded Expression<Func<short>> e1 = Expression.Lambda<Func<short>>( Expression.Invoke( Expression.Lambda<Func<short, short>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(short)) }), Enumerable.Empty<ParameterExpression>()); Func<short> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<short, Func<short>>> e2 = Expression.Lambda<Func<short, Func<short>>>( Expression.Lambda<Func<short>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<short, Func<short>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<short, short>>> e3 = Expression.Lambda<Func<Func<short, short>>>( Expression.Invoke( Expression.Lambda<Func<Func<short, short>>>( Expression.Lambda<Func<short, short>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<short, short> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<short, short>>> e4 = Expression.Lambda<Func<Func<short, short>>>( Expression.Lambda<Func<short, short>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<short, short>> f4 = e4.Compile(useInterpreter); short expected = (short)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotUInt(uint value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(uint), "p"); // parameter hard coded Expression<Func<uint>> e1 = Expression.Lambda<Func<uint>>( Expression.Invoke( Expression.Lambda<Func<uint, uint>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(uint)) }), Enumerable.Empty<ParameterExpression>()); Func<uint> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<uint, Func<uint>>> e2 = Expression.Lambda<Func<uint, Func<uint>>>( Expression.Lambda<Func<uint>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<uint, Func<uint>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<uint, uint>>> e3 = Expression.Lambda<Func<Func<uint, uint>>>( Expression.Invoke( Expression.Lambda<Func<Func<uint, uint>>>( Expression.Lambda<Func<uint, uint>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<uint, uint> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<uint, uint>>> e4 = Expression.Lambda<Func<Func<uint, uint>>>( Expression.Lambda<Func<uint, uint>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<uint, uint>> f4 = e4.Compile(useInterpreter); uint expected = ~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotULong(ulong value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(ulong), "p"); // parameter hard coded Expression<Func<ulong>> e1 = Expression.Lambda<Func<ulong>>( Expression.Invoke( Expression.Lambda<Func<ulong, ulong>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(ulong)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<ulong, Func<ulong>>> e2 = Expression.Lambda<Func<ulong, Func<ulong>>>( Expression.Lambda<Func<ulong>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<ulong, Func<ulong>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<ulong, ulong>>> e3 = Expression.Lambda<Func<Func<ulong, ulong>>>( Expression.Invoke( Expression.Lambda<Func<Func<ulong, ulong>>>( Expression.Lambda<Func<ulong, ulong>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ulong, ulong> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<ulong, ulong>>> e4 = Expression.Lambda<Func<Func<ulong, ulong>>>( Expression.Lambda<Func<ulong, ulong>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<ulong, ulong>> f4 = e4.Compile(useInterpreter); ulong expected = ~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotUShort(ushort value, bool useInterpreter) { ParameterExpression p = Expression.Parameter(typeof(ushort), "p"); // parameter hard coded Expression<Func<ushort>> e1 = Expression.Lambda<Func<ushort>>( Expression.Invoke( Expression.Lambda<Func<ushort, ushort>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(ushort)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort> f1 = e1.Compile(useInterpreter); // function generator that takes a parameter Expression<Func<ushort, Func<ushort>>> e2 = Expression.Lambda<Func<ushort, Func<ushort>>>( Expression.Lambda<Func<ushort>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<ushort, Func<ushort>> f2 = e2.Compile(useInterpreter); // function generator Expression<Func<Func<ushort, ushort>>> e3 = Expression.Lambda<Func<Func<ushort, ushort>>>( Expression.Invoke( Expression.Lambda<Func<Func<ushort, ushort>>>( Expression.Lambda<Func<ushort, ushort>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ushort, ushort> f3 = e3.Compile(useInterpreter)(); // parameter-taking function generator Expression<Func<Func<ushort, ushort>>> e4 = Expression.Lambda<Func<Func<ushort, ushort>>>( Expression.Lambda<Func<ushort, ushort>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<ushort, ushort>> f4 = e4.Compile(useInterpreter); ushort expected = (ushort)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } #endregion } }
#region Arx One FTP // Arx One FTP // A simple FTP client // https://github.com/ArxOne/FTP // Released under MIT license http://opensource.org/licenses/MIT #endregion namespace ArxOne.Ftp.IO { using System; using System.IO; using System.Net.Sockets; using Exceptions; /// <summary> /// FTP stream /// </summary> internal class FtpPassiveStream : FtpStream { private bool _disposed; private readonly FtpStreamMode? _mode; private Stream _innerStream; private Socket _innerSocket; /// <summary> /// Gets or sets the holder. /// </summary> /// <value>The holder.</value> internal FtpSession Session { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="FtpPassiveStream"/> class. /// </summary> /// <param name="socket">The socket.</param> /// <param name="session">The session.</param> /// <exception cref="IOException">The <paramref name="socket" /> parameter is not connected.-or- The <see cref="P:System.Net.Sockets.Socket.SocketType" /> property of the <paramref name="socket" /> parameter is not <see cref="F:System.Net.Sockets.SocketType.Stream" />.-or- The <paramref name="socket" /> parameter is in a nonblocking state.</exception> /// <exception cref="SocketException">An error occurred when attempting to access the socket.</exception> [Obsolete("Use full constructor instead")] public FtpPassiveStream(Socket socket, FtpSession session) : this(socket, session, null, false) { } /// <summary> /// Initializes a new instance of the <see cref="FtpPassiveStream"/> class. /// </summary> /// <param name="socket">The socket.</param> /// <param name="session">The session.</param> /// <param name="mode">The mode.</param> /// <param name="lazy">if set to <c>true</c> [lazy].</param> /// <exception cref="IOException">The <paramref name="socket" /> parameter is not connected.-or- The <see cref="P:System.Net.Sockets.Socket.SocketType" /> property of the <paramref name="socket" /> parameter is not <see cref="F:System.Net.Sockets.SocketType.Stream" />.-or- The <paramref name="socket" /> parameter is in a nonblocking state.</exception> /// <exception cref="SocketException">An error occurred when attempting to access the socket.</exception> public FtpPassiveStream(Socket socket, FtpSession session, FtpStreamMode mode, bool lazy) : this(socket, session, (FtpStreamMode?)mode, lazy) { } /// <summary> /// Initializes a new instance of the <see cref="FtpPassiveStream" /> class. /// </summary> /// <param name="socket">The socket.</param> /// <param name="session">The session.</param> /// <param name="mode">The mode.</param> /// <param name="lazy">if set to <c>true</c> [lazy].</param> /// <exception cref="IOException">The <paramref name="socket" /> parameter is not connected.-or- The <see cref="P:System.Net.Sockets.Socket.SocketType" /> property of the <paramref name="socket" /> parameter is not <see cref="F:System.Net.Sockets.SocketType.Stream" />.-or- The <paramref name="socket" /> parameter is in a nonblocking state.</exception> /// <exception cref="SocketException">An error occurred when attempting to access the socket.</exception> internal FtpPassiveStream(Socket socket, FtpSession session, FtpStreamMode? mode, bool lazy) { _mode = mode; Session = session; Session.Connection.AddReference(); SetSocket(socket, lazy); } /// <summary> /// Initializes a new instance of the <see cref="FtpPassiveStream"/> class. /// </summary> /// <param name="session">The session.</param> protected FtpPassiveStream(FtpSession session) { Session = session; Session.Connection.AddReference(); } /// <summary> /// Sets the socket. /// </summary> /// <param name="socket">The socket.</param> /// <param name="lazy"></param> /// <exception cref="IOException">The <paramref name="socket" /> parameter is not connected.-or- The <see cref="P:System.Net.Sockets.Socket.SocketType" /> property of the <paramref name="socket" /> parameter is not <see cref="F:System.Net.Sockets.SocketType.Stream" />.-or- The <paramref name="socket" /> parameter is in a nonblocking state. </exception> /// <exception cref="SocketException">An error occurred when attempting to access the socket.</exception> protected void SetSocket(Socket socket, bool lazy) { if (!lazy) _innerStream = Session.CreateDataStream(socket); _innerSocket = socket; _innerSocket.SendBufferSize = 1492; } /// <exception cref="IOException">The socket is not connected.-or- The <see cref="P:System.Net.Sockets.Socket.SocketType" /> property of the socket is not <see cref="F:System.Net.Sockets.SocketType.Stream" />.-or- The socket is in a nonblocking state. </exception> public override FtpStream Validated() { CheckLazySocket(); return base.Validated(); } protected virtual void CheckLazySocket() { if (_innerStream == null) _innerStream = Session.CreateDataStream(_innerSocket); } protected virtual Stream GetInnerStream() { return _innerStream; } /// <summary> /// Releases the unmanaged resources used by the <see cref="T:System.Net.Sockets.NetworkStream"/> and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> /// <exception cref="FtpTransportException">PASV stream already closed by server</exception> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing && !_disposed) { _disposed = true; bool isConnected = true; try { if (_innerSocket != null) { isConnected = _innerSocket.Connected; if (isConnected) { Process(delegate { _innerSocket.Shutdown(SocketShutdown.Both); _innerSocket.Close(300000); }); } } Process(delegate { if (_innerStream != null) _innerStream.Dispose(); }); } finally { Release(ExpectEndReply); } if (!isConnected) throw new FtpTransportException("PASV stream already closed by server"); } } /// <summary> /// Aborts this instance. /// </summary> public override void Abort() { Release(false); } /// <summary> /// Releases the instance (deferences it from the session locks). /// </summary> /// <param name="expectEndReply">if set to <c>true</c> [expect end reply].</param> private void Release(bool expectEndReply) { var session = Session; if (session != null) { Session = null; try { if (expectEndReply) { Process(() => session.Expect( 226, // default ack 150 // if the stream was opened but nothing was sent, then we still shall exit gracefully )); } } // on long transfers, the command socket may be closed // however we need to signal it to client finally { session.Connection.Release(); } } } // below are wrapped methods where exceptions need to be reinterpreted #region Exception wrapper /// <summary> /// Processes the specified action. /// </summary> /// <param name="action">The action.</param> /// <exception cref="FtpTransportException">Socket exception in FTP stream</exception> protected static void Process(Action action) { Process(delegate { action(); return 0; }); } /// <summary> /// Processes the specified func. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="func">The func.</param> /// <returns></returns> /// <exception cref="FtpTransportException">Socket exception in FTP stream</exception> protected static TResult Process<TResult>(Func<TResult> func) { try { return func(); } catch (SocketException se) { throw new FtpTransportException("Socket exception in FTP stream", se); } catch (IOException ioe) { throw new FtpTransportException("IO exception in FTP stream", ioe); } } #endregion #region Stream wrappers /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> /// <exception cref="T:System.IO.IOException"> /// An I/O error occurs. /// </exception> /// <exception cref="FtpTransportException">Socket exception in FTP stream</exception> public override void Flush() { Process(() => { if (_innerStream != null) _innerStream.Flush(); }); } /// <summary> /// Reads data from the <see cref="T:System.Net.Sockets.NetworkStream"/>. /// </summary> /// <param name="buffer">An array of type <see cref="T:System.Byte"/> that is the location in memory to store data read from the <see cref="T:System.Net.Sockets.NetworkStream"/>.</param> /// <param name="offset">The location in <paramref name="buffer"/> to begin storing the data to.</param> /// <param name="size">The number of bytes to read from the <see cref="T:System.Net.Sockets.NetworkStream"/>.</param> /// <returns> /// The number of bytes read from the <see cref="T:System.Net.Sockets.NetworkStream"/>. /// </returns> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="buffer"/> parameter is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The <paramref name="offset"/> parameter is less than 0. /// -or- /// The <paramref name="offset"/> parameter is greater than the length of <paramref name="buffer"/>. /// -or- /// The <paramref name="size"/> parameter is less than 0. /// -or- /// The <paramref name="size"/> parameter is greater than the length of <paramref name="buffer"/> minus the value of the <paramref name="offset"/> parameter. /// -or- /// An error occurred when accessing the socket. See the Remarks section for more information. /// </exception> /// <exception cref="T:System.IO.IOException"> /// The underlying <see cref="T:System.Net.Sockets.Socket"/> is closed. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="T:System.Net.Sockets.NetworkStream"/> is closed. /// -or- /// There is a failure reading from the network. /// </exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/> /// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// </PermissionSet> /// <exception cref="FtpTransportException">Socket exception in FTP stream</exception> public override int Read(byte[] buffer, int offset, int size) { return Process(() => InnerRead(buffer, offset, size)); } /// <summary> /// Call to base.Read. /// </summary> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset.</param> /// <param name="size">The size.</param> /// <returns></returns> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="buffer"/> parameter is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The <paramref name="offset"/> parameter is less than 0. /// -or- /// The <paramref name="offset"/> parameter is greater than the length of <paramref name="buffer"/>. /// -or- /// The <paramref name="size"/> parameter is less than 0. /// -or- /// The <paramref name="size"/> parameter is greater than the length of <paramref name="buffer"/> minus the value of the <paramref name="offset"/> parameter. /// -or- /// An error occurred when accessing the socket. See the Remarks section for more information. /// </exception> /// <exception cref="T:System.IO.IOException"> /// The underlying <see cref="T:System.Net.Sockets.Socket"/> is closed. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="T:System.Net.Sockets.NetworkStream"/> is closed. /// -or- /// There is a failure reading from the network. /// </exception> private int InnerRead(byte[] buffer, int offset, int size) { if (_mode.HasValue && _mode != FtpStreamMode.Read) throw new NotSupportedException(); return GetInnerStream().Read(buffer, offset, size); } /// <summary> /// Writes data to the <see cref="T:System.Net.Sockets.NetworkStream"/>. /// </summary> /// <param name="buffer">An array of type <see cref="T:System.Byte"/> that contains the data to write to the <see cref="T:System.Net.Sockets.NetworkStream"/>.</param> /// <param name="offset">The location in <paramref name="buffer"/> from which to start writing data.</param> /// <param name="size">The number of bytes to write to the <see cref="T:System.Net.Sockets.NetworkStream"/>.</param> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="buffer"/> parameter is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The <paramref name="offset"/> parameter is less than 0. /// -or- /// The <paramref name="offset"/> parameter is greater than the length of <paramref name="buffer"/>. /// -or- /// The <paramref name="size"/> parameter is less than 0. /// -or- /// The <paramref name="size"/> parameter is greater than the length of <paramref name="buffer"/> minus the value of the <paramref name="offset"/> parameter. /// </exception> /// <exception cref="T:System.IO.IOException"> /// There was a failure while writing to the network. /// -or- /// An error occurred when accessing the socket. See the Remarks section for more information. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="T:System.Net.Sockets.NetworkStream"/> is closed. /// -or- /// There was a failure reading from the network. /// </exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/> /// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// </PermissionSet> /// <exception cref="FtpTransportException">Socket exception in FTP stream</exception> public override void Write(byte[] buffer, int offset, int size) { Process(() => InnerWrite(buffer, offset, size)); } /// <summary> /// Calls base.Write. /// </summary> /// <exception cref="T:System.ArgumentNullException"> /// The <paramref name="buffer"/> parameter is null. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// The <paramref name="offset"/> parameter is less than 0. /// -or- /// The <paramref name="offset"/> parameter is greater than the length of <paramref name="buffer"/>. /// -or- /// The <paramref name="size"/> parameter is less than 0. /// -or- /// The <paramref name="size"/> parameter is greater than the length of <paramref name="buffer"/> minus the value of the <paramref name="offset"/> parameter. /// </exception> /// <exception cref="T:System.IO.IOException"> /// There was a failure while writing to the network. /// -or- /// An error occurred when accessing the socket. See the Remarks section for more information. /// </exception> /// <exception cref="T:System.ObjectDisposedException"> /// The <see cref="T:System.Net.Sockets.NetworkStream"/> is closed. /// -or- /// There was a failure reading from the network. /// </exception> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset.</param> /// <param name="size">The size.</param> private void InnerWrite(byte[] buffer, int offset, int size) { if (_mode.HasValue && _mode != FtpStreamMode.Write) throw new NotSupportedException(); GetInnerStream().Write(buffer, offset, size); } /// <summary> /// Sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns> /// The new position within the current stream. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. /// </exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. /// </exception> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Gets a value indicating whether the current stream supports reading. /// </summary> /// <value></value> /// <returns>true if the stream supports reading; otherwise, false. /// </returns> public override bool CanRead { get { if (_mode.HasValue) return _mode.Value == FtpStreamMode.Read; return GetInnerStream().CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> /// <value></value> /// <returns>true if the stream supports seeking; otherwise, false. /// </returns> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// </summary> /// <value></value> /// <returns>true if the stream supports writing; otherwise, false. /// </returns> public override bool CanWrite { get { if (_mode.HasValue) return _mode.Value == FtpStreamMode.Write; return GetInnerStream().CanWrite; } } /// <summary> /// Gets the length in bytes of the stream. /// </summary> /// <value></value> /// <returns> /// A long value representing the length of the stream in bytes. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// A class derived from Stream does not support seeking. /// </exception> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> /// <value></value> /// <returns> /// The current position within the stream. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The stream does not support seeking. /// </exception> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Sprite/tk2dSprite")] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] /// <summary> /// Sprite implementation which maintains its own Unity Mesh. Leverages dynamic batching. /// </summary> public class tk2dSprite : tk2dBaseSprite { Mesh mesh; Vector3[] meshVertices; Vector3[] meshNormals = null; Vector4[] meshTangents = null; Color32[] meshColors; new void Awake() { base.Awake(); // Create mesh, independently to everything else mesh = new Mesh(); #if !UNITY_3_5 mesh.MarkDynamic(); #endif mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; // This will not be set when instantiating in code // In that case, Build will need to be called if (Collection) { // reset spriteId if outside bounds // this is when the sprite collection data is corrupt if (_spriteId < 0 || _spriteId >= Collection.Count) _spriteId = 0; Build(); } } protected void OnDestroy() { if (mesh) { #if UNITY_EDITOR DestroyImmediate(mesh); #else Destroy(mesh); #endif } #if !STRIP_PHYSICS_3D if (meshColliderMesh) { #if UNITY_EDITOR DestroyImmediate(meshColliderMesh); #else Destroy(meshColliderMesh); #endif } #endif } public override void Build() { var sprite = collectionInst.spriteDefinitions[spriteId]; meshVertices = new Vector3[sprite.positions.Length]; meshColors = new Color32[sprite.positions.Length]; meshNormals = new Vector3[0]; meshTangents = new Vector4[0]; if (sprite.normals != null && sprite.normals.Length > 0) { meshNormals = new Vector3[sprite.normals.Length]; } if (sprite.tangents != null && sprite.tangents.Length > 0) { meshTangents = new Vector4[sprite.tangents.Length]; } SetPositions(meshVertices, meshNormals, meshTangents); SetColors(meshColors); if (mesh == null) { mesh = new Mesh(); #if !UNITY_3_5 mesh.MarkDynamic(); #endif mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; } mesh.Clear(); mesh.vertices = meshVertices; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.colors32 = meshColors; mesh.uv = sprite.uvs; mesh.triangles = sprite.indices; mesh.bounds = AdjustedMeshBounds( GetBounds(), renderLayer ); UpdateMaterial(); CreateCollider(); } #if UNITY_EDITOR void OnValidate() { MeshFilter meshFilter = GetComponent<MeshFilter>(); if (meshFilter != null) { meshFilter.sharedMesh = mesh; } } #endif /// <summary> /// Adds a tk2dSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry. /// Convenience alias of tk2dBaseSprite.AddComponent<tk2dSprite>(...). /// </summary> public static tk2dSprite AddComponent(GameObject go, tk2dSpriteCollectionData spriteCollection, int spriteId) { return tk2dBaseSprite.AddComponent<tk2dSprite>(go, spriteCollection, spriteId); } /// <summary> /// Adds a tk2dSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry. /// Convenience alias of tk2dBaseSprite.AddComponent<tk2dSprite>(...). /// </summary> public static tk2dSprite AddComponent(GameObject go, tk2dSpriteCollectionData spriteCollection, string spriteName) { return tk2dBaseSprite.AddComponent<tk2dSprite>(go, spriteCollection, spriteName); } /// <summary> /// Create a sprite (and gameObject) displaying the region of the texture specified. /// Use <see cref="tk2dSpriteCollectionData.CreateFromTexture"/> if you need to create a sprite collection /// with multiple sprites. It is your responsibility to destroy the collection when you /// destroy this sprite game object. You can get to it by using sprite.Collection. /// Convenience alias of tk2dBaseSprite.CreateFromTexture<tk2dSprite>(...) /// </summary> public static GameObject CreateFromTexture(Texture texture, tk2dSpriteCollectionSize size, Rect region, Vector2 anchor) { return tk2dBaseSprite.CreateFromTexture<tk2dSprite>(texture, size, region, anchor); } protected override void UpdateGeometry() { UpdateGeometryImpl(); } protected override void UpdateColors() { UpdateColorsImpl(); } protected override void UpdateVertices() { UpdateVerticesImpl(); } protected void UpdateColorsImpl() { // This can happen with prefabs in the inspector if (mesh == null || meshColors == null || meshColors.Length == 0) return; SetColors(meshColors); mesh.colors32 = meshColors; } protected void UpdateVerticesImpl() { var sprite = collectionInst.spriteDefinitions[spriteId]; // This can happen with prefabs in the inspector if (mesh == null || meshVertices == null || meshVertices.Length == 0) return; // Clear out normals and tangents when switching from a sprite with them to one without if (sprite.normals.Length != meshNormals.Length) { meshNormals = (sprite.normals != null && sprite.normals.Length > 0)?(new Vector3[sprite.normals.Length]):(new Vector3[0]); } if (sprite.tangents.Length != meshTangents.Length) { meshTangents = (sprite.tangents != null && sprite.tangents.Length > 0)?(new Vector4[sprite.tangents.Length]):(new Vector4[0]); } SetPositions(meshVertices, meshNormals, meshTangents); mesh.vertices = meshVertices; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.uv = sprite.uvs; mesh.bounds = AdjustedMeshBounds( GetBounds(), renderLayer ); } protected void UpdateGeometryImpl() { // This can happen with prefabs in the inspector if (mesh == null) return; var sprite = collectionInst.spriteDefinitions[spriteId]; if (meshVertices == null || meshVertices.Length != sprite.positions.Length) { meshVertices = new Vector3[sprite.positions.Length]; meshColors = new Color32[sprite.positions.Length]; } if (meshNormals == null || (sprite.normals != null && meshNormals.Length != sprite.normals.Length)) { meshNormals = new Vector3[sprite.normals.Length]; } else if (sprite.normals == null) { meshNormals = new Vector3[0]; } if (meshTangents == null || (sprite.tangents != null && meshTangents.Length != sprite.tangents.Length)) { meshTangents = new Vector4[sprite.tangents.Length]; } else if (sprite.tangents == null) { meshTangents = new Vector4[0]; } SetPositions(meshVertices, meshNormals, meshTangents); SetColors(meshColors); mesh.Clear(); mesh.vertices = meshVertices; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.colors32 = meshColors; mesh.uv = sprite.uvs; mesh.bounds = AdjustedMeshBounds( GetBounds(), renderLayer ); mesh.triangles = sprite.indices; } protected override void UpdateMaterial() { Renderer renderer = GetComponent<Renderer>(); if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst) renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst; } protected override int GetCurrentVertexCount() { if (meshVertices == null) return 0; // Really nasty bug here found by Andrew Welch. return meshVertices.Length; } #if UNITY_EDITOR void OnDrawGizmos() { if (collectionInst != null && spriteId >= 0 && spriteId < collectionInst.Count) { var sprite = collectionInst.spriteDefinitions[spriteId]; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(Vector3.Scale(sprite.untrimmedBoundsData[0], _scale), Vector3.Scale(sprite.untrimmedBoundsData[1], _scale)); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif public override void ForceBuild() { base.ForceBuild(); GetComponent<MeshFilter>().mesh = mesh; } public override void ReshapeBounds(Vector3 dMin, Vector3 dMax) { float minSizeClampTexelScale = 0.1f; // Can't shrink sprite smaller than this many texels // Irrespective of transform var sprite = CurrentSprite; Vector3 oldAbsScale = new Vector3(Mathf.Abs(_scale.x), Mathf.Abs(_scale.y), Mathf.Abs(_scale.z)); Vector3 oldMin = Vector3.Scale(sprite.untrimmedBoundsData[0], _scale) - 0.5f * Vector3.Scale(sprite.untrimmedBoundsData[1], oldAbsScale); Vector3 oldSize = Vector3.Scale(sprite.untrimmedBoundsData[1], oldAbsScale); Vector3 newAbsScale = oldSize + dMax - dMin; newAbsScale.x /= sprite.untrimmedBoundsData[1].x; newAbsScale.y /= sprite.untrimmedBoundsData[1].y; // Clamp the minimum size to avoid having the pivot move when we scale from near-zero if (sprite.untrimmedBoundsData[1].x * newAbsScale.x < sprite.texelSize.x * minSizeClampTexelScale && newAbsScale.x < oldAbsScale.x) { dMin.x = 0; newAbsScale.x = oldAbsScale.x; } if (sprite.untrimmedBoundsData[1].y * newAbsScale.y < sprite.texelSize.y * minSizeClampTexelScale && newAbsScale.y < oldAbsScale.y) { dMin.y = 0; newAbsScale.y = oldAbsScale.y; } // Add our wanted local dMin offset, while negating the positional offset caused by scaling Vector2 scaleFactor = new Vector3(Mathf.Approximately(oldAbsScale.x, 0) ? 0 : (newAbsScale.x / oldAbsScale.x), Mathf.Approximately(oldAbsScale.y, 0) ? 0 : (newAbsScale.y / oldAbsScale.y)); Vector3 scaledMin = new Vector3(oldMin.x * scaleFactor.x, oldMin.y * scaleFactor.y); Vector3 offset = dMin + oldMin - scaledMin; offset.z = 0; transform.position = transform.TransformPoint(offset); scale = new Vector3(_scale.x * scaleFactor.x, _scale.y * scaleFactor.y, _scale.z); } }
using System; using System.IO; using System.Reflection; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using YamlDotNet.Core; using YamlDotNet.Core.Tokens; namespace YamlDotNet.UnitTests { [TestClass] public class ScannerTests : YamlTest { private static Scanner CreateScanner(string name) { return new Scanner(YamlFile(name)); } private void AssertHasNext(Scanner scanner) { Assert.IsTrue(scanner.MoveNext(), "The scanner does not contain more tokens."); } private void AssertDoesNotHaveNext(Scanner scanner) { Assert.IsFalse(scanner.MoveNext(), "The scanner should not contain more tokens."); } private void AssertCurrent(Scanner scanner, Token expected) { Console.WriteLine(expected.GetType().Name); Assert.IsNotNull(scanner.Current, "The current token is null."); Assert.IsTrue(expected.GetType().IsAssignableFrom(scanner.Current.GetType()), "The token is not of the expected type."); foreach (var property in expected.GetType().GetProperties()) { if(property.PropertyType != typeof(Mark) && property.CanRead) { object value = property.GetValue(scanner.Current, null); Console.WriteLine("\t{0} = {1}", property.Name, value); Assert.AreEqual(property.GetValue(expected, null), value, string.Format("The property '{0}' is incorrect.", property.Name)); } } } private void AssertNext(Scanner scanner, Token expected) { AssertHasNext(scanner); AssertCurrent(scanner, expected); } [TestMethod] public void VerifyTokensOnExample1() { Scanner scanner = CreateScanner("test1.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new VersionDirective(new Core.Version(1, 1))); AssertNext(scanner, new TagDirective("!", "!foo")); AssertNext(scanner, new TagDirective("!yaml!", "tag:yaml.org,2002:")); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample2() { Scanner scanner = CreateScanner("test2.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new Scalar("a scalar", ScalarStyle.SingleQuoted)); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample3() { Scanner scanner = CreateScanner("test3.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("a scalar", ScalarStyle.SingleQuoted)); AssertNext(scanner, new DocumentEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample4() { Scanner scanner = CreateScanner("test4.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new Scalar("a scalar", ScalarStyle.SingleQuoted)); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("another scalar", ScalarStyle.SingleQuoted)); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("yet another scalar", ScalarStyle.SingleQuoted)); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample5() { Scanner scanner = CreateScanner("test5.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new Anchor("A")); AssertNext(scanner, new FlowSequenceStart()); AssertNext(scanner, new AnchorAlias("A")); AssertNext(scanner, new FlowSequenceEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample6() { Scanner scanner = CreateScanner("test6.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new Tag("!!", "float")); AssertNext(scanner, new Scalar("3.14", ScalarStyle.DoubleQuoted)); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample7() { Scanner scanner = CreateScanner("test7.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("a plain scalar", ScalarStyle.Plain)); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("a single-quoted scalar", ScalarStyle.SingleQuoted)); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("a double-quoted scalar", ScalarStyle.DoubleQuoted)); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("a literal scalar", ScalarStyle.Literal)); AssertNext(scanner, new DocumentStart()); AssertNext(scanner, new Scalar("a folded scalar", ScalarStyle.Folded)); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample8() { Scanner scanner = CreateScanner("test8.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new FlowSequenceStart()); AssertNext(scanner, new Scalar("item 1", ScalarStyle.Plain)); AssertNext(scanner, new FlowEntry()); AssertNext(scanner, new Scalar("item 2", ScalarStyle.Plain)); AssertNext(scanner, new FlowEntry()); AssertNext(scanner, new Scalar("item 3", ScalarStyle.Plain)); AssertNext(scanner, new FlowSequenceEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample9() { Scanner scanner = CreateScanner("test9.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new FlowMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a simple key", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("a value", ScalarStyle.Plain)); AssertNext(scanner, new FlowEntry()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a complex key", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("another value", ScalarStyle.Plain)); AssertNext(scanner, new FlowEntry()); AssertNext(scanner, new FlowMappingEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample10() { Scanner scanner = CreateScanner("test10.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new BlockSequenceStart()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 1", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new BlockSequenceStart()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 3.1", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 3.2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 1", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 1", ScalarStyle.Plain)); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 2", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample11() { Scanner scanner = CreateScanner("test11.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a simple key", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("a value", ScalarStyle.Plain)); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a complex key", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("another value", ScalarStyle.Plain)); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a mapping", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 1", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 1", ScalarStyle.Plain)); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 2", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a sequence", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new BlockSequenceStart()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 1", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample12() { Scanner scanner = CreateScanner("test12.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new BlockSequenceStart()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new BlockSequenceStart()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 1", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 1", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 1", ScalarStyle.Plain)); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 2", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("complex key", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("complex value", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample13() { Scanner scanner = CreateScanner("test13.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a sequence", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new BlockSequenceStart()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 1", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("a mapping", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 1", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 1", ScalarStyle.Plain)); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key 2", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new Scalar("value 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } [TestMethod] public void VerifyTokensOnExample14() { Scanner scanner = CreateScanner("test14.yaml"); AssertNext(scanner, new StreamStart()); AssertNext(scanner, new BlockMappingStart()); AssertNext(scanner, new Key()); AssertNext(scanner, new Scalar("key", ScalarStyle.Plain)); AssertNext(scanner, new Value()); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 1", ScalarStyle.Plain)); AssertNext(scanner, new BlockEntry()); AssertNext(scanner, new Scalar("item 2", ScalarStyle.Plain)); AssertNext(scanner, new BlockEnd()); AssertNext(scanner, new StreamEnd()); AssertDoesNotHaveNext(scanner); } } }
// Deployment Framework for BizTalk // Copyright (C) 2008-14 Thomas F. Abraham, 2004-08 Scott Colestock // This source file is subject to the Microsoft Public License (Ms-PL). // See http://www.opensource.org/licenses/ms-pl.html. // All other rights reserved. using System; using Microsoft.RuleEngine; namespace DeployBTRules { /// <summary> /// This is a command line application for deploying BizTalk rules and vocabularies. /// </summary> class DeployRules { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static int Main(string[] args) { DeployRulesCommandLine cl = new DeployRulesCommandLine(); if (!cl.ParseAndContinue(args)) { return -1; } if (string.IsNullOrEmpty(cl.ruleSetFile) && string.IsNullOrEmpty(cl.ruleSetName) && string.IsNullOrEmpty(cl.vocabularyName)) { Console.WriteLine(cl.GetUsage()); return -1; } if (!string.IsNullOrEmpty(cl.ruleSetName) && !string.IsNullOrEmpty(cl.vocabularyName)) { Console.WriteLine(cl.GetUsage()); return -1; } if (cl.unpublish) { // If we're unpublishing then we must also undeploy. cl.undeploy = true; } cl.PrintLogo(); Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd = new Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver(); try { try { if (!cl.undeploy && cl.ruleSetFile != string.Empty) { Console.WriteLine("Importing and publishing from file '{0}'...", cl.ruleSetFile); dd.ImportAndPublishFileRuleStore(cl.ruleSetFile); } } catch (System.Exception ex) { if (cl.ruleSetName != string.Empty) { Console.WriteLine("Unable to import/publish {0} ({1}). Attempting deploy operation.", cl.ruleSetFile, ex.Message); } else { throw; } } if (!string.IsNullOrEmpty(cl.ruleSetName)) { ProcessPolicies(cl, dd); } if (!string.IsNullOrEmpty(cl.vocabularyName) && cl.unpublish) { ProcessVocabularies(cl, dd); } Console.WriteLine("Operation complete."); } catch (Microsoft.RuleEngine.RuleEngineDeploymentAlreadyDeployedException ex) { Console.WriteLine("Operation did not complete: " + ex.Message); } catch (Microsoft.RuleEngine.RuleEngineDeploymentNotDeployedException ex) { Console.WriteLine("Operation did not complete: " + ex.Message); } catch (RuleEngineDeploymentRuleSetExistsException ex) { Console.WriteLine("Operation did not complete: " + ex.Message); } catch (RuleEngineDeploymentVocabularyExistsException ex) { Console.WriteLine("Operation did not complete: " + ex.Message); } catch (System.Exception ex) { Console.WriteLine("Failed: " + ex.ToString()); Console.WriteLine(); return -1; } Console.WriteLine(); return 0; } private static void ProcessPolicies( DeployRulesCommandLine cl, Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd) { RuleStore ruleStore = dd.GetRuleStore(); RuleSetInfoCollection rsInfo = ruleStore.GetRuleSets(cl.ruleSetName, RuleStore.Filter.All); Version version = ParseVersion(cl.ruleSetVersion); RuleSetInfo matchingRuleSetInfo = null; foreach (RuleSetInfo currentRsi in rsInfo) { if (currentRsi.MajorRevision == version.Major && currentRsi.MinorRevision == version.Minor) { matchingRuleSetInfo = currentRsi; break; } } if (matchingRuleSetInfo == null) { Console.WriteLine( "No published ruleset with name '" + cl.ruleSetName + "' and version '" + cl.ruleSetVersion + "'."); } else if (cl.undeploy) { Console.WriteLine("Undeploying rule set '{0}' version {1}.{2}...", cl.ruleSetName, version.Major, version.Minor); if (dd.IsRuleSetDeployed(matchingRuleSetInfo)) { dd.Undeploy(matchingRuleSetInfo); } else { Console.WriteLine(" Rule set is not currently deployed."); } if (cl.unpublish) { Console.WriteLine("Unpublishing rule set '{0}' version {1}.{2}...", cl.ruleSetName, version.Major, version.Minor); ruleStore.Remove(matchingRuleSetInfo); } } else { Console.WriteLine("Deploying rule set '{0}' version {1}.{2}...", cl.ruleSetName, version.Major, version.Minor); dd.Deploy(matchingRuleSetInfo); } } private static void ProcessVocabularies( DeployRulesCommandLine cl, Microsoft.BizTalk.RuleEngineExtensions.RuleSetDeploymentDriver dd) { RuleStore ruleStore = dd.GetRuleStore(); VocabularyInfoCollection vInfo = ruleStore.GetVocabularies(cl.vocabularyName, RuleStore.Filter.All); Version version = ParseVersion(cl.ruleSetVersion); VocabularyInfo matchingVocabularyInfo = null; foreach (VocabularyInfo currentRsi in vInfo) { if (currentRsi.MajorRevision == version.Major && currentRsi.MinorRevision == version.Minor) { matchingVocabularyInfo = currentRsi; break; } } if (matchingVocabularyInfo == null) { Console.WriteLine( "No published vocabulary with name '" + cl.vocabularyName + "' and version '" + cl.ruleSetVersion + "'."); } else if (cl.unpublish) { Console.WriteLine("Unpublishing vocabulary '{0}' version {1}.{2}...", cl.vocabularyName, version.Major, version.Minor); ruleStore.Remove(matchingVocabularyInfo); } } private static Version ParseVersion(string versionString) { string[] parts = versionString.Split('.'); if (parts == null || parts.Length != 2) { throw new ArgumentException("Invalid version number. Must be in the format Major.Minor"); } int majorVersion = 0; int minorVersion = 0; bool majorIsOk = int.TryParse(parts[0], out majorVersion); bool minorIsOk = int.TryParse(parts[1], out minorVersion); if (!majorIsOk || !minorIsOk) { throw new ArgumentException("Invalid version number. Must be in the format Major.Minor"); } return new Version(majorVersion, minorVersion); } } }
/* * Copyright (C) 2005-2017 Christoph Rupp ([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See the file COPYING for License information. */ /* * This sample is the implementation of /samples/env3.cpp in C#. * * It creates an Environment with three Databases - one for the Customers, * one for Orders, and a third for managing the 1:n relationship between * the other two. */ using System; using System.Collections.Generic; using System.Text; using Upscaledb; namespace SampleEnv3 { /* * a Customer class */ public struct Customer { public Customer(int id, String name) { this.id = id; this.name = name; } public Customer(byte[] id, byte[] name) { this.id = BitConverter.ToInt32(id, 0); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); this.name = enc.GetString(name); } public int id; public string name; public byte[] GetKey() { return BitConverter.GetBytes(id); } public byte[] GetRecord() { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); return enc.GetBytes(name); } } /* * An Order class; it stores the ID of the Customer, * and the name of the employee who is assigned to this order */ public class Order { public Order(int id, int customerId, string assignee) { this.id = id; this.customerId = customerId; this.assignee = assignee; } public int id; public int customerId; public String assignee; public byte[] GetKey() { return BitConverter.GetBytes(id); } public byte[] GetCustomerKey() { return BitConverter.GetBytes(customerId); } public byte[] GetRecord() { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); return enc.GetBytes(assignee); } } class Program { const int DBIDX_CUSTOMER = 0; const int DBIDX_ORDER = 1; const int DBIDX_C2O = 2; const short DBNAME_CUSTOMER = 1; const short DBNAME_ORDER = 2; const short DBNAME_C2O = 3; static void Main(string[] args) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Upscaledb.Environment env = new Upscaledb.Environment(); Database[] db = new Database[3]; Cursor[] cursor = new Cursor[3]; /* * set up the customer and order data - these arrays will later * be inserted into the Databases */ Customer[] customers = new Customer[4]; customers[0] = new Customer(1, "Alan Antonov Corp."); customers[1] = new Customer(2, "Barry Broke Inc."); customers[2] = new Customer(3, "Carl Caesar Lat."); customers[3] = new Customer(4, "Doris Dove Brd."); Order[] orders = new Order[8]; orders[0] = new Order(1, 1, "Joe"); orders[1] = new Order(2, 1, "Tom"); orders[2] = new Order(3, 3, "Joe"); orders[3] = new Order(4, 4, "Tom"); orders[4] = new Order(5, 3, "Ben"); orders[5] = new Order(6, 3, "Ben"); orders[6] = new Order(7, 4, "Chris"); orders[7] = new Order(8, 1, "Ben"); /* * Create a new Environment */ env.Create("test.db"); /* * then create the three Databases in this Environment; each Database * has a name - the first is our "customer" Database, the second * is for the "orders"; the third manages our 1:n relation and * therefore needs to enable duplicate keys */ db[DBIDX_CUSTOMER] = env.CreateDatabase(DBNAME_CUSTOMER); db[DBIDX_ORDER] = env.CreateDatabase(DBNAME_ORDER); db[DBIDX_C2O] = env.CreateDatabase(DBNAME_C2O, UpsConst.UPS_ENABLE_DUPLICATE_KEYS); /* * create a Cursor for each Database */ cursor[DBIDX_CUSTOMER] = new Cursor(db[DBIDX_CUSTOMER]); cursor[DBIDX_ORDER] = new Cursor(db[DBIDX_ORDER]); cursor[DBIDX_C2O] = new Cursor(db[DBIDX_C2O]); /* * Insert the customers in the customer Database * * INSERT INTO customers VALUES (1, "Alan Antonov Corp."); * INSERT INTO customers VALUES (2, "Barry Broke Inc."); * etc. */ for (int i = 0; i < customers.GetLength(0); i++) { byte[] key = customers[i].GetKey(); byte[] rec = customers[i].GetRecord(); db[DBIDX_CUSTOMER].Insert(key, rec); } /* * Insert the orders in the order Database * * INSERT INTO orders VALUES (1, "Joe"); * INSERT INTO orders VALUES (2, "Tom"); * etc. */ for (int i = 0; i < orders.GetLength(0); i++) { byte[] key = orders[i].GetKey(); byte[] rec = orders[i].GetRecord(); db[DBIDX_ORDER].Insert(key, rec); } /* * and now the 1:n relationships; the flag UPS_DUPLICATE creates * a duplicate key, if the key already exists * * INSERT INTO c2o VALUES (1, 1); * INSERT INTO c2o VALUES (2, 1); * etc */ for (int i = 0; i < orders.GetLength(0); i++) { byte[] key = orders[i].GetCustomerKey(); byte[] rec = orders[i].GetKey(); db[DBIDX_C2O].Insert(key, rec, UpsConst.UPS_DUPLICATE); } /* * now start the queries - we want to dump each customer and * his orders * * loop over the customer; for each customer, loop over the * 1:n table and pick those orders with the customer id. * then load the order and print it * * the outer loop is similar to * SELECT * FROM customers WHERE 1; */ while (1 == 1) { Customer c; try { cursor[DBIDX_CUSTOMER].MoveNext(); } catch (DatabaseException e) { // reached end of Database? if (e.ErrorCode == UpsConst.UPS_KEY_NOT_FOUND) break; Console.Out.WriteLine("cursor.MoveNext failed: " + e); return; } // load the customer c = new Customer(cursor[DBIDX_CUSTOMER].GetKey(), cursor[DBIDX_CUSTOMER].GetRecord()); // print information about this customer Console.Out.WriteLine("customer " + c.id + " ('" + c.name + "')"); /* * loop over the 1:n table * * SELECT * FROM customers, orders, c2o * WHERE c2o.customer_id=customers.id AND * c2o.order_id=orders.id; */ try { cursor[DBIDX_C2O].Find(c.GetKey()); } catch (DatabaseException e) { // no order for this customer? if (e.ErrorCode == UpsConst.UPS_KEY_NOT_FOUND) continue; Console.Out.WriteLine("cursor.Find failed: " + e); return; } do { /* * load the order; orderId is a byteArray with the ID of the * Order; the record of the item is a byteArray with the * name of the assigned employee * * SELECT * FROM orders WHERE id = order_id; */ byte[] orderId = cursor[DBIDX_C2O].GetRecord(); cursor[DBIDX_ORDER].Find(orderId); String assignee = enc.GetString(cursor[DBIDX_ORDER].GetRecord()); Console.Out.WriteLine(" order: " + BitConverter.ToInt32(orderId, 0) + " (assigned to " + assignee + ")"); /* * move to the next order of this customer * * the flag UPS_ONLY_DUPLICATES restricts the cursor * movement to the duplicates of the current key. */ try { cursor[DBIDX_C2O].MoveNext(UpsConst.UPS_ONLY_DUPLICATES); } catch (DatabaseException e) { // no more orders for this customer? if (e.ErrorCode == UpsConst.UPS_KEY_NOT_FOUND) break; Console.Out.WriteLine("cursor.MoveNext failed: " + e); return; } } while (1 == 1); } } } }
//================================================================================================= // Copyright 2017 Dirk Lemstra <https://graphicsmagick.codeplex.com/> // // Licensed under the ImageMagick License (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.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing permissions and // limitations under the License. //================================================================================================= using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Text; using System.Windows.Media.Imaging; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Fasterflect; namespace GraphicsMagick { public sealed class DrawableAffine: Drawable { internal DrawableAffine(object instance) : base(instance) { } public DrawableAffine(Matrix matrix) : base(AssemblyHelper.CreateInstance(Types.DrawableAffine, new Type[] {typeof(Matrix)}, matrix)) { } public DrawableAffine(Double scaleX, Double scaleY, Double shearX, Double shearY, Double translateX, Double translateY) : base(AssemblyHelper.CreateInstance(Types.DrawableAffine, new Type[] {typeof(Double), typeof(Double), typeof(Double), typeof(Double), typeof(Double), typeof(Double)}, scaleX, scaleY, shearX, shearY, translateX, translateY)) { } public Double ScaleX { get { object result; try { result = _Instance.GetPropertyValue("ScaleX"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("ScaleX", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double ScaleY { get { object result; try { result = _Instance.GetPropertyValue("ScaleY"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("ScaleY", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double ShearX { get { object result; try { result = _Instance.GetPropertyValue("ShearX"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("ShearX", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double ShearY { get { object result; try { result = _Instance.GetPropertyValue("ShearY"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("ShearY", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double TranslateX { get { object result; try { result = _Instance.GetPropertyValue("TranslateX"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("TranslateX", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } public Double TranslateY { get { object result; try { result = _Instance.GetPropertyValue("TranslateY"); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } return (Double)result; } set { try { _Instance.SetPropertyValue("TranslateY", value); } catch (Exception ex) { throw ExceptionHelper.Create(ex); } } } } }
#if !NET45PLUS // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableHashSet{T}.HashBucket"/> struct. /// </content> public partial class ImmutableHashSet<T> { /// <summary> /// The result of a mutation operation. /// </summary> internal enum OperationResult { /// <summary> /// The change required element(s) to be added or removed from the collection. /// </summary> SizeChanged, /// <summary> /// No change was required (the operation ended in a no-op). /// </summary> NoChangeRequired, } /// <summary> /// Contains all the keys in the collection that hash to the same value. /// </summary> internal struct HashBucket { /// <summary> /// One of the values in this bucket. /// </summary> private readonly T _firstValue; /// <summary> /// Any other elements that hash to the same value. /// </summary> /// <value> /// This is null if and only if the entire bucket is empty (including <see cref="_firstValue"/>). /// It's empty if <see cref="_firstValue"/> has an element but no additional elements. /// </value> private readonly ImmutableList<T>.Node _additionalElements; /// <summary> /// Initializes a new instance of the <see cref="HashBucket"/> struct. /// </summary> /// <param name="firstElement">The first element.</param> /// <param name="additionalElements">The additional elements.</param> private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null) { _firstValue = firstElement; _additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> internal bool IsEmpty { get { return _additionalElements == null; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Adds the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param> /// <returns>A new <see cref="HashBucket"/> that contains the added value and any values already held by this <see cref="HashBucket"/>.</returns> internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result) { if (this.IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(value); } if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0) { result = OperationResult.NoChangeRequired; return this; } result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.Add(value)); } /// <summary> /// Determines whether the <see cref="HashBucket"/> contains the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="valueComparer">The value comparer.</param> internal bool Contains(T value, IEqualityComparer<T> valueComparer) { if (this.IsEmpty) { return false; } return valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0; } /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="value">The value to search for.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="existingValue">The value from the set that the search found, or the original value if the search yielded no match.</param> /// <returns> /// A value indicating whether the search was successful. /// </returns> internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue) { if (!this.IsEmpty) { if (valueComparer.Equals(value, _firstValue)) { existingValue = _firstValue; return true; } int index = _additionalElements.IndexOf(value, valueComparer); if (index >= 0) { existingValue = _additionalElements[index]; return true; } } existingValue = value; return false; } /// <summary> /// Removes the specified value if it exists in the collection. /// </summary> /// <param name="value">The value.</param> /// <param name="equalityComparer">The equality comparer.</param> /// <param name="result">A description of the effect was on adding an element to this <see cref="HashBucket"/>.</param> /// <returns>A new <see cref="HashBucket"/> that does not contain the removed value and any values already held by this <see cref="HashBucket"/>.</returns> internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result) { if (this.IsEmpty) { result = OperationResult.NoChangeRequired; return this; } if (equalityComparer.Equals(_firstValue, value)) { if (_additionalElements.IsEmpty) { result = OperationResult.SizeChanged; return new HashBucket(); } else { // We can promote any element from the list into the first position, but it's most efficient // to remove the root node in the binary tree that implements the list. int indexOfRootNode = _additionalElements.Left.Count; result = OperationResult.SizeChanged; return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(indexOfRootNode)); } } int index = _additionalElements.IndexOf(value, equalityComparer); if (index < 0) { result = OperationResult.NoChangeRequired; return this; } else { result = OperationResult.SizeChanged; return new HashBucket(_firstValue, _additionalElements.RemoveAt(index)); } } /// <summary> /// Freezes this instance so that any further mutations require new memory allocations. /// </summary> internal void Freeze() { if (_additionalElements != null) { _additionalElements.Freeze(); } } /// <summary> /// Enumerates all the elements in this instance. /// </summary> internal struct Enumerator : IEnumerator<T>, IDisposable { /// <summary> /// The bucket being enumerated. /// </summary> private readonly HashBucket _bucket; /// <summary> /// A value indicating whether this enumerator has been disposed. /// </summary> private bool _disposed; /// <summary> /// The current position of this enumerator. /// </summary> private Position _currentPosition; /// <summary> /// The enumerator that represents the current position over the <see cref="_additionalElements"/> of the <see cref="HashBucket"/>. /// </summary> private ImmutableList<T>.Enumerator _additionalEnumerator; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet{T}.HashBucket.Enumerator"/> struct. /// </summary> /// <param name="bucket">The bucket.</param> internal Enumerator(HashBucket bucket) { _disposed = false; _bucket = bucket; _currentPosition = Position.BeforeFirst; _additionalEnumerator = default(ImmutableList<T>.Enumerator); } /// <summary> /// Describes the positions the enumerator state machine may be in. /// </summary> private enum Position { /// <summary> /// The first element has not yet been moved to. /// </summary> BeforeFirst, /// <summary> /// We're at the <see cref="_firstValue"/> of the containing bucket. /// </summary> First, /// <summary> /// We're enumerating the <see cref="_additionalElements"/> in the bucket. /// </summary> Additional, /// <summary> /// The end of enumeration has been reached. /// </summary> End, } /// <summary> /// Gets the current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Gets the current element. /// </summary> public T Current { get { this.ThrowIfDisposed(); switch (_currentPosition) { case Position.First: return _bucket._firstValue; case Position.Additional: return _additionalEnumerator.Current; default: throw new InvalidOperationException(); } } } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception> public bool MoveNext() { this.ThrowIfDisposed(); if (_bucket.IsEmpty) { _currentPosition = Position.End; return false; } switch (_currentPosition) { case Position.BeforeFirst: _currentPosition = Position.First; return true; case Position.First: if (_bucket._additionalElements.IsEmpty) { _currentPosition = Position.End; return false; } _currentPosition = Position.Additional; _additionalEnumerator = new ImmutableList<T>.Enumerator(_bucket._additionalElements); return _additionalEnumerator.MoveNext(); case Position.Additional: return _additionalEnumerator.MoveNext(); case Position.End: return false; default: throw new InvalidOperationException(); } } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created. </exception> public void Reset() { this.ThrowIfDisposed(); _additionalEnumerator.Dispose(); _currentPosition = Position.BeforeFirst; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _disposed = true; _additionalEnumerator.Dispose(); } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed. /// </summary> private void ThrowIfDisposed() { if (_disposed) { Validation.Requires.FailObjectDisposed(this); } } } } } } #endif
/* * JpegLib.cs - Implementation of the "DotGNU.Images.JpegLib" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software, you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY, without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program, if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace DotGNU.Images { using System; using System.IO; using System.Runtime.InteropServices; using OpenSystem.Platform; // This class imports definitions from "libjpeg" via PInvoke. Eventually we // may want to replace this with a managed JPEG library by compiling "libjpeg" // directly with "pnetC". But this should work for now, assuming that the // underlying OS does indeed have "libjpeg" available. internal unsafe sealed class JpegLib { public const int JPEG_LIB_VERSION = 62; public const int DCTSIZE = 8; public const int DCTSIZE2 = 64; public const int NUM_QUANT_TBLS = 4; public const int NUM_HUFF_TBLS = 4; public const int NUM_ARITH_TBLS = 16; public const int MAX_COMPS_IN_SCAN = 4; public const int MAX_SAMP_FACTOR = 4; public const int C_MAX_BLOCKS_IN_MCU = 10; public const int D_MAX_BLOCKS_IN_MCU = 10; public enum J_COLOR_SPACE { JCS_UNKNOWN, JCS_GRAYSCALE, JCS_RGB, JCS_YCbCr, JCS_CMYK, JCS_YCCK }; public enum J_DCT_METHOD { JDCT_ISLOW, JDCT_IFAST, JDCT_FLOAT }; public enum J_DITHER_MODE { JDITHER_NONE, JDITHER_ORDERED, JDITHER_FS }; [StructLayout(LayoutKind.Sequential)] public struct jpeg_compress_struct { public IntPtr err; [NonSerializedAttribute] public void *mem; [NonSerializedAttribute] public void *progress; public IntPtr client_data; public Int is_decompressor; public Int global_state; [NonSerializedAttribute] public jpeg_destination_mgr *dest; public UInt image_width; public UInt image_height; public Int input_components; public J_COLOR_SPACE in_color_space; public double input_gamma; public Int data_precision; public Int num_components; public J_COLOR_SPACE jpeg_color_space; [NonSerializedAttribute] public void *comp_info; [NonSerializedAttribute] public void *quant_tbl_ptrs_0; [NonSerializedAttribute] public void *quant_tbl_ptrs_1; [NonSerializedAttribute] public void *quant_tbl_ptrs_2; [NonSerializedAttribute] public void *quant_tbl_ptrs_3; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_0; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_1; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_2; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_3; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_0; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_1; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_2; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_3; public UChar arith_dc_L_0; public UChar arith_dc_L_1; public UChar arith_dc_L_2; public UChar arith_dc_L_3; public UChar arith_dc_L_4; public UChar arith_dc_L_5; public UChar arith_dc_L_6; public UChar arith_dc_L_7; public UChar arith_dc_L_8; public UChar arith_dc_L_9; public UChar arith_dc_L_10; public UChar arith_dc_L_11; public UChar arith_dc_L_12; public UChar arith_dc_L_13; public UChar arith_dc_L_14; public UChar arith_dc_L_15; public UChar arith_dc_U_0; public UChar arith_dc_U_1; public UChar arith_dc_U_2; public UChar arith_dc_U_3; public UChar arith_dc_U_4; public UChar arith_dc_U_5; public UChar arith_dc_U_6; public UChar arith_dc_U_7; public UChar arith_dc_U_8; public UChar arith_dc_U_9; public UChar arith_dc_U_10; public UChar arith_dc_U_11; public UChar arith_dc_U_12; public UChar arith_dc_U_13; public UChar arith_dc_U_14; public UChar arith_dc_U_15; public UChar arith_dc_K_0; public UChar arith_dc_K_1; public UChar arith_dc_K_2; public UChar arith_dc_K_3; public UChar arith_dc_K_4; public UChar arith_dc_K_5; public UChar arith_dc_K_6; public UChar arith_dc_K_7; public UChar arith_dc_K_8; public UChar arith_dc_K_9; public UChar arith_dc_K_10; public UChar arith_dc_K_11; public UChar arith_dc_K_12; public UChar arith_dc_K_13; public UChar arith_dc_K_14; public UChar arith_dc_K_15; public Int num_scans; [NonSerializedAttribute] public void *scan_info; public Int raw_data_in; public Int arith_code; public Int optimize_coding; public Int CCIR601_sampling; public Int smoothing_factor; public J_DCT_METHOD dct_method; public UInt restart_interval; public Int restart_in_rows; public Int write_JFIF_header; public UChar JFIF_major_version; public UChar JFIF_minor_version; public UChar density_unit; public UShort X_density; public UShort Y_density; public Int write_Adobe_marker; public UInt next_scanline; public Int progressive_mode; public Int max_h_samp_factor; public Int max_v_samp_factor; public UInt total_iMCU_rows; public Int comps_in_scan; [NonSerializedAttribute] public void *cur_comp_info_0; [NonSerializedAttribute] public void *cur_comp_info_1; [NonSerializedAttribute] public void *cur_comp_info_2; [NonSerializedAttribute] public void *cur_comp_info_3; public UInt MCUs_per_row; public UInt MCU_rows_in_scan; public Int blocks_in_MCU; public Int MCU_membership_0; public Int MCU_membership_1; public Int MCU_membership_2; public Int MCU_membership_3; public Int MCU_membership_4; public Int MCU_membership_5; public Int MCU_membership_6; public Int MCU_membership_7; public Int MCU_membership_8; public Int MCU_membership_9; public Int Ss, Se, Ah, Al; [NonSerializedAttribute] public void *master; [NonSerializedAttribute] public void *main; [NonSerializedAttribute] public void *prep; [NonSerializedAttribute] public void *coef; [NonSerializedAttribute] public void *marker; [NonSerializedAttribute] public void *cconvert; [NonSerializedAttribute] public void *downsample; [NonSerializedAttribute] public void *fdct; [NonSerializedAttribute] public void *entropy; [NonSerializedAttribute] public void *script_space; public Int script_space_size; }; // struct jpeg_compress_struct [StructLayout(LayoutKind.Sequential)] public struct jpeg_decompress_struct { public IntPtr err; [NonSerializedAttribute] public void *mem; [NonSerializedAttribute] public void *progress; public IntPtr client_data; public Int is_decompressor; public Int global_state; [NonSerializedAttribute] public jpeg_source_mgr *src; public UInt image_width; public UInt image_height; public Int num_components; public J_COLOR_SPACE jpeg_color_space; public J_COLOR_SPACE out_color_space; public UInt scale_num, scale_denom; public double output_gamma; public Int buffered_image; public Int raw_data_out; public J_DCT_METHOD dct_method; public Int do_fancy_upsampling; public Int do_block_smoothing; public Int quantize_colors; public J_DITHER_MODE dither_mode; public Int two_pass_quantize; public Int desired_number_of_colors; public Int enable_1pass_quant; public Int enable_external_quant; public Int enable_2pass_quant; public UInt output_width; public UInt output_height; public Int out_color_components; public Int output_components; public Int rec_outbuf_height; public Int actual_number_of_colors; [NonSerializedAttribute] public void *colormap; public UInt output_scanline; public Int input_scan_number; public UInt input_iMCU_row; public Int output_scan_number; public UInt output_iMCU_row; [NonSerializedAttribute] public void *coef_bits; [NonSerializedAttribute] public void *quant_tbl_ptrs_0; [NonSerializedAttribute] public void *quant_tbl_ptrs_1; [NonSerializedAttribute] public void *quant_tbl_ptrs_2; [NonSerializedAttribute] public void *quant_tbl_ptrs_3; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_0; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_1; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_2; [NonSerializedAttribute] public void *dc_huff_tbl_ptrs_3; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_0; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_1; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_2; [NonSerializedAttribute] public void *ac_huff_tbl_ptrs_3; public Int data_precision; [NonSerializedAttribute] public void *comp_info; public Int progressive_mode; public Int arith_code; public UChar arith_dc_L_0; public UChar arith_dc_L_1; public UChar arith_dc_L_2; public UChar arith_dc_L_3; public UChar arith_dc_L_4; public UChar arith_dc_L_5; public UChar arith_dc_L_6; public UChar arith_dc_L_7; public UChar arith_dc_L_8; public UChar arith_dc_L_9; public UChar arith_dc_L_10; public UChar arith_dc_L_11; public UChar arith_dc_L_12; public UChar arith_dc_L_13; public UChar arith_dc_L_14; public UChar arith_dc_L_15; public UChar arith_dc_U_0; public UChar arith_dc_U_1; public UChar arith_dc_U_2; public UChar arith_dc_U_3; public UChar arith_dc_U_4; public UChar arith_dc_U_5; public UChar arith_dc_U_6; public UChar arith_dc_U_7; public UChar arith_dc_U_8; public UChar arith_dc_U_9; public UChar arith_dc_U_10; public UChar arith_dc_U_11; public UChar arith_dc_U_12; public UChar arith_dc_U_13; public UChar arith_dc_U_14; public UChar arith_dc_U_15; public UChar arith_dc_K_0; public UChar arith_dc_K_1; public UChar arith_dc_K_2; public UChar arith_dc_K_3; public UChar arith_dc_K_4; public UChar arith_dc_K_5; public UChar arith_dc_K_6; public UChar arith_dc_K_7; public UChar arith_dc_K_8; public UChar arith_dc_K_9; public UChar arith_dc_K_10; public UChar arith_dc_K_11; public UChar arith_dc_K_12; public UChar arith_dc_K_13; public UChar arith_dc_K_14; public UChar arith_dc_K_15; public UInt restart_interval; public Int saw_JFIF_marker; public UChar JFIF_major_version; public UChar JFIF_minor_version; public UChar density_unit; public UShort X_density; public UShort Y_density; public Int saw_Adobe_marker; public UChar Adobe_transform; public Int CCIR601_sampling; [NonSerializedAttribute] public void *marker_list; public Int max_h_samp_factor; public Int max_v_samp_factor; public Int min_DCT_scaled_size; public UInt total_iMCU_rows; [NonSerializedAttribute] public void *sample_range_limit; public Int comps_in_scan; [NonSerializedAttribute] public void *cur_comp_info_0; [NonSerializedAttribute] public void *cur_comp_info_1; [NonSerializedAttribute] public void *cur_comp_info_2; [NonSerializedAttribute] public void *cur_comp_info_3; public UInt MCUs_per_row; public UInt MCU_rows_in_scan; public Int blocks_in_MCU; public Int MCU_membership_0; public Int MCU_membership_1; public Int MCU_membership_2; public Int MCU_membership_3; public Int MCU_membership_4; public Int MCU_membership_5; public Int MCU_membership_6; public Int MCU_membership_7; public Int MCU_membership_8; public Int MCU_membership_9; public Int Ss, Se, Ah, Al; public Int unread_marker; [NonSerializedAttribute] public void *master; [NonSerializedAttribute] public void *main; [NonSerializedAttribute] public void *coef; [NonSerializedAttribute] public void *post; [NonSerializedAttribute] public void *inputctl; [NonSerializedAttribute] public void *marker; [NonSerializedAttribute] public void *entropy; [NonSerializedAttribute] public void *idct; [NonSerializedAttribute] public void *upsample; [NonSerializedAttribute] public void *cconvert; [NonSerializedAttribute] public void *cquantize; }; // struct jpeg_decompress_struct public delegate void init_source_type (ref jpeg_decompress_struct cinfo); public delegate Int fill_input_buffer_type (ref jpeg_decompress_struct cinfo); public delegate void skip_input_data_type (ref jpeg_decompress_struct cinfo, Long num_bytes); public delegate Int resync_to_restart_type (ref jpeg_decompress_struct cinfo, Int desired); public delegate void term_source_type (ref jpeg_decompress_struct cinfo); [StructLayout(LayoutKind.Sequential)] public struct jpeg_source_mgr { public IntPtr next_input_byte; public size_t bytes_in_buffer; public init_source_type init_source; public fill_input_buffer_type fill_input_buffer; public skip_input_data_type skip_input_data; public resync_to_restart_type resync_to_restart; public term_source_type term_source; }; // struct jpeg_source_mgr public delegate void init_destination_type (ref jpeg_compress_struct cinfo); public delegate Int empty_output_buffer_type (ref jpeg_compress_struct cinfo); public delegate void term_destination_type (ref jpeg_compress_struct cinfo); [StructLayout(LayoutKind.Sequential)] public struct jpeg_destination_mgr { public IntPtr next_output_byte; public size_t free_in_buffer; public init_destination_type init_destination; public empty_output_buffer_type empty_output_buffer; public term_destination_type term_destination; }; // struct jpeg_destination_mgr [DllImport("jpeg")] extern public static void jpeg_CreateCompress (ref jpeg_compress_struct cinfo, Int version, size_t structsize); public static void jpeg_create_compress(ref jpeg_compress_struct cinfo) { jpeg_CreateCompress(ref cinfo, (Int)JPEG_LIB_VERSION, (size_t)(sizeof(jpeg_compress_struct))); } [DllImport("jpeg")] extern public static void jpeg_CreateDecompress (ref jpeg_decompress_struct cinfo, Int version, size_t structsize); public static void jpeg_create_decompress(ref jpeg_decompress_struct cinfo) { jpeg_CreateDecompress(ref cinfo, (Int)JPEG_LIB_VERSION, (size_t)(sizeof(jpeg_decompress_struct))); } [DllImport("jpeg")] extern public static void jpeg_destroy_compress (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_destroy_decompress (ref jpeg_decompress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_set_defaults (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_set_colorspace (ref jpeg_compress_struct cinfo, J_COLOR_SPACE colorspace); [DllImport("jpeg")] extern public static void jpeg_default_colorspace (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_set_quality (ref jpeg_compress_struct cinfo, Int quality, Int force_baseline); [DllImport("jpeg")] extern public static void jpeg_set_linear_quality (ref jpeg_compress_struct cinfo, Int scale_factor, Int force_baseline); [DllImport("jpeg")] extern public static void jpeg_add_quant_table (ref jpeg_compress_struct cinfo, Int which_tbl, void *basic_table, Int scale_factor, Int force_baseline); [DllImport("jpeg")] extern public static Int jpeg_quality_scaling(Int quality); [DllImport("jpeg")] extern public static void jpeg_simple_progression (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_suppress_tables (ref jpeg_compress_struct cinfo, Int suppress); [DllImport("jpeg")] extern public static void *jpeg_alloc_quant_table (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void *jpeg_alloc_quant_table (ref jpeg_decompress_struct cinfo); [DllImport("jpeg")] extern public static void *jpeg_alloc_huff_table (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void *jpeg_alloc_huff_table (ref jpeg_decompress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_start_compress (ref jpeg_compress_struct cinfo, Int write_all_tables); // Note: can only be used 1 scanline at a time. [DllImport("jpeg")] extern public static UInt jpeg_write_scanlines (ref jpeg_compress_struct cinfo, ref IntPtr scanline, UInt num_lines); [DllImport("jpeg")] extern public static void jpeg_finish_compress (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_write_tables (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_calc_output_dimensions (ref jpeg_decompress_struct cinfo); [DllImport("jpeg")] extern public static Int jpeg_read_header (ref jpeg_decompress_struct cinfo, Int require_image); public const Int JPEG_SUSPENDED = (Int)0; public const Int JPEG_HEADER_OK = (Int)1; public const Int JPEG_HEADER_TABLES_ONLY = (Int)2; [DllImport("jpeg")] extern public static Int jpeg_start_decompress (ref jpeg_decompress_struct cinfo); // Note: can only be used 1 scanline at a time. [DllImport("jpeg")] extern public static UInt jpeg_read_scanlines (ref jpeg_decompress_struct cinfo, ref IntPtr scanline, UInt max_lines); [DllImport("jpeg")] extern public static Int jpeg_finish_decompress (ref jpeg_decompress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_abort_compress (ref jpeg_compress_struct cinfo); [DllImport("jpeg")] extern public static void jpeg_abort_decompress (ref jpeg_decompress_struct cinfo); [DllImport("jpeg")] extern public static Int jpeg_resync_to_restart (ref jpeg_decompress_struct cinfo, Int desired); [DllImport("jpeg")] extern public static IntPtr jpeg_std_error(IntPtr err); // State data for stream processing. private class StreamState { public IntPtr buf; public byte[] buffer; public Stream stream; public bool sawEOF; }; // class StreamState // Get the stream state for a decompress structure. private static StreamState GetStreamState(ref jpeg_decompress_struct cinfo) { GCHandle handle = (GCHandle)(cinfo.client_data); return (StreamState)(handle.Target); } // Initialize a stream data source. private static void init_source(ref jpeg_decompress_struct cinfo) { // Nothing to do here: already initialized. } // Fill an input buffer from a stream. private static Int fill_input_buffer(ref jpeg_decompress_struct cinfo) { int len; StreamState state = GetStreamState(ref cinfo); if(!(state.sawEOF)) { len = state.stream.Read (state.buffer, 0, state.buffer.Length); if(len > 0) { Marshal.Copy(state.buffer, 0, state.buf, len); cinfo.src->next_input_byte = state.buf; cinfo.src->bytes_in_buffer = (size_t)len; return (Int)1; } state.sawEOF = true; } // Insert an EOI marker to indicate end of stream to "libjpeg". Marshal.WriteByte(state.buf, 0, (byte)0xFF); Marshal.WriteByte(state.buf, 1, (byte)0xD9); cinfo.src->next_input_byte = state.buf; cinfo.src->bytes_in_buffer = (size_t)2; return (Int)1; } // Skip data in an input stream. private static void skip_input_data (ref jpeg_decompress_struct cinfo, Long num_bytes) { #if __CSCC__ jpeg_source_mgr *src = cinfo.src; int num = (int)num_bytes; if(num > 0) { while(num > (int)(src->bytes_in_buffer)) { num -= (int)(src->bytes_in_buffer); fill_input_buffer(ref cinfo); } src->next_input_byte = new IntPtr((src->next_input_byte.ToInt64()) + num); src->bytes_in_buffer = (size_t)(((int)(src->bytes_in_buffer)) - num); } #endif } // Terminate an input source. private static void term_source(ref jpeg_decompress_struct cinfo) { // Nothing to do here. } // Convert a stream into a source manager. public static void StreamToSourceManager (ref jpeg_decompress_struct cinfo, Stream stream, byte[] prime, int primeLen) { // Allocate a state structure and store it in "cinfo". IntPtr buf = Marshal.AllocHGlobal(4096); StreamState state = new StreamState(); state.buf = buf; state.buffer = new byte [4096]; state.stream = stream; cinfo.client_data = (IntPtr)(GCHandle.Alloc(state)); // We prime the input buffer with the JPEG magic number // if some higher-level process has already read it. int len; if(prime != null) { len = primeLen; Marshal.Copy(prime, 0, buf, len); } else { len = 0; } // Create the managed version of "jpeg_source_mgr". jpeg_source_mgr mgr = new jpeg_source_mgr(); mgr.next_input_byte = buf; mgr.bytes_in_buffer = (size_t)len; mgr.init_source = new init_source_type(init_source); mgr.fill_input_buffer = new fill_input_buffer_type(fill_input_buffer); mgr.skip_input_data = new skip_input_data_type(skip_input_data); mgr.resync_to_restart = new resync_to_restart_type(jpeg_resync_to_restart); mgr.term_source = new term_source_type(term_source); // Convert it into the unmanaged version and store it. #if __CSCC__ IntPtr umgr = Marshal.AllocHGlobal(sizeof(jpeg_source_mgr)); Marshal.StructureToPtr(mgr, umgr, false); cinfo.src = (jpeg_source_mgr *)umgr; #endif } // Free a source manager. public static void FreeSourceManager(ref jpeg_decompress_struct cinfo) { GCHandle handle = (GCHandle)(cinfo.client_data); StreamState state = (StreamState)(handle.Target); Marshal.FreeHGlobal(state.buf); handle.Free(); Marshal.FreeHGlobal((IntPtr)(cinfo.src)); cinfo.client_data = IntPtr.Zero; cinfo.src = null; } // Get the stream state for a compress structure. private static StreamState GetStreamState(ref jpeg_compress_struct cinfo) { GCHandle handle = (GCHandle)(cinfo.client_data); return (StreamState)(handle.Target); } // Initialize a stream data destination. private static void init_destination(ref jpeg_compress_struct cinfo) { // Nothing to do here: already initialized. } // Empty an output buffer to a stream. private static Int empty_output_buffer(ref jpeg_compress_struct cinfo) { int len; StreamState state = GetStreamState(ref cinfo); len = state.buffer.Length; Marshal.Copy(state.buf, state.buffer, 0, len); state.stream.Write(state.buffer, 0, len); cinfo.dest->next_output_byte = state.buf; cinfo.dest->free_in_buffer = (size_t)len; return (Int)1; } // Terminate an output destination. private static void term_destination(ref jpeg_compress_struct cinfo) { // Nothing to do here. } // Convert a stream into a destination manager. public static void StreamToDestinationManager (ref jpeg_compress_struct cinfo, Stream stream) { // Allocate a state structure and store it in "cinfo". IntPtr buf = Marshal.AllocHGlobal(4096); StreamState state = new StreamState(); state.buf = buf; state.buffer = new byte [4096]; state.stream = stream; cinfo.client_data = (IntPtr)(GCHandle.Alloc(state)); // Create the managed version of "jpeg_destination_mgr". jpeg_destination_mgr mgr = new jpeg_destination_mgr(); mgr.next_output_byte = buf; mgr.free_in_buffer = (size_t)4096; mgr.init_destination = new init_destination_type(init_destination); mgr.empty_output_buffer = new empty_output_buffer_type(empty_output_buffer); mgr.term_destination = new term_destination_type(term_destination); // Convert it into the unmanaged version and store it. #if __CSCC__ IntPtr umgr = Marshal.AllocHGlobal (sizeof(jpeg_destination_mgr)); Marshal.StructureToPtr(mgr, umgr, false); cinfo.dest = (jpeg_destination_mgr *)umgr; #endif } // Free a destination manager. public static void FreeDestinationManager(ref jpeg_compress_struct cinfo) { GCHandle handle = (GCHandle)(cinfo.client_data); StreamState state = (StreamState)(handle.Target); Marshal.FreeHGlobal(state.buf); handle.Free(); Marshal.FreeHGlobal((IntPtr)(cinfo.dest)); cinfo.client_data = IntPtr.Zero; cinfo.dest = null; } // Create a standard error handler. public static IntPtr CreateErrorHandler() { IntPtr err = Marshal.AllocHGlobal(512); return jpeg_std_error(err); } // Free a standard error handler. public static void FreeErrorHandler(IntPtr err) { Marshal.FreeHGlobal(err); } // Determine if the "libjpeg" library is present. public static bool JpegLibraryPresent() { try { // Call an innocuous function, which will cause an // exception throw if the library is not present. jpeg_quality_scaling(0); return true; } catch(Exception) { return false; } } }; // class JpegLib }; // namespace DotGNU.Images
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.IO { public sealed partial class DirectoryInfo : FileSystemInfo { private string _name; public DirectoryInfo(string path) { Init(originalPath: PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path, fullPath: Path.GetFullPath(path), isNormalized: true); } internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false) { Init(originalPath, fullPath, fileName, isNormalized); } private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false) { // Want to throw the original argument name OriginalPath = originalPath ?? throw new ArgumentNullException("path"); fullPath = fullPath ?? originalPath; Debug.Assert(!isNormalized || !PathInternal.IsPartiallyQualified(fullPath), "should be fully qualified if normalized"); fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath); _name = fileName ?? (PathHelpers.IsRoot(fullPath) ? fullPath : Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath))); FullPath = fullPath; DisplayPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ? "." : originalPath; } public override string Name => _name; public DirectoryInfo Parent { get { string s = FullPath; // FullPath might end in either "parent\child" or "parent\child", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. if (!PathHelpers.IsRoot(s)) { s = PathHelpers.TrimEndingDirectorySeparator(s); } string parentName = Path.GetDirectoryName(s); return parentName != null ? new DirectoryInfo(parentName, null) : null; } } public DirectoryInfo CreateSubdirectory(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); return CreateSubdirectoryHelper(path); } private DirectoryInfo CreateSubdirectoryHelper(string path) { Debug.Assert(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); string newDirs = Path.Combine(FullPath, path); string fullPath = Path.GetFullPath(newDirs); if (0 != string.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path)); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public FileInfo[] GetFiles(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). private FileInfo[] InternalGetFiles(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); return EnumerableHelpers.ToArray(enumerable); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { get { string rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } public void MoveTo(string destDirName) { if (destDirName == null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); string destination = Path.GetFullPath(destDirName); string destinationWithSeparator = destination; if (destinationWithSeparator[destinationWithSeparator.Length - 1] != Path.DirectorySeparatorChar) destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString; string fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; StringComparison pathComparison = PathInternal.StringComparison; if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); string sourceRoot = Path.GetPathRoot(fullSourcePath); string destinationRoot = Path.GetPathRoot(destinationWithSeparator); if (!string.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); // Windows will throw if the source file/directory doesn't exist, we preemptively check // to make sure our cross platform behavior matches NetFX behavior. if (!Exists && !FileSystem.Current.FileExists(FullPath)) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath)); if (FileSystem.Current.DirectoryExists(destinationWithSeparator)) throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator)); FileSystem.Current.MoveDirectory(FullPath, destination); Init(originalPath: destDirName, fullPath: destinationWithSeparator, fileName: _name, isNormalized: true); // Flush any cached information about the directory. Invalidate(); } public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } /// <summary> /// Returns the original path. Use FullPath or Name properties for the path / directory name. /// </summary> public override string ToString() { return DisplayPath; } } }
using System; using System.Collections.Generic; using System.Linq; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Utilities; namespace Signum.React.Selenium; public class ResultTableProxy { public WebDriver Selenium { get; private set; } public IWebElement Element; SearchControlProxy SearchControl; public ResultTableProxy(IWebElement element, SearchControlProxy searchControl) { this.Selenium = element.GetDriver(); this.Element = element; this.SearchControl = searchControl; } public WebElementLocator ResultTableElement { get { return this.Element.WithLocator(By.CssSelector("table.sf-search-results")); } } public WebElementLocator RowsLocator { get { return this.Element.WithLocator(By.CssSelector("table.sf-search-results > tbody > tr")); } } public List<ResultRowProxy> AllRows() { return RowsLocator.FindElements().Select(e => new ResultRowProxy(e)).ToList(); } public ResultRowProxy RowElement(int rowIndex) { return new ResultRowProxy(RowElementLocator(rowIndex).WaitVisible()); } private WebElementLocator RowElementLocator(int rowIndex) { return this.Element.WithLocator(By.CssSelector("tr[data-row-index='{0}']".FormatWith(rowIndex))); } public ResultRowProxy RowElement(Lite<IEntity> lite) { return new ResultRowProxy(RowElementLocator(lite).WaitVisible()); } private WebElementLocator RowElementLocator(Lite<IEntity> lite) { return this.Element.WithLocator(By.CssSelector("tr[data-entity='{0}']".FormatWith(lite.Key()))); } public List<Lite<IEntity>> SelectedEntities() { return RowsLocator.FindElements() .Where(tr => tr.IsElementPresent(By.CssSelector("input.sf-td-selection:checked"))) .Select(a => Lite.Parse<IEntity>(a.GetAttribute("data-entity"))) .ToList(); } public WebElementLocator CellElement(int rowIndex, string token) { var columnIndex = GetColumnIndex(token); return RowElement(rowIndex).CellElement(columnIndex); } public WebElementLocator CellElement(Lite<IEntity> lite, string token) { var columnIndex = GetColumnIndex(token); return RowElement(lite).CellElement(columnIndex); } public int GetColumnIndex(string token) { var tokens = this.GetColumnTokens(); var index = tokens.IndexOf(token); if (index == -1) throw new InvalidOperationException("Token {0} not found between {1}".FormatWith(token, tokens.NotNull().CommaAnd())); return index; } public void SelectRow(int rowIndex) { RowElement(rowIndex).SelectedCheckbox.Find().Click(); } public void SelectRow(params int[] rowIndexes) { foreach (var index in rowIndexes) SelectRow(index); } public void SelectRow(Lite<IEntity> lite) { RowElement(lite).SelectedCheckbox.Find().Click(); } public void SelectAllRows() { SelectRow(0.To(RowsCount()).ToArray()); } public WebElementLocator HeaderElement { get { return this.Element.WithLocator(By.CssSelector("thead > tr > th")); } } public string[] GetColumnTokens() { var ths = this.Element.FindElements(By.CssSelector("thead > tr > th")).ToList(); return ths.Select(a => a.GetAttribute("data-column-name")).ToArray(); } public WebElementLocator HeaderCellElement(string token) { return this.HeaderElement.CombineCss("[data-column-name='{0}']".FormatWith(token)); } public ResultTableProxy OrderBy(string token) { OrderBy(token, OrderType.Ascending); return this; } public ResultTableProxy OrderByDescending(string token) { OrderBy(token, OrderType.Descending); return this; } public ResultTableProxy ThenBy(string token) { OrderBy(token, OrderType.Ascending, thenBy: true); return this; } public ResultTableProxy ThenByDescending(string token) { OrderBy(token, OrderType.Descending, thenBy: true); return this; } private void OrderBy(string token, OrderType orderType, bool thenBy = false) { do { SearchControl.WaitSearchCompleted(() => { Actions action = new Actions(Selenium); if (thenBy) action.KeyDown(Keys.Shift); HeaderCellElement(token).Find().Click(); if (thenBy) action.KeyUp(Keys.Shift); }); } while (!HeaderCellElement(token).CombineCss(SortSpan(orderType)).IsPresent()); } public bool HasColumn(string token) { return HeaderCellElement(token).IsPresent(); } public void RemoveColumn(string token) { var headerLocator = HeaderCellElement(token); headerLocator.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.CssSelector(".sf-remove-header")).Click(); headerLocator.WaitNoPresent(); } public WebElementLocator EntityLink(Lite<IEntity> lite) { var entityIndex = GetColumnIndex("Entity"); return RowElement(lite).EntityLink(entityIndex); } public WebElementLocator EntityLink(int rowIndex) { var entityIndex = GetColumnIndex("Entity"); return RowElement(rowIndex).EntityLink(entityIndex); } public FramePageProxy<T> EntityClickInPlace<T>(Lite<T> lite) where T : Entity { EntityLink(lite).Find().Click(); return new FramePageProxy<T>(this.Selenium); } public FramePageProxy<T> EntityClickInPlace<T>(int rowIndex) where T : Entity { EntityLink(rowIndex).Find().Click(); return new FramePageProxy<T>(this.Selenium); } public FrameModalProxy<T> EntityClick<T>(Lite<T> lite) where T : Entity { var element = EntityLink(lite).Find().CaptureOnClick(); return new FrameModalProxy<T>(element); } public void WaitRows(int rows) { this.Selenium.Wait(() => this.RowsCount() == rows); } public FrameModalProxy<T> EntityClick<T>(int rowIndex) where T : Entity { var element = EntityLink(rowIndex).Find().CaptureOnClick(); return new FrameModalProxy<T>(element); } public FramePageProxy<T> EntityClickNormalPage<T>(Lite<T> lite) where T : Entity { EntityLink(lite).Find().Click(); return new FramePageProxy<T>(this.Element.GetDriver()); } public FramePageProxy<T> EntityClickNormalPage<T>(int rowIndex) where T : Entity { EntityLink(rowIndex).Find().Click(); return new FramePageProxy<T>(this.Element.GetDriver()); } public EntityContextMenuProxy EntityContextMenu(int rowIndex, string columnToken = "Entity") { CellElement(rowIndex, columnToken).Find().ContextClick(); var element = this.SearchControl.WaitContextMenu(); return new EntityContextMenuProxy(this, element); } public EntityContextMenuProxy EntityContextMenu(Lite<Entity> lite, string columnToken = "Entity") { CellElement(lite, columnToken).Find().ContextClick(); var element = this.SearchControl.WaitContextMenu(); return new EntityContextMenuProxy(this, element); } public int RowsCount() { return this.Element.FindElements(By.CssSelector("tbody > tr[data-entity]")).Count; } public Lite<Entity> EntityInIndex(int rowIndex) { var result = this.Element.FindElement(By.CssSelector("tbody > tr:nth-child(" + (rowIndex + 1) + ")")).GetAttribute("data-entity"); return Lite.Parse(result); } public bool IsHeaderMarkedSorted(string token) { return IsHeaderMarkedSorted(token, OrderType.Ascending) || IsHeaderMarkedSorted(token, OrderType.Descending); } public bool IsHeaderMarkedSorted(string token, OrderType orderType) { return HeaderCellElement(token).CombineCss(SortSpan(orderType)).IsPresent(); } private static string SortSpan(OrderType orderType) { return " span.sf-header-sort." + (orderType == OrderType.Ascending ? "asc" : "desc"); } public bool IsElementInCell(int rowIndex, string token, By locator) { return CellElement(rowIndex, token).Find().FindElements(locator).Any(); } public ColumnEditorProxy EditColumnName(string token) { var headerSelector = this.HeaderCellElement(token); headerSelector.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.ClassName("sf-edit-header")).Click(); return SearchControl.ColumnEditor(); } public ColumnEditorProxy AddColumnBefore(string token) { var headerSelector = this.HeaderCellElement(token); headerSelector.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.ClassName("sf-insert-header")).Click(); return SearchControl.ColumnEditor(); } public void RemoveColumnBefore(string token) { var headerSelector = this.HeaderCellElement(token); headerSelector.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.ClassName("sf-remove-header")).Click(); } public void WaitSuccess(Lite<IEntity> lite) => WaitSuccess(new List<Lite<IEntity>> { lite }); public void WaitSuccess(List<Lite<IEntity>> lites) { lites.ForEach(lite => RowElementLocator(lite).CombineCss(".sf-entity-ctxmenu-success").WaitVisible()); } public void WaitNoVisible(Lite<IEntity> lite) => WaitNoVisible(new List<Lite<IEntity>> { lite }); public void WaitNoVisible(List<Lite<IEntity>> lites) { lites.ToList().ForEach(lite => RowElementLocator(lite).WaitNoVisible()); } } public class ResultRowProxy { public IWebElement RowElement; public ResultRowProxy(IWebElement rowElement) { this.RowElement = rowElement; } public WebElementLocator SelectedCheckbox => new WebElementLocator(RowElement, By.CssSelector("input.sf-td-selection")); public WebElementLocator CellElement(int columnIndex) => new WebElementLocator(RowElement, By.CssSelector("td:nth-child({0})".FormatWith(columnIndex + 1))); public WebElementLocator EntityLink(int entityColumnIndex) => CellElement(entityColumnIndex).CombineCss("> a"); }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.GenerateFromMembers.GenerateEqualsAndGetHashCode; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.GenerateFromMembers.GenerateEqualsAndGetHashCode { public class GenerateEqualsAndGetHashCodeTests : AbstractCSharpCodeActionTest { protected override object CreateCodeRefactoringProvider(Workspace workspace) { return new GenerateEqualsAndGetHashCodeCodeRefactoringProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsSingleField() { await TestAsync( @"using System . Collections . Generic ; class Program { [|int a ;|] } ", @"using System . Collections . Generic ; class Program { int a ; public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && EqualityComparer < int > . Default . Equals ( a , program . a ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsLongName() { await TestAsync( @"using System . Collections . Generic ; class ReallyLongName { [|int a ;|] } ", @"using System . Collections . Generic ; class ReallyLongName { int a ; public override bool Equals ( object obj ) { var name = obj as ReallyLongName ; return name != null && EqualityComparer < int > . Default . Equals ( a , name . a ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsKeywordName() { await TestAsync( @"using System . Collections . Generic ; class ReallyLongLong { [|long a ;|] } ", @"using System . Collections . Generic ; class ReallyLongLong { long a ; public override bool Equals ( object obj ) { var @long = obj as ReallyLongLong ; return @long != null && EqualityComparer < long > . Default . Equals ( a , @long . a ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsProperty() { await TestAsync( @"using System . Collections . Generic ; class ReallyLongName { [|int a ; string B { get ; }|] } ", @"using System . Collections . Generic ; class ReallyLongName { int a ; string B { get ; } public override bool Equals ( object obj ) { var name = obj as ReallyLongName ; return name != null && EqualityComparer < int > . Default . Equals ( a , name . a ) && EqualityComparer < string > . Default . Equals ( B , name . B ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseTypeWithNoEquals() { await TestAsync( @"class Base { } class Program : Base { [|int i ;|] } ", @"using System . Collections . Generic; class Base { } class Program : Base { int i ; public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && EqualityComparer < int > . Default . Equals ( i , program . i ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsBaseWithOverriddenEquals() { await TestAsync( @"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Program : Base { [|int i ; string S { get ; }|] } ", @"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Program : Base { int i ; string S { get ; } public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && base . Equals ( obj ) && EqualityComparer < int > . Default . Equals ( i , program . i ) && EqualityComparer < string > . Default . Equals ( S , program . S ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsOverriddenDeepBase() { await TestAsync( @"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Middle : Base { } class Program : Middle { [|int i ; string S { get ; }|] } ", @"using System . Collections . Generic ; class Base { public override bool Equals ( object o ) { } } class Middle : Base { } class Program : Middle { int i ; string S { get ; } public override bool Equals ( object obj ) { var program = obj as Program ; return program != null && base . Equals ( obj ) && EqualityComparer < int > . Default . Equals ( i , program . i ) && EqualityComparer < string > . Default . Equals ( S , program . S ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsStruct() { await TestAsync( @"using System . Collections . Generic ; struct ReallyLongName { [|int i ; string S { get ; }|] } ", @"using System . Collections . Generic ; struct ReallyLongName { int i ; string S { get ; } public override bool Equals ( object obj ) { if ( ! ( obj is ReallyLongName ) ) { return false ; } var name = ( ReallyLongName ) obj ; return EqualityComparer < int > . Default . Equals ( i , name . i ) && EqualityComparer < string > . Default . Equals ( S , name . S ) ; } } ", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestEqualsGenericType() { var code = @" using System.Collections.Generic; class Program<T> { [|int i;|] } "; var expected = @" using System.Collections.Generic; class Program<T> { int i; public override bool Equals(object obj) { var program = obj as Program<T>; return program != null && EqualityComparer<int>.Default.Equals(i, program.i); } } "; await TestAsync(code, expected, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeSingleField() { await TestAsync( @"using System . Collections . Generic ; class Program { [|int i ;|] } ", @"using System . Collections . Generic ; class Program { int i ; public override int GetHashCode ( ) { return EqualityComparer < int > . Default . GetHashCode ( i ) ; } } ", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeTypeParameter() { await TestAsync( @"using System . Collections . Generic ; class Program < T > { [|T i ;|] } ", @"using System . Collections . Generic ; class Program < T > { T i ; public override int GetHashCode ( ) { return EqualityComparer < T > . Default . GetHashCode ( i ) ; } } ", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeGenericType() { await TestAsync( @"using System . Collections . Generic ; class Program < T > { [|Program < T > i ;|] } ", @"using System . Collections . Generic ; class Program < T > { Program < T > i ; public override int GetHashCode ( ) { return EqualityComparer < Program < T > > . Default . GetHashCode ( i ) ; } } ", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestGetHashCodeMultipleMembers() { await TestAsync( @"using System . Collections . Generic ; class Program { [|int i ; string S { get ; }|] } ", @"using System . Collections . Generic ; class Program { int i ; string S { get ; } public override int GetHashCode ( ) { var hashCode = EqualityComparer < int > . Default . GetHashCode ( i ) ; hashCode = hashCode * - 1521134295 + EqualityComparer < string > . Default . GetHashCode ( S ) ; return hashCode ; } } ", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText1() { await TestSmartTagTextAsync( @"using System . Collections . Generic ; class Program { [|bool b ; HashSet < string > s ;|] public Program ( bool b ) { this . b = b ; } } ", FeaturesResources.GenerateEqualsObject); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText2() { await TestSmartTagTextAsync( @"using System . Collections . Generic ; class Program { [|bool b ; HashSet < string > s ;|] public Program ( bool b ) { this . b = b ; } } ", FeaturesResources.GenerateGetHashCode, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TestSmartTagText3() { await TestSmartTagTextAsync( @"using System . Collections . Generic ; class Program { [|bool b ; HashSet < string > s ;|] public Program ( bool b ) { this . b = b ; } } ", FeaturesResources.GenerateBoth, index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuple_Disabled() { await TestAsync(@"using System . Collections . Generic ; class C { [|(int, string) a ;|] } ", @"using System . Collections . Generic ; class C { (int, string) a ; public override bool Equals ( object obj ) { var c = obj as C ; return c != null && EqualityComparer < (int, string) > . Default . Equals ( a , c . a ) ; } } ", index: 0, parseOptions: TestOptions.Regular.WithLanguageVersion(CodeAnalysis.CSharp.LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuples_Equals() { await TestAsync( @"using System . Collections . Generic ; class C { [|(int, string) a ;|] } ", @"using System . Collections . Generic ; class C { (int, string) a ; public override bool Equals ( object obj ) { var c = obj as C ; return c != null && EqualityComparer < (int, string) > . Default . Equals ( a , c . a ) ; } } ", index: 0, parseOptions: TestOptions.Regular.WithTuplesFeature(), withScriptOption: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TupleWithNames_Equals() { await TestAsync( @"using System . Collections . Generic ; class C { [|(int x, string y) a ;|] } ", @"using System . Collections . Generic ; class C { (int x, string y) a ; public override bool Equals ( object obj ) { var c = obj as C ; return c != null && EqualityComparer < (int x, string y) > . Default . Equals ( a , c . a ) ; } } ", index: 0, parseOptions: TestOptions.Regular.WithTuplesFeature(), withScriptOption: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task Tuple_HashCode() { await TestAsync( @"using System . Collections . Generic ; class Program { [|(int, string) i ;|] } ", @"using System . Collections . Generic ; class Program { (int, string) i ; public override int GetHashCode ( ) { return EqualityComparer < (int, string) > . Default . GetHashCode ( i ) ; } } ", index: 1, parseOptions: TestOptions.Regular.WithTuplesFeature(), withScriptOption: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEqualsAndGetHashCode)] public async Task TupleWithNames_HashCode() { await TestAsync( @"using System . Collections . Generic ; class Program { [|(int x, string y) i ;|] } ", @"using System . Collections . Generic ; class Program { (int x, string y) i ; public override int GetHashCode ( ) { return EqualityComparer < (int x, string y) > . Default . GetHashCode ( i ) ; } } ", index: 1, parseOptions: TestOptions.Regular.WithTuplesFeature(), withScriptOption: true); } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; using ZXing.QrCode.Internal; namespace ZXing.QrCode { /// <summary> /// This implementation can detect and decode QR Codes in an image. /// <author>Sean Owen</author> /// </summary> public class QRCodeReader : Reader { private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; private readonly Decoder decoder = new Decoder(); /// <summary> /// Gets the decoder. /// </summary> /// <returns></returns> protected Decoder getDecoder() { return decoder; } /// <summary> /// Locates and decodes a QR code in an image. /// /// <returns>a String representing the content encoded by the QR code</returns> /// </summary> public Result decode(BinaryBitmap image) { return decode(image, null); } /// <summary> /// Locates and decodes a barcode in some format within an image. This method also accepts /// hints, each possibly associated to some data, which may help the implementation decode. /// </summary> /// <param name="image">image of barcode to decode</param> /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/> /// to arbitrary data. The /// meaning of the data depends upon the hint type. The implementation may or may not do /// anything with these hints.</param> /// <returns> /// String which the barcode encodes /// </returns> public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { DecoderResult decoderResult; ResultPoint[] points; if (image == null || image.BlackMatrix == null) { // something is wrong with the image return null; } if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { var bits = extractPureBits(image.BlackMatrix); if (bits == null) return null; decoderResult = decoder.decode(bits, hints); points = NO_POINTS; } else { var detectorResult = new Detector(image.BlackMatrix).detect(hints); if (detectorResult == null) return null; decoderResult = decoder.decode(detectorResult.Bits, hints); points = detectorResult.Points; } if (decoderResult == null) return null; // If the code was mirrored: swap the bottom-left and the top-right points. var data = decoderResult.Other as QRCodeDecoderMetaData; if (data != null) { data.applyMirroredCorrection(points); } var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); var byteSegments = decoderResult.ByteSegments; if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } var ecLevel = decoderResult.ECLevel; if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } if (decoderResult.StructuredAppend) { result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber); result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity); } return result; } /// <summary> /// Resets any internal state the implementation has after a decode, to prepare it /// for reuse. /// </summary> public void reset() { // do nothing } /// <summary> /// This method detects a code in a "pure" image -- that is, pure monochrome image /// which contains only an unrotated, unskewed, image of a code, with some white border /// around it. This is a specialized method that works exceptionally fast in this special /// case. /// /// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" /> /// </summary> private static BitMatrix extractPureBits(BitMatrix image) { int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if (leftTopBlack == null || rightBottomBlack == null) { return null; } float moduleSize; if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize)) return null; int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; // Sanity check! if (left >= right || top >= bottom) { return null; } if (bottom - top != right - left) { // Special case, where bottom-right module wasn't black so we found something else in the last row // Assume it's a square, so use height as the width right = left + (bottom - top); } int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize); int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize); if (matrixWidth <= 0 || matrixHeight <= 0) { return null; } if (matrixHeight != matrixWidth) { // Only possibly decode square regions return null; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = (int)(moduleSize / 2.0f); top += nudge; left += nudge; // But careful that this does not sample off the edge int nudgedTooFarRight = left + (int)((matrixWidth - 1) * moduleSize) - (right - 1); if (nudgedTooFarRight > 0) { if (nudgedTooFarRight > nudge) { // Neither way fits; abort return null; } left -= nudgedTooFarRight; } int nudgedTooFarDown = top + (int)((matrixHeight - 1) * moduleSize) - (bottom - 1); if (nudgedTooFarDown > 0) { if (nudgedTooFarDown > nudge) { // Neither way fits; abort return null; } top -= nudgedTooFarDown; } // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + (int)(y * moduleSize); for (int x = 0; x < matrixWidth; x++) { if (image[left + (int)(x * moduleSize), iOffset]) { bits[x, y] = true; } } } return bits; } private static bool moduleSize(int[] leftTopBlack, BitMatrix image, out float msize) { int height = image.Height; int width = image.Width; int x = leftTopBlack[0]; int y = leftTopBlack[1]; bool inBlack = true; int transitions = 0; while (x < width && y < height) { if (inBlack != image[x, y]) { if (++transitions == 5) { break; } inBlack = !inBlack; } x++; y++; } if (x == width || y == height) { msize = 0.0f; return false; } msize = (x - leftTopBlack[0]) / 7.0f; return true; } } }
/* * 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 { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; /// <summary> /// Grid proxy with fake serialization. /// </summary> [Serializable] [ExcludeFromCodeCoverage] internal class IgniteProxy : IIgnite, IBinaryWriteAware, ICluster { /** */ [NonSerialized] private readonly Ignite _ignite; /// <summary> /// Default ctor for marshalling. /// </summary> public IgniteProxy() { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="ignite">Grid.</param> public IgniteProxy(Ignite ignite) { _ignite = ignite; } /** <inheritdoc /> */ public string Name { get { return _ignite.Name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ public IIgnite Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _ignite.GetCluster().ForLocal(); } /** <inheritdoc /> */ public ICompute GetCompute() { return _ignite.GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return _ignite.GetCluster().ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _ignite.GetCluster().ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(ICollection<Guid> ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { return _ignite.GetCluster().ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _ignite.GetCluster().ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _ignite.GetCluster().ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _ignite.GetCluster().ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _ignite.GetCluster().ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _ignite.GetCluster().ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _ignite.GetCluster().ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { return _ignite.GetCluster().ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _ignite.GetCluster().ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _ignite.GetCluster().ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _ignite.GetCluster().ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _ignite.GetCluster().ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _ignite.GetCluster().ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _ignite.GetCluster().GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _ignite.GetCluster().GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _ignite.GetCluster().GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _ignite.GetCluster().GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] public void Dispose() { _ignite.Dispose(); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { return _ignite.GetCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { return _ignite.GetOrCreateCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return _ignite.GetOrCreateCache<TK, TV>(configuration); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return _ignite.GetOrCreateCache<TK, TV>(configuration, nearConfiguration); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { return _ignite.CreateCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return _ignite.CreateCache<TK, TV>(configuration); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return _ignite.CreateCache<TK, TV>(configuration, nearConfiguration); } /** <inheritdoc /> */ public void DestroyCache(string name) { _ignite.DestroyCache(name); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _ignite.GetCluster().GetLocalNode(); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _ignite.GetCluster().PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _ignite.GetCluster().TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _ignite.GetCluster().GetTopology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _ignite.GetCluster().ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _ignite.GetCluster().ClientReconnectTask; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { return _ignite.GetDataStreamer<TK, TV>(cacheName); } /** <inheritdoc /> */ public IBinary GetBinary() { return _ignite.GetBinary(); } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string name) { return _ignite.GetAffinity(name); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _ignite.GetTransactions(); } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _ignite.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _ignite.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _ignite.GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { return _ignite.GetAtomicLong(name, initialValue, create); } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { return _ignite.GetConfiguration(); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return _ignite.CreateNearCache<TK, TV>(name, configuration); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return _ignite.GetOrCreateNearCache<TK, TV>(name, configuration); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { return _ignite.GetCacheNames(); } /** <inheritdoc /> */ public ILogger Logger { get { return _ignite.Logger; } } /** <inheritdoc /> */ public event EventHandler Stopping { add { _ignite.Stopping += value; } remove { _ignite.Stopping -= value; } } /** <inheritdoc /> */ public event EventHandler Stopped { add { _ignite.Stopped += value; } remove { _ignite.Stopped -= value; } } /** <inheritdoc /> */ public event EventHandler ClientDisconnected { add { _ignite.ClientDisconnected += value; } remove { _ignite.ClientDisconnected -= value; } } /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected { add { _ignite.ClientReconnected += value; } remove { _ignite.ClientReconnected -= value; } } /** <inheritdoc /> */ public T GetPlugin<T>(string name) where T : class { return _ignite.GetPlugin<T>(name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { return _ignite.GetAtomicSequence(name, initialValue, create); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { return _ignite.GetAtomicReference(name, initialValue, create); } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { // No-op. } /// <summary> /// Target grid. /// </summary> internal Ignite Target { get { return _ignite; } } } }
//--------------------------------------------------------------------------- // // <copyright file="Rotation3DAnimationUsingKeyFrames.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; namespace System.Windows.Media.Animation { /// <summary> /// This class is used to animate a Rotation3D property value along a set /// of key frames. /// </summary> [ContentProperty("KeyFrames")] public class Rotation3DAnimationUsingKeyFrames : Rotation3DAnimationBase, IKeyFrameAnimation, IAddChild { #region Data private Rotation3DKeyFrameCollection _keyFrames; private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames; private bool _areKeyTimesValid; #endregion #region Constructors /// <Summary> /// Creates a new KeyFrameRotation3DAnimation. /// </Summary> public Rotation3DAnimationUsingKeyFrames() : base() { _areKeyTimesValid = true; } #endregion #region Freezable /// <summary> /// Creates a copy of this KeyFrameRotation3DAnimation. /// </summary> /// <returns>The copy</returns> public new Rotation3DAnimationUsingKeyFrames Clone() { return (Rotation3DAnimationUsingKeyFrames)base.Clone(); } /// <summary> /// Returns a version of this class with all its base property values /// set to the current animated values and removes the animations. /// </summary> /// <returns> /// Since this class isn't animated, this method will always just return /// this instance of the class. /// </returns> public new Rotation3DAnimationUsingKeyFrames CloneCurrentValue() { return (Rotation3DAnimationUsingKeyFrames)base.CloneCurrentValue(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); canFreeze &= Freezable.Freeze(_keyFrames, isChecking); if (canFreeze & !_areKeyTimesValid) { ResolveKeyTimes(); } return canFreeze; } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. /// </summary> protected override void OnChanged() { _areKeyTimesValid = false; base.OnChanged(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new Rotation3DAnimationUsingKeyFrames(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { Rotation3DAnimationUsingKeyFrames sourceAnimation = (Rotation3DAnimationUsingKeyFrames) sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { Rotation3DAnimationUsingKeyFrames sourceAnimation = (Rotation3DAnimationUsingKeyFrames) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable source) { Rotation3DAnimationUsingKeyFrames sourceAnimation = (Rotation3DAnimationUsingKeyFrames) source; base.GetAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { Rotation3DAnimationUsingKeyFrames sourceAnimation = (Rotation3DAnimationUsingKeyFrames) source; base.GetCurrentValueAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Helper used by the four Freezable clone methods to copy the resolved key times and /// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core /// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here. /// </summary> /// <param name="sourceAnimation"></param> /// <param name="isCurrentValueClone"></param> private void CopyCommon(Rotation3DAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone) { _areKeyTimesValid = sourceAnimation._areKeyTimesValid; if ( _areKeyTimesValid && sourceAnimation._sortedResolvedKeyFrames != null) { // _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply _sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone(); } if (sourceAnimation._keyFrames != null) { if (isCurrentValueClone) { _keyFrames = (Rotation3DKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue(); } else { _keyFrames = (Rotation3DKeyFrameCollection)sourceAnimation._keyFrames.Clone(); } OnFreezablePropertyChanged(null, _keyFrames); } } #endregion // Freezable #region IAddChild interface /// <summary> /// Adds a child object to this KeyFrameAnimation. /// </summary> /// <param name="child"> /// The child object to add. /// </param> /// <remarks> /// A KeyFrameAnimation only accepts a KeyFrame of the proper type as /// a child. /// </remarks> void IAddChild.AddChild(object child) { WritePreamble(); if (child == null) { throw new ArgumentNullException("child"); } AddChild(child); WritePostscript(); } /// <summary> /// Implemented to allow KeyFrames to be direct children /// of KeyFrameAnimations in markup. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddChild(object child) { Rotation3DKeyFrame keyFrame = child as Rotation3DKeyFrame; if (keyFrame != null) { KeyFrames.Add(keyFrame); } else { throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child"); } } /// <summary> /// Adds a text string as a child of this KeyFrameAnimation. /// </summary> /// <param name="childText"> /// The text to add. /// </param> /// <remarks> /// A KeyFrameAnimation does not accept text as a child, so this method will /// raise an InvalididOperationException unless a derived class has /// overridden the behavior to add text. /// </remarks> /// <exception cref="ArgumentNullException">The childText parameter is /// null.</exception> void IAddChild.AddText(string childText) { if (childText == null) { throw new ArgumentNullException("childText"); } AddText(childText); } /// <summary> /// This method performs the core functionality of the AddText() /// method on the IAddChild interface. For a KeyFrameAnimation this means /// throwing and InvalidOperationException because it doesn't /// support adding text. /// </summary> /// <remarks> /// This method is the only core implementation. It does not call /// WritePreamble() or WritePostscript(). It also doesn't throw an /// ArgumentNullException if the childText parameter is null. These tasks /// are performed by the interface implementation. Therefore, it's OK /// for a derived class to override this method and call the base /// class implementation only if they determine that it's the right /// course of action. The derived class can rely on KeyFrameAnimation's /// implementation of IAddChild.AddChild or implement their own /// following the Freezable pattern since that would be a public /// method. /// </remarks> /// <param name="childText">A string representing the child text that /// should be added. If this is a KeyFrameAnimation an exception will be /// thrown.</param> /// <exception cref="InvalidOperationException">Timelines have no way /// of adding text.</exception> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddText(string childText) { throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren)); } #endregion #region Rotation3DAnimationBase /// <summary> /// Calculates the value this animation believes should be the current value for the property. /// </summary> /// <param name="defaultOriginValue"> /// This value is the suggested origin value provided to the animation /// to be used if the animation does not have its own concept of a /// start value. If this animation is the first in a composition chain /// this value will be the snapshot value if one is available or the /// base property value if it is not; otherise this value will be the /// value returned by the previous animation in the chain with an /// animationClock that is not Stopped. /// </param> /// <param name="defaultDestinationValue"> /// This value is the suggested destination value provided to the animation /// to be used if the animation does not have its own concept of an /// end value. This value will be the base value if the animation is /// in the first composition layer of animations on a property; /// otherwise this value will be the output value from the previous /// composition layer of animations for the property. /// </param> /// <param name="animationClock"> /// This is the animationClock which can generate the CurrentTime or /// CurrentProgress value to be used by the animation to generate its /// output value. /// </param> /// <returns> /// The value this animation believes should be the current value for the property. /// </returns> protected sealed override Rotation3D GetCurrentValueCore( Rotation3D defaultOriginValue, Rotation3D defaultDestinationValue, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); if (_keyFrames == null) { return defaultDestinationValue; } // We resolved our KeyTimes when we froze, but also got notified // of the frozen state and therefore invalidated ourselves. if (!_areKeyTimesValid) { ResolveKeyTimes(); } if (_sortedResolvedKeyFrames == null) { return defaultDestinationValue; } TimeSpan currentTime = animationClock.CurrentTime.Value; Int32 keyFrameCount = _sortedResolvedKeyFrames.Length; Int32 maxKeyFrameIndex = keyFrameCount - 1; Rotation3D currentIterationValue; Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames."); Int32 currentResolvedKeyFrameIndex = 0; // Skip all the key frames with key times lower than the current time. // currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex // if we are past the last key frame. while ( currentResolvedKeyFrameIndex < keyFrameCount && currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } // If there are multiple key frames at the same key time, be sure to go to the last one. while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex && currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } if (currentResolvedKeyFrameIndex == keyFrameCount) { // Past the last key frame. currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex); } else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { // Exactly on a key frame. currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex); } else { // Between two key frames. Double currentSegmentProgress = 0.0; Rotation3D fromValue; if (currentResolvedKeyFrameIndex == 0) { // The current key frame is the first key frame so we have // some special rules for determining the fromValue and an // optimized method of calculating the currentSegmentProgress. // If we're additive we want the base value to be a zero value // so that if there isn't a key frame at time 0.0, we'll use // the zero value for the time 0.0 value and then add that // later to the base value. if (IsAdditive) { fromValue = AnimatedTypeHelpers.GetZeroValueRotation3D(defaultOriginValue); } else { fromValue = defaultOriginValue; } // Current segment time divided by the segment duration. // Note: the reason this works is that we know that we're in // the first segment, so we can assume: // // currentTime.TotalMilliseconds = current segment time // _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration currentSegmentProgress = currentTime.TotalMilliseconds / _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds; } else { Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1; TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime; fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex); TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime; TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime; currentSegmentProgress = segmentCurrentTime.TotalMilliseconds / segmentDuration.TotalMilliseconds; } currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress); } // If we're cumulative, we need to multiply the final key frame // value by the current repeat count and add this to the return // value. if (IsCumulative) { Double currentRepeat = (Double)(animationClock.CurrentIteration - 1); if (currentRepeat > 0.0) { currentIterationValue = AnimatedTypeHelpers.AddRotation3D( currentIterationValue, AnimatedTypeHelpers.ScaleRotation3D(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat)); } } // If we're additive we need to add the base value to the return value. if (IsAdditive) { return AnimatedTypeHelpers.AddRotation3D(defaultOriginValue, currentIterationValue); } return currentIterationValue; } /// <summary> /// Provide a custom natural Duration when the Duration property is set to Automatic. /// </summary> /// <param name="clock"> /// The Clock whose natural duration is desired. /// </param> /// <returns> /// If the last KeyFrame of this animation is a KeyTime, then this will /// be used as the NaturalDuration; otherwise it will be one second. /// </returns> protected override sealed Duration GetNaturalDurationCore(Clock clock) { return new Duration(LargestTimeSpanKeyTime); } #endregion #region IKeyFrameAnimation /// <summary> /// Returns the Rotation3DKeyFrameCollection used by this KeyFrameRotation3DAnimation. /// </summary> IList IKeyFrameAnimation.KeyFrames { get { return KeyFrames; } set { KeyFrames = (Rotation3DKeyFrameCollection)value; } } /// <summary> /// Returns the Rotation3DKeyFrameCollection used by this KeyFrameRotation3DAnimation. /// </summary> public Rotation3DKeyFrameCollection KeyFrames { get { ReadPreamble(); // The reason we don't just set _keyFrames to the empty collection // in the first place is that null tells us that the user has not // asked for the collection yet. The first time they ask for the // collection and we're unfrozen, policy dictates that we give // them a new unfrozen collection. All subsequent times they will // get whatever collection is present, whether frozen or unfrozen. if (_keyFrames == null) { if (this.IsFrozen) { _keyFrames = Rotation3DKeyFrameCollection.Empty; } else { WritePreamble(); _keyFrames = new Rotation3DKeyFrameCollection(); OnFreezablePropertyChanged(null, _keyFrames); WritePostscript(); } } return _keyFrames; } set { if (value == null) { throw new ArgumentNullException("value"); } WritePreamble(); if (value != _keyFrames) { OnFreezablePropertyChanged(_keyFrames, value); _keyFrames = value; WritePostscript(); } } } /// <summary> /// Returns true if we should serialize the KeyFrames, property for this Animation. /// </summary> /// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeKeyFrames() { ReadPreamble(); return _keyFrames != null && _keyFrames.Count > 0; } #endregion #region Public Properties /// <summary> /// If this property is set to true, this animation will add its value /// to the base value or the value of the previous animation in the /// composition chain. Another way of saying this is that the units /// specified in the animation are relative to the base value rather /// than absolute units. /// </summary> /// <remarks> /// In the case where the first key frame's resolved key time is not /// 0.0 there is slightly different behavior between KeyFrameRotation3DAnimations /// with IsAdditive set and without. Animations with the property set to false /// will behave as if there is a key frame at time 0.0 with the value of the /// base value. Animations with the property set to true will behave as if /// there is a key frame at time 0.0 with a zero value appropriate to the type /// of the animation. These behaviors provide the results most commonly expected /// and can be overridden by simply adding a key frame at time 0.0 with the preferred value. /// </remarks> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value)); } } /// <summary> /// If this property is set to true, the value of this animation will /// accumulate over repeat cycles. For example, if this is a point /// animation and your key frames describe something approximating and /// arc, setting this property to true will result in an animation that /// would appear to bounce the point across the screen. /// </summary> /// <remarks> /// This property works along with the IsAdditive property. Setting /// this value to true has no effect unless IsAdditive is also set /// to true. /// </remarks> public bool IsCumulative { get { return (bool)GetValue(IsCumulativeProperty); } set { SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value)); } } #endregion #region Private Methods private struct KeyTimeBlock { public int BeginIndex; public int EndIndex; } private Rotation3D GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue"); return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value; } private Rotation3DKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame"); return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex]; } /// <summary> /// Returns the largest time span specified key time from all of the key frames. /// If there are not time span key times a time span of one second is returned /// to match the default natural duration of the From/To/By animations. /// </summary> private TimeSpan LargestTimeSpanKeyTime { get { bool hasTimeSpanKeyTime = false; TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero; if (_keyFrames != null) { Int32 keyFrameCount = _keyFrames.Count; for (int index = 0; index < keyFrameCount; index++) { KeyTime keyTime = _keyFrames[index].KeyTime; if (keyTime.Type == KeyTimeType.TimeSpan) { hasTimeSpanKeyTime = true; if (keyTime.TimeSpan > largestTimeSpanKeyTime) { largestTimeSpanKeyTime = keyTime.TimeSpan; } } } } if (hasTimeSpanKeyTime) { return largestTimeSpanKeyTime; } else { return TimeSpan.FromSeconds(1.0); } } } private void ResolveKeyTimes() { Debug.Assert(!_areKeyTimesValid, "KeyFrameRotation3DAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid."); int keyFrameCount = 0; if (_keyFrames != null) { keyFrameCount = _keyFrames.Count; } if (keyFrameCount == 0) { _sortedResolvedKeyFrames = null; _areKeyTimesValid = true; return; } _sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount]; int index = 0; // Initialize the _originalKeyFrameIndex. for ( ; index < keyFrameCount; index++) { _sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index; } // calculationDuration represents the time span we will use to resolve // percent key times. This is defined as the value in the following // precedence order: // 1. The animation's duration, but only if it is a time span, not auto or forever. // 2. The largest time span specified key time of all the key frames. // 3. 1 second, to match the From/To/By animations. TimeSpan calculationDuration = TimeSpan.Zero; Duration duration = Duration; if (duration.HasTimeSpan) { calculationDuration = duration.TimeSpan; } else { calculationDuration = LargestTimeSpanKeyTime; } int maxKeyFrameIndex = keyFrameCount - 1; ArrayList unspecifiedBlocks = new ArrayList(); bool hasPacedKeyTimes = false; // // Pass 1: Resolve Percent and Time key times. // index = 0; while (index < keyFrameCount) { KeyTime keyTime = _keyFrames[index].KeyTime; switch (keyTime.Type) { case KeyTimeType.Percent: _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds( keyTime.Percent * calculationDuration.TotalMilliseconds); index++; break; case KeyTimeType.TimeSpan: _sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan; index++; break; case KeyTimeType.Paced: case KeyTimeType.Uniform: if (index == maxKeyFrameIndex) { // If the last key frame doesn't have a specific time // associated with it its resolved key time will be // set to the calculationDuration, which is the // defined in the comments above where it is set. // Reason: We only want extra time at the end of the // key frames if the user specifically states that // the last key frame ends before the animation ends. _sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration; index++; } else if ( index == 0 && keyTime.Type == KeyTimeType.Paced) { // Note: It's important that this block come after // the previous if block because of rule precendence. // If the first key frame in a multi-frame key frame // collection is paced, we set its resolved key time // to 0.0 for performance reasons. If we didn't, the // resolved key time list would be dependent on the // base value which can change every animation frame // in many cases. _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero; index++; } else { if (keyTime.Type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } KeyTimeBlock block = new KeyTimeBlock(); block.BeginIndex = index; // NOTE: We don't want to go all the way up to the // last frame because if it is Uniform or Paced its // resolved key time will be set to the calculation // duration using the logic above. // // This is why the logic is: // ((++index) < maxKeyFrameIndex) // instead of: // ((++index) < keyFrameCount) while ((++index) < maxKeyFrameIndex) { KeyTimeType type = _keyFrames[index].KeyTime.Type; if ( type == KeyTimeType.Percent || type == KeyTimeType.TimeSpan) { break; } else if (type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } } Debug.Assert(index < keyFrameCount, "The end index for a block of unspecified key frames is out of bounds."); block.EndIndex = index; unspecifiedBlocks.Add(block); } break; } } // // Pass 2: Resolve Uniform key times. // for (int j = 0; j < unspecifiedBlocks.Count; j++) { KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j]; TimeSpan blockBeginTime = TimeSpan.Zero; if (block.BeginIndex > 0) { blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime; } // The number of segments is equal to the number of key // frames we're working on plus 1. Think about the case // where we're working on a single key frame. There's a // segment before it and a segment after it. // // Time known Uniform Time known // ^ ^ ^ // | | | // | (segment 1) | (segment 2) | Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1; TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount); index = block.BeginIndex; TimeSpan resolvedTime = blockBeginTime + uniformTimeStep; while (index < block.EndIndex) { _sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime; resolvedTime += uniformTimeStep; index++; } } // // Pass 3: Resolve Paced key times. // if (hasPacedKeyTimes) { ResolvePacedKeyTimes(); } // // Sort resolved key frame entries. // Array.Sort(_sortedResolvedKeyFrames); _areKeyTimesValid = true; return; } /// <summary> /// This should only be called from ResolveKeyTimes and only at the /// appropriate time. /// </summary> private void ResolvePacedKeyTimes() { Debug.Assert(_keyFrames != null && _keyFrames.Count > 2, "Caller must guard against calling this method when there are insufficient keyframes."); // If the first key frame is paced its key time has already // been resolved, so we start at index 1. int index = 1; int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1; do { if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced) { // // We've found a paced key frame so this is the // beginning of a paced block. // // The first paced key frame in this block. int firstPacedBlockKeyFrameIndex = index; // List of segment lengths for this paced block. List<Double> segmentLengths = new List<Double>(); // The resolved key time for the key frame before this // block which we'll use as our starting point. TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime; // The total of the segment lengths of the paced key // frames in this block. Double totalLength = 0.0; // The key value of the previous key frame which will be // used to determine the segment length of this key frame. Rotation3D prevKeyValue = _keyFrames[index - 1].Value; do { Rotation3D currentKeyValue = _keyFrames[index].Value; // Determine the segment length for this key frame and // add to the total length. totalLength += AnimatedTypeHelpers.GetSegmentLengthRotation3D(prevKeyValue, currentKeyValue); // Temporarily store the distance into the total length // that this key frame represents in the resolved // key times array to be converted to a resolved key // time outside of this loop. segmentLengths.Add(totalLength); // Prepare for the next iteration. prevKeyValue = currentKeyValue; index++; } while ( index < maxKeyFrameIndex && _keyFrames[index].KeyTime.Type == KeyTimeType.Paced); // index is currently set to the index of the key frame // after the last paced key frame. This will always // be a valid index because we limit ourselves with // maxKeyFrameIndex. // We need to add the distance between the last paced key // frame and the next key frame to get the total distance // inside the key frame block. totalLength += AnimatedTypeHelpers.GetSegmentLengthRotation3D(prevKeyValue, _keyFrames[index].Value); // Calculate the time available in the resolved key time space. TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime; // Convert lengths in segmentLengths list to resolved // key times for the paced key frames in this block. for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++) { // The resolved key time for each key frame is: // // The key time of the key frame before this paced block // + ((the percentage of the way through the total length) // * the resolved key time space available for the block) _sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds( (segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds); } } else { index++; } } while (index < maxKeyFrameIndex); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Web; using Umbraco.Core.Logging; using Umbraco.Core.Profiling; namespace Umbraco.Core { /// <summary> /// Starts the timer and invokes a callback upon disposal. Provides a simple way of timing an operation by wrapping it in a <code>using</code> (C#) statement. /// </summary> public class DisposableTimer : DisposableObject { private readonly ILogger _logger; private readonly LogType? _logType; private readonly IProfiler _profiler; private readonly Type _loggerType; private readonly string _endMessage; private readonly IDisposable _profilerStep; private readonly Stopwatch _stopwatch = Stopwatch.StartNew(); private readonly Action<long> _callback; internal enum LogType { Debug, Info } internal DisposableTimer(ILogger logger, LogType logType, IProfiler profiler, Type loggerType, string startMessage, string endMessage) { if (logger == null) throw new ArgumentNullException("logger"); if (loggerType == null) throw new ArgumentNullException("loggerType"); _logger = logger; _logType = logType; _profiler = profiler; _loggerType = loggerType; _endMessage = endMessage; switch (logType) { case LogType.Debug: logger.Debug(loggerType, startMessage); break; case LogType.Info: logger.Info(loggerType, startMessage); break; default: throw new ArgumentOutOfRangeException("logType"); } if (profiler != null) { _profilerStep = profiler.Step(loggerType, startMessage); } } protected internal DisposableTimer(Action<long> callback) { if (callback == null) throw new ArgumentNullException("callback"); _callback = callback; } public Stopwatch Stopwatch { get { return _stopwatch; } } /// <summary> /// Starts the timer and invokes the specified callback upon disposal. /// </summary> /// <param name="callback">The callback.</param> /// <returns></returns> [Obsolete("Use either TraceDuration or DebugDuration instead of using Start")] public static DisposableTimer Start(Action<long> callback) { return new DisposableTimer(callback); } #region TraceDuration [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer TraceDuration<T>(Func<string> startMessage, Func<string> completeMessage) { return TraceDuration(typeof(T), startMessage, completeMessage); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer TraceDuration(Type loggerType, Func<string> startMessage, Func<string> completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Info, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage(), completeMessage()); } /// <summary> /// Adds a start and end log entry as Info and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer TraceDuration<T>(string startMessage, string completeMessage) { return TraceDuration(typeof(T), startMessage, completeMessage); } /// <summary> /// Adds a start and end log entry as Info and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer TraceDuration<T>(string startMessage) { return TraceDuration(typeof(T), startMessage, "Complete"); } /// <summary> /// Adds a start and end log entry as Info and tracks how long it takes until disposed. /// </summary> /// <param name="loggerType"></param> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer TraceDuration(Type loggerType, string startMessage, string completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Info, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage, completeMessage); } #endregion #region DebugDuration /// <summary> /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer DebugDuration<T>(string startMessage, string completeMessage) { return DebugDuration(typeof(T), startMessage, completeMessage); } /// <summary> /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="startMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer DebugDuration<T>(string startMessage) { return DebugDuration(typeof(T), startMessage, "Complete"); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer DebugDuration<T>(Func<string> startMessage, Func<string> completeMessage) { return DebugDuration(typeof(T), startMessage, completeMessage); } /// <summary> /// Adds a start and end log entry as Debug and tracks how long it takes until disposed. /// </summary> /// <param name="loggerType"></param> /// <param name="startMessage"></param> /// <param name="completeMessage"></param> /// <returns></returns> [Obsolete("Use the Umbraco.Core.Logging.ProfilingLogger to create instances of DisposableTimer")] public static DisposableTimer DebugDuration(Type loggerType, string startMessage, string completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Debug, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage, completeMessage); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the other methods that specify strings instead of Func")] public static DisposableTimer DebugDuration(Type loggerType, Func<string> startMessage, Func<string> completeMessage) { return new DisposableTimer( LoggerResolver.Current.Logger, LogType.Debug, ProfilerResolver.HasCurrent ? ProfilerResolver.Current.Profiler : null, loggerType, startMessage(), completeMessage()); } #endregion /// <summary> /// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic. /// </summary> protected override void DisposeResources() { if (_profiler != null) { _profiler.DisposeIfDisposable(); } if (_profilerStep != null) { _profilerStep.Dispose(); } if (_logType.HasValue && _endMessage.IsNullOrWhiteSpace() == false && _loggerType != null && _logger != null) { switch (_logType) { case LogType.Debug: _logger.Debug(_loggerType, () => _endMessage + " (took " + Stopwatch.ElapsedMilliseconds + "ms)"); break; case LogType.Info: _logger.Info(_loggerType, () => _endMessage + " (took " + Stopwatch.ElapsedMilliseconds + "ms)"); break; default: throw new ArgumentOutOfRangeException("logType"); } } if (_callback != null) { _callback.Invoke(Stopwatch.ElapsedMilliseconds); } } } }
// 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. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.IO; using System.Xml; using System.Data.Common; using System.Diagnostics; using System.Text; namespace System.Data.SqlTypes { public sealed class SqlXml : System.Data.SqlTypes.INullable { private bool _fNotNull; // false if null, the default ctor (plain 0) will make it Null private Stream _stream; private bool _firstCreateReader; private readonly static XmlReaderSettings s_defaultXmlReaderSettings = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }; private readonly static XmlReaderSettings s_defaultXmlReaderSettingsCloseInput = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true }; private readonly static XmlReaderSettings s_defaultXmlReaderSettingsAsyncCloseInput = new XmlReaderSettings() { Async = true, ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true }; public SqlXml() { SetNull(); } // constructor // construct a Null private SqlXml(bool fNull) { SetNull(); } public SqlXml(XmlReader value) { // whoever pass in the XmlReader is responsible for closing it if (value == null) { SetNull(); } else { _fNotNull = true; _firstCreateReader = true; _stream = CreateMemoryStreamFromXmlReader(value); } } public SqlXml(Stream value) { // whoever pass in the stream is responsible for closing it // similar to SqlBytes implementation if (value == null) { SetNull(); } else { _firstCreateReader = true; _fNotNull = true; _stream = value; } } public XmlReader CreateReader() { if (IsNull) { throw new SqlNullValueException(); } SqlXmlStreamWrapper stream = new SqlXmlStreamWrapper(_stream); // if it is the first time we create reader and stream does not support CanSeek, no need to reset position if ((!_firstCreateReader || stream.CanSeek) && stream.Position != 0) { stream.Seek(0, SeekOrigin.Begin); } XmlReader r = CreateSqlXmlReader(stream); _firstCreateReader = false; return r; } internal static XmlReader CreateSqlXmlReader(Stream stream, bool closeInput = false, bool async = false) { XmlReaderSettings settingsToUse; if (closeInput) { settingsToUse = async ? s_defaultXmlReaderSettingsAsyncCloseInput : s_defaultXmlReaderSettingsCloseInput; } else { Debug.Assert(!async, "Currently we do not have pre-created settings for !closeInput+async"); settingsToUse = s_defaultXmlReaderSettings; } return XmlReader.Create(stream, settingsToUse); } // NOTE: ReflectionPermission required here for accessing the non-public internal method CreateSqlReader() of System.Xml regardless of its grant set. // INullable public bool IsNull { get { return !_fNotNull; } } public string Value { get { if (IsNull) throw new SqlNullValueException(); StringWriter sw = new StringWriter((System.IFormatProvider)null); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; XmlWriter ww = XmlWriter.Create(sw, writerSettings); XmlReader reader = this.CreateReader(); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { ww.WriteNode(reader, true); } ww.Flush(); return sw.ToString(); } } public static SqlXml Null { get { return new SqlXml(true); } } private void SetNull() { _fNotNull = false; _stream = null; _firstCreateReader = true; } private Stream CreateMemoryStreamFromXmlReader(XmlReader reader) { XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream writerSettings.ConformanceLevel = ConformanceLevel.Fragment; writerSettings.Encoding = Encoding.GetEncoding("utf-16"); writerSettings.OmitXmlDeclaration = true; MemoryStream writerStream = new MemoryStream(); XmlWriter ww = XmlWriter.Create(writerStream, writerSettings); if (reader.ReadState == ReadState.Closed) throw new InvalidOperationException(SQLResource.ClosedXmlReaderMessage); if (reader.ReadState == ReadState.Initial) reader.Read(); while (!reader.EOF) { ww.WriteNode(reader, true); } ww.Flush(); // set the stream to the beginning writerStream.Seek(0, SeekOrigin.Begin); return writerStream; } } // SqlXml // two purposes for this class // 1) keep its internal position so one reader positions on the orginial stream // will not interface with the other // 2) when xmlreader calls close, do not close the orginial stream // internal sealed class SqlXmlStreamWrapper : Stream { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private Stream _stream; private long _lPosition; private bool _isClosed; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal SqlXmlStreamWrapper(Stream stream) { _stream = stream; Debug.Assert(_stream != null, "stream can not be null"); _lPosition = 0; _isClosed = false; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // Always can read/write/seek, unless stream is null, // which means the stream has been closed. public override bool CanRead { get { if (IsStreamClosed()) return false; return _stream.CanRead; } } public override bool CanSeek { get { if (IsStreamClosed()) return false; return _stream.CanSeek; } } public override bool CanWrite { get { if (IsStreamClosed()) return false; return _stream.CanWrite; } } public override long Length { get { ThrowIfStreamClosed("get_Length"); ThrowIfStreamCannotSeek("get_Length"); return _stream.Length; } } public override long Position { get { ThrowIfStreamClosed("get_Position"); ThrowIfStreamCannotSeek("get_Position"); return _lPosition; } set { ThrowIfStreamClosed("set_Position"); ThrowIfStreamCannotSeek("set_Position"); if (value < 0 || value > _stream.Length) throw new ArgumentOutOfRangeException("value"); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { long lPosition = 0; ThrowIfStreamClosed("Seek"); ThrowIfStreamCannotSeek("Seek"); switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _stream.Length) throw new ArgumentOutOfRangeException("offset"); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _stream.Length) throw new ArgumentOutOfRangeException("offset"); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _stream.Length + offset; if (lPosition < 0 || lPosition > _stream.Length) throw new ArgumentOutOfRangeException("offset"); _lPosition = lPosition; break; default: throw ADP.InvalidSeekOrigin("offset"); } return _lPosition; } public override int Read(byte[] buffer, int offset, int count) { ThrowIfStreamClosed("Read"); ThrowIfStreamCannotRead("Read"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); int iBytesRead = (int)_stream.Read(buffer, offset, count); _lPosition += iBytesRead; return iBytesRead; } public override void Write(byte[] buffer, int offset, int count) { ThrowIfStreamClosed("Write"); ThrowIfStreamCannotWrite("Write"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); _stream.Write(buffer, offset, count); _lPosition += count; } public override int ReadByte() { ThrowIfStreamClosed("ReadByte"); ThrowIfStreamCannotRead("ReadByte"); // If at the end of stream, return -1, rather than call ReadByte, // which will throw exception. This is the behavior for Stream. // if (_stream.CanSeek && _lPosition >= _stream.Length) return -1; if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); int ret = _stream.ReadByte(); _lPosition++; return ret; } public override void WriteByte(byte value) { ThrowIfStreamClosed("WriteByte"); ThrowIfStreamCannotWrite("WriteByte"); if (_stream.CanSeek && _stream.Position != _lPosition) _stream.Seek(_lPosition, SeekOrigin.Begin); _stream.WriteByte(value); _lPosition++; } public override void SetLength(long value) { ThrowIfStreamClosed("SetLength"); ThrowIfStreamCannotSeek("SetLength"); _stream.SetLength(value); if (_lPosition > value) _lPosition = value; } public override void Flush() { if (_stream != null) _stream.Flush(); } protected override void Dispose(bool disposing) { try { // does not close the underline stream but mark itself as closed _isClosed = true; } finally { base.Dispose(disposing); } } private void ThrowIfStreamCannotSeek(string method) { if (!_stream.CanSeek) throw new NotSupportedException(SQLResource.InvalidOpStreamNonSeekable(method)); } private void ThrowIfStreamCannotRead(string method) { if (!_stream.CanRead) throw new NotSupportedException(SQLResource.InvalidOpStreamNonReadable(method)); } private void ThrowIfStreamCannotWrite(string method) { if (!_stream.CanWrite) throw new NotSupportedException(SQLResource.InvalidOpStreamNonWritable(method)); } private void ThrowIfStreamClosed(string method) { if (IsStreamClosed()) throw new ObjectDisposedException(SQLResource.InvalidOpStreamClosed(method)); } private bool IsStreamClosed() { // Check the .CanRead and .CanWrite and .CanSeek properties to make sure stream is really closed if (_isClosed || _stream == null || (!_stream.CanRead && !_stream.CanWrite && !_stream.CanSeek)) return true; else return false; } } // class SqlXmlStreamWrapper }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elasticloadbalancing-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticLoadBalancing.Model { /// <summary> /// Contains the result of a successful invocation of <a>DescribeLoadBalancers</a>. /// </summary> public partial class LoadBalancerDescription { private List<string> _availabilityZones = new List<string>(); private List<BackendServerDescription> _backendServerDescriptions = new List<BackendServerDescription>(); private string _canonicalHostedZoneName; private string _canonicalHostedZoneNameID; private DateTime? _createdTime; private string _dnsName; private HealthCheck _healthCheck; private List<Instance> _instances = new List<Instance>(); private List<ListenerDescription> _listenerDescriptions = new List<ListenerDescription>(); private string _loadBalancerName; private Policies _policies; private string _scheme; private List<string> _securityGroups = new List<string>(); private SourceSecurityGroup _sourceSecurityGroup; private List<string> _subnets = new List<string>(); private string _vpcId; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public LoadBalancerDescription() { } /// <summary> /// Gets and sets the property AvailabilityZones. /// <para> /// Specifies a list of Availability Zones. /// </para> /// </summary> public List<string> AvailabilityZones { get { return this._availabilityZones; } set { this._availabilityZones = value; } } // Check to see if AvailabilityZones property is set internal bool IsSetAvailabilityZones() { return this._availabilityZones != null && this._availabilityZones.Count > 0; } /// <summary> /// Gets and sets the property BackendServerDescriptions. /// <para> /// Contains a list of back-end server descriptions. /// </para> /// </summary> public List<BackendServerDescription> BackendServerDescriptions { get { return this._backendServerDescriptions; } set { this._backendServerDescriptions = value; } } // Check to see if BackendServerDescriptions property is set internal bool IsSetBackendServerDescriptions() { return this._backendServerDescriptions != null && this._backendServerDescriptions.Count > 0; } /// <summary> /// Gets and sets the property CanonicalHostedZoneName. /// <para> /// Provides the name of the Amazon Route 53 hosted zone that is associated with the /// load balancer. For information on how to associate your load balancer with a hosted /// zone, go to <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-domain-names-with-elb.html">Using /// Domain Names With Elastic Load Balancing</a> in the <i>Elastic Load Balancing Developer /// Guide</i>. /// </para> /// </summary> public string CanonicalHostedZoneName { get { return this._canonicalHostedZoneName; } set { this._canonicalHostedZoneName = value; } } // Check to see if CanonicalHostedZoneName property is set internal bool IsSetCanonicalHostedZoneName() { return this._canonicalHostedZoneName != null; } /// <summary> /// Gets and sets the property CanonicalHostedZoneNameID. /// <para> /// Provides the ID of the Amazon Route 53 hosted zone name that is associated with the /// load balancer. For information on how to associate or disassociate your load balancer /// with a hosted zone, go to <a href="http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/using-domain-names-with-elb.html">Using /// Domain Names With Elastic Load Balancing</a> in the <i>Elastic Load Balancing Developer /// Guide</i>. /// </para> /// </summary> public string CanonicalHostedZoneNameID { get { return this._canonicalHostedZoneNameID; } set { this._canonicalHostedZoneNameID = value; } } // Check to see if CanonicalHostedZoneNameID property is set internal bool IsSetCanonicalHostedZoneNameID() { return this._canonicalHostedZoneNameID != null; } /// <summary> /// Gets and sets the property CreatedTime. /// <para> /// Provides the date and time the load balancer was created. /// </para> /// </summary> public DateTime CreatedTime { get { return this._createdTime.GetValueOrDefault(); } set { this._createdTime = value; } } // Check to see if CreatedTime property is set internal bool IsSetCreatedTime() { return this._createdTime.HasValue; } /// <summary> /// Gets and sets the property DNSName. /// <para> /// Specifies the external DNS name associated with the load balancer. /// </para> /// </summary> public string DNSName { get { return this._dnsName; } set { this._dnsName = value; } } // Check to see if DNSName property is set internal bool IsSetDNSName() { return this._dnsName != null; } /// <summary> /// Gets and sets the property HealthCheck. /// <para> /// Specifies information regarding the various health probes conducted on the load balancer. /// /// </para> /// </summary> public HealthCheck HealthCheck { get { return this._healthCheck; } set { this._healthCheck = value; } } // Check to see if HealthCheck property is set internal bool IsSetHealthCheck() { return this._healthCheck != null; } /// <summary> /// Gets and sets the property Instances. /// <para> /// Provides a list of EC2 instance IDs for the load balancer. /// </para> /// </summary> public List<Instance> Instances { get { return this._instances; } set { this._instances = value; } } // Check to see if Instances property is set internal bool IsSetInstances() { return this._instances != null && this._instances.Count > 0; } /// <summary> /// Gets and sets the property ListenerDescriptions. /// <para> /// LoadBalancerPort, InstancePort, Protocol, InstanceProtocol, and PolicyNames are returned /// in a list of tuples in the ListenerDescriptions element. /// </para> /// </summary> public List<ListenerDescription> ListenerDescriptions { get { return this._listenerDescriptions; } set { this._listenerDescriptions = value; } } // Check to see if ListenerDescriptions property is set internal bool IsSetListenerDescriptions() { return this._listenerDescriptions != null && this._listenerDescriptions.Count > 0; } /// <summary> /// Gets and sets the property LoadBalancerName. /// <para> /// Specifies the name associated with the load balancer. /// </para> /// </summary> public string LoadBalancerName { get { return this._loadBalancerName; } set { this._loadBalancerName = value; } } // Check to see if LoadBalancerName property is set internal bool IsSetLoadBalancerName() { return this._loadBalancerName != null; } /// <summary> /// Gets and sets the property Policies. /// <para> /// Provides a list of policies defined for the load balancer. /// </para> /// </summary> public Policies Policies { get { return this._policies; } set { this._policies = value; } } // Check to see if Policies property is set internal bool IsSetPolicies() { return this._policies != null; } /// <summary> /// Gets and sets the property Scheme. /// <para> /// Specifies the type of load balancer. /// </para> /// /// <para> /// If the <code>Scheme</code> is <code>internet-facing</code>, the load balancer has /// a publicly resolvable DNS name that resolves to public IP addresses. /// </para> /// /// <para> /// If the <code>Scheme</code> is <code>internal</code>, the load balancer has a publicly /// resolvable DNS name that resolves to private IP addresses. /// </para> /// /// <para> /// This option is only available for load balancers attached to an Amazon VPC. /// </para> /// </summary> public string Scheme { get { return this._scheme; } set { this._scheme = value; } } // Check to see if Scheme property is set internal bool IsSetScheme() { return this._scheme != null; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// The security groups the load balancer is a member of (VPC only). /// </para> /// </summary> public List<string> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property SourceSecurityGroup. /// <para> /// The security group that you can use as part of your inbound rules for your load balancer's /// back-end Amazon EC2 application instances. To only allow traffic from load balancers, /// add a security group rule to your back end instance that specifies this source security /// group as the inbound source. /// </para> /// </summary> public SourceSecurityGroup SourceSecurityGroup { get { return this._sourceSecurityGroup; } set { this._sourceSecurityGroup = value; } } // Check to see if SourceSecurityGroup property is set internal bool IsSetSourceSecurityGroup() { return this._sourceSecurityGroup != null; } /// <summary> /// Gets and sets the property Subnets. /// <para> /// Provides a list of VPC subnet IDs for the load balancer. /// </para> /// </summary> public List<string> Subnets { get { return this._subnets; } set { this._subnets = value; } } // Check to see if Subnets property is set internal bool IsSetSubnets() { return this._subnets != null && this._subnets.Count > 0; } /// <summary> /// Gets and sets the property VPCId. /// <para> /// Provides the ID of the VPC attached to the load balancer. /// </para> /// </summary> public string VPCId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VPCId property is set internal bool IsSetVPCId() { return this._vpcId != null; } } }
//----------------------------------------------------------------------- // <copyright file="DemoInputManager.cs" company="Google Inc."> // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- #if UNITY_ANDROID && !UNITY_EDITOR #define RUNNING_ON_ANDROID_DEVICE #endif // UNITY_ANDROID && !UNITY_EDITOR namespace GoogleVR.Demos { using UnityEngine; using UnityEngine.UI; using System; #if UNITY_2017_2_OR_NEWER using UnityEngine.XR; #else using XRSettings = UnityEngine.VR.VRSettings; #endif // UNITY_2017_2_OR_NEWER public class DemoInputManager : MonoBehaviour { private const string MESSAGE_CANVAS_NAME = "MessageCanvas"; private const string MESSAGE_TEXT_NAME = "MessageText"; private const string LASER_GAMEOBJECT_NAME = "Laser"; private const string CONTROLLER_CONNECTING_MESSAGE = "Daydream controller connecting..."; private const string CONTROLLER_DISCONNECTED_MESSAGE = "Daydream controller not connected"; private const string CONTROLLER_SCANNING_MESSAGE = "Scanning for Daydream controller..."; private const string NON_GVR_PLATFORM = "Please select a supported Google VR platform via 'Build Settings > Android | iOS > Switch Platform'\n"; private const string VR_SUPPORT_NOT_CHECKED = "Please make sure 'Player Settings > Virtual Reality Supported' is checked\n"; private const string EMPTY_VR_SDK_WARNING_MESSAGE = "Please add 'Daydream' or 'Cardboard' under 'Player Settings > Virtual Reality SDKs'\n"; // Java class, method, and field constants. private const int ANDROID_MIN_DAYDREAM_API = 24; private const string FIELD_SDK_INT = "SDK_INT"; private const string PACKAGE_BUILD_VERSION = "android.os.Build$VERSION"; private const string PACKAGE_DAYDREAM_API_CLASS = "com.google.vr.ndk.base.DaydreamApi"; private const string METHOD_IS_DAYDREAM_READY = "isDaydreamReadyPlatform"; private bool isDaydream = false; private int activeControllerPointer = 0; private static readonly GvrControllerHand[] AllHands = { GvrControllerHand.Right, GvrControllerHand.Left, }; // Buttons that can trigger pointer switching. private const GvrControllerButton pointerButtonMask = GvrControllerButton.App | GvrControllerButton.TouchPadButton | GvrControllerButton.Trigger | GvrControllerButton.Grip; [Tooltip("Reference to GvrControllerMain")] public GameObject controllerMain; public static string CONTROLLER_MAIN_PROP_NAME = "controllerMain"; [Tooltip("Reference to GvrControllerPointers")] public GameObject[] controllerPointers; public static string CONTROLLER_POINTER_PROP_NAME = "controllerPointers"; [Tooltip("Reference to GvrReticlePointer")] public GameObject reticlePointer; public static string RETICLE_POINTER_PROP_NAME = "reticlePointer"; public GameObject messageCanvas; public Text messageText; #if !RUNNING_ON_ANDROID_DEVICE public enum EmulatedPlatformType { Daydream, Cardboard } [Tooltip("Emulated GVR Platform")] public EmulatedPlatformType gvrEmulatedPlatformType = EmulatedPlatformType.Daydream; public static string EMULATED_PLATFORM_PROP_NAME = "gvrEmulatedPlatformType"; #else // Running on an Android device. private GvrSettings.ViewerPlatformType viewerPlatform; #endif // !RUNNING_ON_ANDROID_DEVICE void Start() { if (messageCanvas == null) { messageCanvas = transform.Find(MESSAGE_CANVAS_NAME).gameObject; if (messageCanvas != null) { messageText = messageCanvas.transform.Find(MESSAGE_TEXT_NAME).GetComponent<Text>(); } } // Message canvas will be enabled later when there's a message to display. messageCanvas.SetActive(false); #if !RUNNING_ON_ANDROID_DEVICE if (playerSettingsHasDaydream() || playerSettingsHasCardboard()) { // The list is populated with valid VR SDK(s), pick the first one. gvrEmulatedPlatformType = (XRSettings.supportedDevices[0] == GvrSettings.VR_SDK_DAYDREAM) ? EmulatedPlatformType.Daydream : EmulatedPlatformType.Cardboard; } isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream); #else // Running on an Android device. viewerPlatform = GvrSettings.ViewerPlatform; // First loaded device in Player Settings. string vrDeviceName = XRSettings.loadedDeviceName; if (vrDeviceName != GvrSettings.VR_SDK_CARDBOARD && vrDeviceName != GvrSettings.VR_SDK_DAYDREAM) { Debug.LogErrorFormat("Loaded device was '{0}', must be one of '{1}' or '{2}'", vrDeviceName, GvrSettings.VR_SDK_DAYDREAM, GvrSettings.VR_SDK_CARDBOARD); return; } // On a non-Daydream ready phone, fall back to Cardboard if it's present in the list of // enabled VR SDKs. // On a Daydream-ready phone, go into Cardboard mode if it's the currently-paired viewer. if ((!IsDeviceDaydreamReady() && playerSettingsHasCardboard()) || (IsDeviceDaydreamReady() && playerSettingsHasCardboard() && GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Cardboard)) { vrDeviceName = GvrSettings.VR_SDK_CARDBOARD; } isDaydream = (vrDeviceName == GvrSettings.VR_SDK_DAYDREAM); #endif // !RUNNING_ON_ANDROID_DEVICE SetVRInputMechanism(); } // Runtime switching enabled only in-editor. void Update() { UpdateStatusMessage(); // Scan all devices' buttons for button down, and switch the singleton pointer // to the controller the user last clicked. int newPointer = activeControllerPointer; if (controllerPointers.Length > 1 && controllerPointers[1] != null) { GvrTrackedController trackedController1 = controllerPointers[1].GetComponent<GvrTrackedController>(); foreach (var hand in AllHands) { GvrControllerInputDevice device = GvrControllerInput.GetDevice(hand); if (device.GetButtonDown(pointerButtonMask)) { // Match the button to our own controllerPointers list. if (device == trackedController1.ControllerInputDevice) { newPointer = 1; } else { newPointer = 0; } break; } } } if (newPointer != activeControllerPointer) { activeControllerPointer = newPointer; SetVRInputMechanism(); } #if !RUNNING_ON_ANDROID_DEVICE UpdateEmulatedPlatformIfPlayerSettingsChanged(); if ((isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Daydream) || (!isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard)) { return; } isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream); SetVRInputMechanism(); #else // Running on an Android device. // Viewer type switched at runtime. if (!IsDeviceDaydreamReady() || viewerPlatform == GvrSettings.ViewerPlatform) { return; } isDaydream = (GvrSettings.ViewerPlatform == GvrSettings.ViewerPlatformType.Daydream); viewerPlatform = GvrSettings.ViewerPlatform; SetVRInputMechanism(); #endif // !RUNNING_ON_ANDROID_DEVICE } public bool IsCurrentlyDaydream() { return isDaydream; } public static bool playerSettingsHasDaydream() { string[] playerSettingsVrSdks = XRSettings.supportedDevices; return Array.Exists<string>(playerSettingsVrSdks, element => element.Equals(GvrSettings.VR_SDK_DAYDREAM)); } public static bool playerSettingsHasCardboard() { string[] playerSettingsVrSdks = XRSettings.supportedDevices; return Array.Exists<string>(playerSettingsVrSdks, element => element.Equals(GvrSettings.VR_SDK_CARDBOARD)); } #if !RUNNING_ON_ANDROID_DEVICE private void UpdateEmulatedPlatformIfPlayerSettingsChanged() { if (!playerSettingsHasDaydream() && !playerSettingsHasCardboard()) { return; } // Player Settings > VR SDK list may have changed at runtime. The emulated platform // may not have been manually updated if that's the case. if (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream && !playerSettingsHasDaydream()) { gvrEmulatedPlatformType = EmulatedPlatformType.Cardboard; } else if (gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard && !playerSettingsHasCardboard()) { gvrEmulatedPlatformType = EmulatedPlatformType.Daydream; } } #endif // !RUNNING_ON_ANDROID_DEVICE #if RUNNING_ON_ANDROID_DEVICE // Running on an Android device. private static bool IsDeviceDaydreamReady() { // Check API level. using (var version = new AndroidJavaClass(PACKAGE_BUILD_VERSION)) { if (version.GetStatic<int>(FIELD_SDK_INT) < ANDROID_MIN_DAYDREAM_API) { return false; } } // API level > 24, check whether the device is Daydream-ready.. AndroidJavaObject androidActivity = null; try { androidActivity = GvrActivityHelper.GetActivity(); } catch (AndroidJavaException e) { Debug.LogError("Exception while connecting to the Activity: " + e); return false; } AndroidJavaClass daydreamApiClass = new AndroidJavaClass(PACKAGE_DAYDREAM_API_CLASS); if (daydreamApiClass == null || androidActivity == null) { return false; } return daydreamApiClass.CallStatic<bool>(METHOD_IS_DAYDREAM_READY, androidActivity); } #endif // RUNNING_ON_ANDROID_DEVICE private void UpdateStatusMessage() { if (messageText == null || messageCanvas == null) { return; } #if !UNITY_ANDROID && !UNITY_IOS messageText.text = NON_GVR_PLATFORM; messageCanvas.SetActive(true); return; #else #if UNITY_EDITOR if (!UnityEditor.PlayerSettings.virtualRealitySupported) { messageText.text = VR_SUPPORT_NOT_CHECKED; messageCanvas.SetActive(true); return; } #endif // UNITY_EDITOR bool isVrSdkListEmpty = !playerSettingsHasCardboard() && !playerSettingsHasDaydream(); if (!isDaydream) { if (messageCanvas.activeSelf) { messageText.text = EMPTY_VR_SDK_WARNING_MESSAGE; messageCanvas.SetActive(isVrSdkListEmpty); } return; } string vrSdkWarningMessage = isVrSdkListEmpty ? EMPTY_VR_SDK_WARNING_MESSAGE : ""; string controllerMessage = ""; GvrPointerGraphicRaycaster graphicRaycaster = messageCanvas.GetComponent<GvrPointerGraphicRaycaster>(); GvrControllerInputDevice dominantDevice = GvrControllerInput.GetDevice(GvrControllerHand.Dominant); GvrConnectionState connectionState = dominantDevice.State; // This is an example of how to process the controller's state to display a status message. switch (connectionState) { case GvrConnectionState.Connected: break; case GvrConnectionState.Disconnected: controllerMessage = CONTROLLER_DISCONNECTED_MESSAGE; messageText.color = Color.white; break; case GvrConnectionState.Scanning: controllerMessage = CONTROLLER_SCANNING_MESSAGE; messageText.color = Color.cyan; break; case GvrConnectionState.Connecting: controllerMessage = CONTROLLER_CONNECTING_MESSAGE; messageText.color = Color.yellow; break; case GvrConnectionState.Error: controllerMessage = "ERROR: " + dominantDevice.ErrorDetails; messageText.color = Color.red; break; default: // Shouldn't happen. Debug.LogError("Invalid controller state: " + connectionState); break; } messageText.text = string.Format("{0}\n{1}", vrSdkWarningMessage, controllerMessage); if (graphicRaycaster != null) { graphicRaycaster.enabled = !isVrSdkListEmpty || connectionState != GvrConnectionState.Connected; } messageCanvas.SetActive(isVrSdkListEmpty || (connectionState != GvrConnectionState.Connected)); #endif // !UNITY_ANDROID && !UNITY_IOS } private void SetVRInputMechanism() { SetGazeInputActive(!isDaydream); SetControllerInputActive(isDaydream); } private void SetGazeInputActive(bool active) { if (reticlePointer == null) { return; } reticlePointer.SetActive(active); // Update the pointer type only if this is currently activated. if (!active) { return; } GvrReticlePointer pointer = reticlePointer.GetComponent<GvrReticlePointer>(); if (pointer != null) { GvrPointerInputModule.Pointer = pointer; } } private void SetControllerInputActive(bool active) { if (controllerMain != null) { controllerMain.SetActive(active); } if (controllerPointers == null || controllerPointers.Length <= activeControllerPointer) { return; } controllerPointers[activeControllerPointer].SetActive(active); // Update the pointer type only if this is currently activated. if (!active) { return; } GvrLaserPointer pointer = controllerPointers[activeControllerPointer].GetComponentInChildren<GvrLaserPointer>(true); if (pointer != null) { GvrPointerInputModule.Pointer = pointer; } } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI81; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.LowLevelAPI81 { /// <summary> /// C_DigestInit, C_Digest, C_DigestUpdate, C_DigestFinal and C_DigestKey tests. /// </summary> [TestClass] public class _12_DigestTest { /// <summary> /// C_DigestInit and C_Digest test. /// </summary> [TestMethod] public void _01_DigestSinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1); // Initialize digesting operation rv = pkcs11.C_DigestInit(session, ref mechanism); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of digest value in first call ulong digestLen = 0; rv = pkcs11.C_Digest(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(digestLen > 0); // Allocate array for digest value byte[] digest = new byte[digestLen]; // Get digest value in second call rv = pkcs11.C_Digest(session, sourceData, Convert.ToUInt64(sourceData.Length), digest, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with digest value rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_DigestInit, C_DigestUpdate and C_DigestFinal test. /// </summary> [TestMethod] public void _02_DigestMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] digest = null; // Multipart digesting functions C_DigestUpdate and C_DigestFinal can be used i.e. for digesting of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize digesting operation rv = pkcs11.C_DigestInit(session, ref mechanism); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Digest each individual source data part rv = pkcs11.C_DigestUpdate(session, part, Convert.ToUInt64(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Get length of digest value in first call ulong digestLen = 0; rv = pkcs11.C_DigestFinal(session, null, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(digestLen > 0); // Allocate array for digest value digest = new byte[digestLen]; // Get digest value in second call rv = pkcs11.C_DigestFinal(session, digest, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with digest value rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_DigestInit, C_DigestKey and C_DigestFinal test. /// </summary> [TestMethod] public void _03_DigestKeyTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1); // Initialize digesting operation rv = pkcs11.C_DigestInit(session, ref mechanism); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Digest key rv = pkcs11.C_DigestKey(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of digest value in first call ulong digestLen = 0; rv = pkcs11.C_DigestFinal(session, null, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(digestLen > 0); // Allocate array for digest value byte[] digest = new byte[digestLen]; // Get digest value in second call rv = pkcs11.C_DigestFinal(session, digest, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with digest value rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Reflection; using System.ComponentModel; namespace Aga.Controls.Tree.NodeControls { public abstract class BaseTextControl : EditableControl { private TextFormatFlags _baseFormatFlags; private TextFormatFlags _formatFlags; private Pen _focusPen; private StringFormat _format; #region Properties private Font _font = null; public Font Font { get { if (_font == null) return Control.DefaultFont; else return _font; } set { if (value == Control.DefaultFont) _font = null; else _font = value; } } protected bool ShouldSerializeFont() { return (_font != null); } private HorizontalAlignment _textAlign = HorizontalAlignment.Left; [DefaultValue(HorizontalAlignment.Left)] public HorizontalAlignment TextAlign { get { return _textAlign; } set { _textAlign = value; SetFormatFlags(); } } private StringTrimming _trimming = StringTrimming.None; [DefaultValue(StringTrimming.None)] public StringTrimming Trimming { get { return _trimming; } set { _trimming = value; SetFormatFlags(); } } private bool _displayHiddenContentInToolTip = true; [DefaultValue(true)] public bool DisplayHiddenContentInToolTip { get { return _displayHiddenContentInToolTip; } set { _displayHiddenContentInToolTip = value; } } private bool _useCompatibleTextRendering = false; [DefaultValue(false)] public bool UseCompatibleTextRendering { get { return _useCompatibleTextRendering; } set { _useCompatibleTextRendering = value; } } #endregion protected BaseTextControl() { IncrementalSearchEnabled = true; _focusPen = new Pen(Color.Black); _focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; _format = new StringFormat(StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces); _baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.NoPrefix | TextFormatFlags.PreserveGraphicsTranslateTransform; SetFormatFlags(); LeftMargin = 3; } private void SetFormatFlags() { _format.Alignment = TextHelper.TranslateAligment(TextAlign); _format.Trimming = Trimming; _formatFlags = _baseFormatFlags | TextHelper.TranslateAligmentToFlag(TextAlign) | TextHelper.TranslateTrimmingToFlag(Trimming); } public override Size MeasureSize(TreeNodeAdv node, DrawContext context) { return GetLabelSize(node, context); } protected Size GetLabelSize(TreeNodeAdv node, DrawContext context) { return GetLabelSize(node, context, GetLabel(node)); } protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label) { PerformanceAnalyzer.Start("GetLabelSize"); CheckThread(); Font font = GetDrawingFont(node, context, label); Size s = Size.Empty; if (UseCompatibleTextRendering) s = TextRenderer.MeasureText(label, font); else { SizeF sf = context.Graphics.MeasureString(label, font); s = Size.Ceiling(sf); } PerformanceAnalyzer.Finish("GetLabelSize"); if (!s.IsEmpty) return s; else return new Size(10, Font.Height); } protected Font GetDrawingFont(TreeNodeAdv node, DrawContext context, string label) { Font font = context.Font; if (DrawText != null) { DrawEventArgs args = new DrawEventArgs(node, context, label); args.Font = context.Font; OnDrawText(args); font = args.Font; } return font; } protected void SetEditControlProperties(Control control, TreeNodeAdv node) { string label = GetLabel(node); DrawContext context = new DrawContext(); context.Font = control.Font; control.Font = GetDrawingFont(node, context, label); } public override void Draw(TreeNodeAdv node, DrawContext context) { if (context.CurrentEditorOwner == this && node == Parent.CurrentNode) return; PerformanceAnalyzer.Start("BaseTextControl.Draw"); string label = GetLabel(node); Rectangle bounds = GetBounds(node, context); Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y, bounds.Width, context.Bounds.Height); Brush backgroundBrush; Color textColor; Font font; CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label); if (backgroundBrush != null) context.Graphics.FillRectangle(backgroundBrush, focusRect); if (context.DrawFocus) { focusRect.Width--; focusRect.Height--; if (context.DrawSelection == DrawSelectionMode.None) _focusPen.Color = SystemColors.ControlText; else _focusPen.Color = SystemColors.InactiveCaption; context.Graphics.DrawRectangle(_focusPen, focusRect); } if (UseCompatibleTextRendering) TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags); else context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format); PerformanceAnalyzer.Finish("BaseTextControl.Draw"); } private static Dictionary<Color, Brush> _brushes = new Dictionary<Color,Brush>(); private static Brush GetFrush(Color color) { Brush br; if (_brushes.ContainsKey(color)) br = _brushes[color]; else { br = new SolidBrush(color); _brushes.Add(color, br); } return br; } private void CreateBrushes(TreeNodeAdv node, DrawContext context, string text, out Brush backgroundBrush, out Color textColor, out Font font, ref string label) { textColor = SystemColors.ControlText; backgroundBrush = null; font = context.Font; if (context.DrawSelection == DrawSelectionMode.Active) { textColor = SystemColors.HighlightText; backgroundBrush = SystemBrushes.Highlight; } else if (context.DrawSelection == DrawSelectionMode.Inactive) { textColor = SystemColors.ControlText; backgroundBrush = SystemBrushes.InactiveBorder; } else if (context.DrawSelection == DrawSelectionMode.FullRowSelect) textColor = SystemColors.HighlightText; if (!context.Enabled) textColor = SystemColors.GrayText; if (DrawText != null) { DrawEventArgs args = new DrawEventArgs(node, context, text); args.TextColor = textColor; args.BackgroundBrush = backgroundBrush; args.Font = font; OnDrawText(args); textColor = args.TextColor; backgroundBrush = args.BackgroundBrush; font = args.Font; label = args.Text; } } public string GetLabel(TreeNodeAdv node) { if (node != null && node.Tag != null) { object obj = GetValue(node); if (obj != null) return FormatLabel(obj); } return string.Empty; } protected virtual string FormatLabel(object obj) { return obj.ToString(); } public void SetLabel(TreeNodeAdv node, string value) { SetValue(node, value); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _focusPen.Dispose(); _format.Dispose(); } } /// <summary> /// Fires when control is going to draw a text. Can be used to change text or back color /// </summary> public event EventHandler<DrawEventArgs> DrawText; protected virtual void OnDrawText(DrawEventArgs args) { if (DrawText != null) DrawText(this, args); } } }
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 Tasks.Query.Api.Areas.HelpPage.SampleGeneration { /// <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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Uheer.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Orders; using Nop.Services.Events; using Nop.Services.Stores; namespace Nop.Services.Orders { /// <summary> /// Checkout attribute service /// </summary> public partial class CheckoutAttributeService : ICheckoutAttributeService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : store ID /// {1} : >A value indicating whether we should exlude shippable attributes /// </remarks> private const string CHECKOUTATTRIBUTES_ALL_KEY = "Nop.checkoutattribute.all-{0}-{1}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : checkout attribute ID /// </remarks> private const string CHECKOUTATTRIBUTES_BY_ID_KEY = "Nop.checkoutattribute.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : checkout attribute ID /// </remarks> private const string CHECKOUTATTRIBUTEVALUES_ALL_KEY = "Nop.checkoutattributevalue.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : checkout attribute value ID /// </remarks> private const string CHECKOUTATTRIBUTEVALUES_BY_ID_KEY = "Nop.checkoutattributevalue.id-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string CHECKOUTATTRIBUTES_PATTERN_KEY = "Nop.checkoutattribute."; /// <summary> /// Key pattern to clear cache /// </summary> private const string CHECKOUTATTRIBUTEVALUES_PATTERN_KEY = "Nop.checkoutattributevalue."; #endregion #region Fields private readonly IRepository<CheckoutAttribute> _checkoutAttributeRepository; private readonly IRepository<CheckoutAttributeValue> _checkoutAttributeValueRepository; private readonly IStoreMappingService _storeMappingService; private readonly IEventPublisher _eventPublisher; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="checkoutAttributeRepository">Checkout attribute repository</param> /// <param name="checkoutAttributeValueRepository">Checkout attribute value repository</param> /// <param name="storeMappingService">Store mapping service</param> /// <param name="eventPublisher">Event published</param> public CheckoutAttributeService(ICacheManager cacheManager, IRepository<CheckoutAttribute> checkoutAttributeRepository, IRepository<CheckoutAttributeValue> checkoutAttributeValueRepository, IStoreMappingService storeMappingService, IEventPublisher eventPublisher) { this._cacheManager = cacheManager; this._checkoutAttributeRepository = checkoutAttributeRepository; this._checkoutAttributeValueRepository = checkoutAttributeValueRepository; this._storeMappingService = storeMappingService; this._eventPublisher = eventPublisher; } #endregion #region Methods #region Checkout attributes /// <summary> /// Deletes a checkout attribute /// </summary> /// <param name="checkoutAttribute">Checkout attribute</param> public virtual void DeleteCheckoutAttribute(CheckoutAttribute checkoutAttribute) { if (checkoutAttribute == null) throw new ArgumentNullException("checkoutAttribute"); _checkoutAttributeRepository.Delete(checkoutAttribute); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(checkoutAttribute); } /// <summary> /// Gets all checkout attributes /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="excludeShippableAttributes">A value indicating whether we should exlude shippable attributes</param> /// <returns>Checkout attribute collection</returns> public virtual IList<CheckoutAttribute> GetAllCheckoutAttributes(int storeId = 0, bool excludeShippableAttributes = false) { string key = string.Format(CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes); return _cacheManager.Get(key, () => { var query = from ca in _checkoutAttributeRepository.Table orderby ca.DisplayOrder select ca; var checkoutAttributes = query.ToList(); if (storeId > 0) { //store mapping checkoutAttributes = checkoutAttributes.Where(ca => _storeMappingService.Authorize(ca)).ToList(); } if (excludeShippableAttributes) { //remove attributes which require shippable products checkoutAttributes = checkoutAttributes.RemoveShippableAttributes().ToList(); } return checkoutAttributes; }); } /// <summary> /// Gets a checkout attribute /// </summary> /// <param name="checkoutAttributeId">Checkout attribute identifier</param> /// <returns>Checkout attribute</returns> public virtual CheckoutAttribute GetCheckoutAttributeById(int checkoutAttributeId) { if (checkoutAttributeId == 0) return null; string key = string.Format(CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId); return _cacheManager.Get(key, () => { return _checkoutAttributeRepository.GetById(checkoutAttributeId); }); } /// <summary> /// Inserts a checkout attribute /// </summary> /// <param name="checkoutAttribute">Checkout attribute</param> public virtual void InsertCheckoutAttribute(CheckoutAttribute checkoutAttribute) { if (checkoutAttribute == null) throw new ArgumentNullException("checkoutAttribute"); _checkoutAttributeRepository.Insert(checkoutAttribute); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(checkoutAttribute); } /// <summary> /// Updates the checkout attribute /// </summary> /// <param name="checkoutAttribute">Checkout attribute</param> public virtual void UpdateCheckoutAttribute(CheckoutAttribute checkoutAttribute) { if (checkoutAttribute == null) throw new ArgumentNullException("checkoutAttribute"); _checkoutAttributeRepository.Update(checkoutAttribute); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(checkoutAttribute); } #endregion #region Checkout variant attribute values /// <summary> /// Deletes a checkout attribute value /// </summary> /// <param name="checkoutAttributeValue">Checkout attribute value</param> public virtual void DeleteCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue) { if (checkoutAttributeValue == null) throw new ArgumentNullException("checkoutAttributeValue"); _checkoutAttributeValueRepository.Delete(checkoutAttributeValue); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(checkoutAttributeValue); } /// <summary> /// Gets checkout attribute values by checkout attribute identifier /// </summary> /// <param name="checkoutAttributeId">The checkout attribute identifier</param> /// <returns>Checkout attribute value collection</returns> public virtual IList<CheckoutAttributeValue> GetCheckoutAttributeValues(int checkoutAttributeId) { string key = string.Format(CHECKOUTATTRIBUTEVALUES_ALL_KEY, checkoutAttributeId); return _cacheManager.Get(key, () => { var query = from cav in _checkoutAttributeValueRepository.Table orderby cav.DisplayOrder where cav.CheckoutAttributeId == checkoutAttributeId select cav; var checkoutAttributeValues = query.ToList(); return checkoutAttributeValues; }); } /// <summary> /// Gets a checkout attribute value /// </summary> /// <param name="checkoutAttributeValueId">Checkout attribute value identifier</param> /// <returns>Checkout attribute value</returns> public virtual CheckoutAttributeValue GetCheckoutAttributeValueById(int checkoutAttributeValueId) { if (checkoutAttributeValueId == 0) return null; string key = string.Format(CHECKOUTATTRIBUTEVALUES_BY_ID_KEY, checkoutAttributeValueId); return _cacheManager.Get(key, () => { return _checkoutAttributeValueRepository.GetById(checkoutAttributeValueId); }); } /// <summary> /// Inserts a checkout attribute value /// </summary> /// <param name="checkoutAttributeValue">Checkout attribute value</param> public virtual void InsertCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue) { if (checkoutAttributeValue == null) throw new ArgumentNullException("checkoutAttributeValue"); _checkoutAttributeValueRepository.Insert(checkoutAttributeValue); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(checkoutAttributeValue); } /// <summary> /// Updates the checkout attribute value /// </summary> /// <param name="checkoutAttributeValue">Checkout attribute value</param> public virtual void UpdateCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue) { if (checkoutAttributeValue == null) throw new ArgumentNullException("checkoutAttributeValue"); _checkoutAttributeValueRepository.Update(checkoutAttributeValue); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(checkoutAttributeValue); } #endregion #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using Microsoft.Azure; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Protocol; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// A job schedule that allows recurring jobs by specifying when to run /// jobs and a specification used to create each job. /// </summary> public partial class CloudJobSchedule { /// <summary> /// Initializes a new instance of the CloudJobSchedule class. /// </summary> public CloudJobSchedule() { CustomInit(); } /// <summary> /// Initializes a new instance of the CloudJobSchedule class. /// </summary> /// <param name="id">A string that uniquely identifies the schedule /// within the account.</param> /// <param name="displayName">The display name for the /// schedule.</param> /// <param name="url">The URL of the job schedule.</param> /// <param name="eTag">The ETag of the job schedule.</param> /// <param name="lastModified">The last modified time of the job /// schedule.</param> /// <param name="creationTime">The creation time of the job /// schedule.</param> /// <param name="state">The current state of the job schedule.</param> /// <param name="stateTransitionTime">The time at which the job /// schedule entered the current state.</param> /// <param name="previousState">The previous state of the job /// schedule.</param> /// <param name="previousStateTransitionTime">The time at which the job /// schedule entered its previous state.</param> /// <param name="schedule">The schedule according to which jobs will be /// created.</param> /// <param name="jobSpecification">The details of the jobs to be /// created on this schedule.</param> /// <param name="executionInfo">Information about jobs that have been /// and will be run under this schedule.</param> /// <param name="metadata">A list of name-value pairs associated with /// the schedule as metadata.</param> /// <param name="stats">The lifetime resource usage statistics for the /// job schedule.</param> public CloudJobSchedule(string id = default(string), string displayName = default(string), string url = default(string), string eTag = default(string), System.DateTime? lastModified = default(System.DateTime?), System.DateTime? creationTime = default(System.DateTime?), JobScheduleState? state = default(JobScheduleState?), System.DateTime? stateTransitionTime = default(System.DateTime?), JobScheduleState? previousState = default(JobScheduleState?), System.DateTime? previousStateTransitionTime = default(System.DateTime?), Schedule schedule = default(Schedule), JobSpecification jobSpecification = default(JobSpecification), JobScheduleExecutionInformation executionInfo = default(JobScheduleExecutionInformation), IList<MetadataItem> metadata = default(IList<MetadataItem>), JobScheduleStatistics stats = default(JobScheduleStatistics)) { Id = id; DisplayName = displayName; Url = url; ETag = eTag; LastModified = lastModified; CreationTime = creationTime; State = state; StateTransitionTime = stateTransitionTime; PreviousState = previousState; PreviousStateTransitionTime = previousStateTransitionTime; Schedule = schedule; JobSpecification = jobSpecification; ExecutionInfo = executionInfo; Metadata = metadata; Stats = stats; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets a string that uniquely identifies the schedule within /// the account. /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets the display name for the schedule. /// </summary> [JsonProperty(PropertyName = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the URL of the job schedule. /// </summary> [JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or sets the ETag of the job schedule. /// </summary> /// <remarks> /// This is an opaque string. You can use it to detect whether the job /// schedule has changed between requests. In particular, you can be /// pass the ETag with an Update Job Schedule request to specify that /// your changes should take effect only if nobody else has modified /// the schedule in the meantime. /// </remarks> [JsonProperty(PropertyName = "eTag")] public string ETag { get; set; } /// <summary> /// Gets or sets the last modified time of the job schedule. /// </summary> /// <remarks> /// This is the last time at which the schedule level data, such as the /// job specification or recurrence information, changed. It does not /// factor in job-level changes such as new jobs being created or jobs /// changing state. /// </remarks> [JsonProperty(PropertyName = "lastModified")] public System.DateTime? LastModified { get; set; } /// <summary> /// Gets or sets the creation time of the job schedule. /// </summary> [JsonProperty(PropertyName = "creationTime")] public System.DateTime? CreationTime { get; set; } /// <summary> /// Gets or sets the current state of the job schedule. /// </summary> /// <remarks> /// Possible values include: 'active', 'completed', 'disabled', /// 'terminating', 'deleting' /// </remarks> [JsonProperty(PropertyName = "state")] public JobScheduleState? State { get; set; } /// <summary> /// Gets or sets the time at which the job schedule entered the current /// state. /// </summary> [JsonProperty(PropertyName = "stateTransitionTime")] public System.DateTime? StateTransitionTime { get; set; } /// <summary> /// Gets or sets the previous state of the job schedule. /// </summary> /// <remarks> /// This property is not present if the job schedule is in its initial /// active state. Possible values include: 'active', 'completed', /// 'disabled', 'terminating', 'deleting' /// </remarks> [JsonProperty(PropertyName = "previousState")] public JobScheduleState? PreviousState { get; set; } /// <summary> /// Gets or sets the time at which the job schedule entered its /// previous state. /// </summary> /// <remarks> /// This property is not present if the job schedule is in its initial /// active state. /// </remarks> [JsonProperty(PropertyName = "previousStateTransitionTime")] public System.DateTime? PreviousStateTransitionTime { get; set; } /// <summary> /// Gets or sets the schedule according to which jobs will be created. /// </summary> [JsonProperty(PropertyName = "schedule")] public Schedule Schedule { get; set; } /// <summary> /// Gets or sets the details of the jobs to be created on this /// schedule. /// </summary> [JsonProperty(PropertyName = "jobSpecification")] public JobSpecification JobSpecification { get; set; } /// <summary> /// Gets or sets information about jobs that have been and will be run /// under this schedule. /// </summary> [JsonProperty(PropertyName = "executionInfo")] public JobScheduleExecutionInformation ExecutionInfo { get; set; } /// <summary> /// Gets or sets a list of name-value pairs associated with the /// schedule as metadata. /// </summary> /// <remarks> /// The Batch service does not assign any meaning to metadata; it is /// solely for the use of user code. /// </remarks> [JsonProperty(PropertyName = "metadata")] public IList<MetadataItem> Metadata { get; set; } /// <summary> /// Gets or sets the lifetime resource usage statistics for the job /// schedule. /// </summary> [JsonProperty(PropertyName = "stats")] public JobScheduleStatistics Stats { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (JobSpecification != null) { JobSpecification.Validate(); } if (Metadata != null) { foreach (var element in Metadata) { if (element != null) { element.Validate(); } } } if (Stats != null) { Stats.Validate(); } } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ThisToThat; namespace ThisToThatTests { [TestClass] public class ToSByteTests { /// <summary> /// Makes multiple Byte to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestByteToSByteOrDefault() { // Test conversion of source type minimum value Byte source = Byte.MinValue; Assert.IsInstanceOfType(source, typeof(Byte)); SByte? result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = (byte)42; Assert.IsInstanceOfType(source, typeof(Byte)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Byte.MaxValue; Assert.IsInstanceOfType(source, typeof(Byte)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (255) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple Byte to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestByteToSByteNullable() { // Test conversion of source type minimum value Byte source = Byte.MinValue; Assert.IsInstanceOfType(source, typeof(Byte)); SByte? result = source.ToSByteNullable(); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = (byte)42; Assert.IsInstanceOfType(source, typeof(Byte)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Byte.MaxValue; Assert.IsInstanceOfType(source, typeof(Byte)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (255) is greater than the target type's maximum value (127). Assert.IsNull(result); } /// <summary> /// Makes multiple Int16 to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestInt16ToSByteOrDefault() { // Test conversion of source type minimum value Int16 source = Int16.MinValue; Assert.IsInstanceOfType(source, typeof(Int16)); SByte? result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's minimum value (-32768) is less than the target type's minimum value (-128). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = (short)42; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Int16.MaxValue; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (32767) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple Int16 to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestInt16ToSByteNullable() { // Test conversion of source type minimum value Int16 source = Int16.MinValue; Assert.IsInstanceOfType(source, typeof(Int16)); SByte? result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-32768) is less than the target type's minimum value (-128). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = (short)42; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Int16.MaxValue; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (32767) is greater than the target type's maximum value (127). Assert.IsNull(result); } /// <summary> /// Makes multiple UInt16 to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestUInt16ToSByteOrDefault() { // Test conversion of source type minimum value UInt16 source = UInt16.MinValue; Assert.IsInstanceOfType(source, typeof(UInt16)); SByte? result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = (ushort)42; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = UInt16.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (65535) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple UInt16 to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestUInt16ToSByteNullable() { // Test conversion of source type minimum value UInt16 source = UInt16.MinValue; Assert.IsInstanceOfType(source, typeof(UInt16)); SByte? result = source.ToSByteNullable(); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = (ushort)42; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = UInt16.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt16)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (65535) is greater than the target type's maximum value (127). Assert.IsNull(result); } /// <summary> /// Makes multiple Int32 to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestInt32ToSByteOrDefault() { // Test conversion of source type minimum value Int32 source = Int32.MinValue; Assert.IsInstanceOfType(source, typeof(Int32)); SByte? result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's minimum value (-2147483648) is less than the target type's minimum value (-128). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = 42; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Int32.MaxValue; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (2147483647) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple Int32 to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestInt32ToSByteNullable() { // Test conversion of source type minimum value Int32 source = Int32.MinValue; Assert.IsInstanceOfType(source, typeof(Int32)); SByte? result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-2147483648) is less than the target type's minimum value (-128). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = 42; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Int32.MaxValue; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (2147483647) is greater than the target type's maximum value (127). Assert.IsNull(result); } /// <summary> /// Makes multiple UInt32 to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestUInt32ToSByteOrDefault() { // Test conversion of source type minimum value UInt32 source = UInt32.MinValue; Assert.IsInstanceOfType(source, typeof(UInt32)); SByte? result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = 42u; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = UInt32.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (4294967295) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple UInt32 to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestUInt32ToSByteNullable() { // Test conversion of source type minimum value UInt32 source = UInt32.MinValue; Assert.IsInstanceOfType(source, typeof(UInt32)); SByte? result = source.ToSByteNullable(); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = 42u; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = UInt32.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (4294967295) is greater than the target type's maximum value (127). Assert.IsNull(result); } /// <summary> /// Makes multiple Int64 to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestInt64ToSByteOrDefault() { // Test conversion of source type minimum value Int64 source = Int64.MinValue; Assert.IsInstanceOfType(source, typeof(Int64)); SByte? result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (-128). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = 42L; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Int64.MaxValue; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple Int64 to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestInt64ToSByteNullable() { // Test conversion of source type minimum value Int64 source = Int64.MinValue; Assert.IsInstanceOfType(source, typeof(Int64)); SByte? result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (-128). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = 42L; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = Int64.MaxValue; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (127). Assert.IsNull(result); } /// <summary> /// Makes multiple UInt64 to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestUInt64ToSByteOrDefault() { // Test conversion of source type minimum value UInt64 source = UInt64.MinValue; Assert.IsInstanceOfType(source, typeof(UInt64)); SByte? result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = 42UL; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = UInt64.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToSByteOrDefault((sbyte)86); // Here we would expect this conversion to fail (and return the default value of (sbyte)86), // since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (127). Assert.AreEqual((sbyte)86, result); Assert.IsInstanceOfType(result, typeof(SByte)); } /// <summary> /// Makes multiple UInt64 to nullable SByte conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestUInt64ToSByteNullable() { // Test conversion of source type minimum value UInt64 source = UInt64.MinValue; Assert.IsInstanceOfType(source, typeof(UInt64)); SByte? result = source.ToSByteNullable(); Assert.AreEqual((sbyte)0, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type value 42 to target type source = 42UL; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToSByteNullable(); Assert.AreEqual((sbyte)42, result); Assert.IsInstanceOfType(result, typeof(SByte)); // Test conversion of source type maximum value source = UInt64.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToSByteNullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (127). Assert.IsNull(result); } /* Single to SByte: Method omitted. SByte is an integral type. Single is non-integral (can contain fractions). Conversions involving possible rounding or truncation are not currently provided by this library. */ /* Double to SByte: Method omitted. SByte is an integral type. Double is non-integral (can contain fractions). Conversions involving possible rounding or truncation are not currently provided by this library. */ /* Decimal to SByte: Method omitted. SByte is an integral type. Decimal is non-integral (can contain fractions). Conversions involving possible rounding or truncation are not currently provided by this library. */ /// <summary> /// Makes multiple String to SByte or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestStringToSByteOrDefault() { // Test conversion of target type minimum value SByte resultMin = "-128".ToSByteOrDefault(); Assert.AreEqual((sbyte)-128, resultMin); // Test conversion of fixed value (42) SByte result42 = "42".ToSByteOrDefault(); Assert.AreEqual((sbyte)42, result42); // Test conversion of target type maximum value SByte resultMax = "127".ToSByteOrDefault(); Assert.AreEqual((sbyte)127, resultMax); // Test conversion of "foo" SByte resultFoo = "foo".ToSByteOrDefault((sbyte)86); Assert.AreEqual((sbyte)86, resultFoo); } /// <summary> /// Makes multiple String to SByteNullable conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToSByte tests")] public void TestStringToSByteNullable() { // Test conversion of target type minimum value SByte? resultMin = "-128".ToSByteNullable(); Assert.AreEqual((sbyte)-128, resultMin); // Test conversion of fixed value (42) SByte? result42 = "42".ToSByteNullable(); Assert.AreEqual((sbyte)42, result42); // Test conversion of target type maximum value SByte? resultMax = "127".ToSByteNullable(); Assert.AreEqual((sbyte)127, resultMax); // Test conversion of "foo" SByte? resultFoo = "foo".ToSByteNullable(); Assert.IsNull(resultFoo); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading { /// <summary> /// Propagates notification that operations should be canceled. /// </summary> /// <remarks> /// <para> /// A <see cref="CancellationToken"/> may be created directly in an unchangeable canceled or non-canceled state /// using the CancellationToken's constructors. However, to have a CancellationToken that can change /// from a non-canceled to a canceled state, /// <see cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see> must be used. /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its /// <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property. /// </para> /// <para> /// Once canceled, a token may not transition to a non-canceled state, and a token whose /// <see cref="CanBeCanceled"/> is false will never change to one that can be canceled. /// </para> /// <para> /// All members of this struct are thread-safe and may be used concurrently from multiple threads. /// </para> /// </remarks> [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] public readonly struct CancellationToken { // The backing TokenSource. // if null, it implicitly represents the same thing as new CancellationToken(false). // When required, it will be instantiated to reflect this. private readonly CancellationTokenSource _source; //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid private readonly static Action<object> s_actionToActionObjShunt = obj => ((Action)obj)(); /// <summary> /// Returns an empty CancellationToken value. /// </summary> /// <remarks> /// The <see cref="CancellationToken"/> value returned by this property will be non-cancelable by default. /// </remarks> public static CancellationToken None => default; /// <summary> /// Gets whether cancellation has been requested for this token. /// </summary> /// <value>Whether cancellation has been requested for this token.</value> /// <remarks> /// <para> /// This property indicates whether cancellation has been requested for this token, /// either through the token initially being constructed in a canceled state, or through /// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see> /// on the token's associated <see cref="CancellationTokenSource"/>. /// </para> /// <para> /// If this property is true, it only guarantees that cancellation has been requested. /// It does not guarantee that every registered handler /// has finished executing, nor that cancellation requests have finished propagating /// to all registered handlers. Additional synchronization may be required, /// particularly in situations where related objects are being canceled concurrently. /// </para> /// </remarks> public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested; /// <summary> /// Gets whether this token is capable of being in the canceled state. /// </summary> /// <remarks> /// If CanBeCanceled returns false, it is guaranteed that the token will never transition /// into a canceled state, meaning that <see cref="IsCancellationRequested"/> will never /// return true. /// </remarks> public bool CanBeCanceled => _source != null; /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is signaled when the token is canceled.</summary> /// <remarks> /// Accessing this property causes a <see cref="T:System.Threading.WaitHandle">WaitHandle</see> /// to be instantiated. It is preferable to only use this property when necessary, and to then /// dispose the associated <see cref="CancellationTokenSource"/> instance at the earliest opportunity (disposing /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle; // public CancellationToken() // this constructor is implicit for structs // -> this should behaves exactly as for new CancellationToken(false) /// <summary> /// Internal constructor only a CancellationTokenSource should create a CancellationToken /// </summary> internal CancellationToken(CancellationTokenSource source) => _source = source; /// <summary> /// Initializes the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <param name="canceled"> /// The canceled state for the token. /// </param> /// <remarks> /// Tokens created with this constructor will remain in the canceled state specified /// by the <paramref name="canceled"/> parameter. If <paramref name="canceled"/> is false, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be false. /// If <paramref name="canceled"/> is true, /// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be true. /// </remarks> public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null) { } /// <summary> /// Registers a delegate that will be called when this <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback) => Register( s_actionToActionObjShunt, callback ?? throw new ArgumentNullException(nameof(callback)), useSynchronizationContext: false, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) => Register( s_actionToActionObjShunt, callback ?? throw new ArgumentNullException(nameof(callback)), useSynchronizationContext, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured /// along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration Register(Action<object> callback, object state) => Register(callback, state, useSynchronizationContext: false, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// <para> /// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, /// will be captured along with the delegate and will be used when executing it. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public CancellationTokenRegistration Register(Action<object> callback, object state, bool useSynchronizationContext) => Register(callback, state, useSynchronizationContext, useExecutionContext: true); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the delegate will be run immediately and synchronously. /// Any exception the delegate generates will be propagated out of this method call. /// </para> /// <para> /// <see cref="System.Threading.ExecutionContext">ExecutionContext</see> is not captured nor flowed /// to the callback's invocation. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> public CancellationTokenRegistration UnsafeRegister(Action<object> callback, object state) => Register(callback, state, useSynchronizationContext: false, useExecutionContext: false); /// <summary> /// Registers a delegate that will be called when this /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled. /// </summary> /// <remarks> /// <para> /// If this token is already in the canceled state, the /// delegate will be run immediately and synchronously. Any exception the delegate generates will be /// propagated out of this method call. /// </para> /// </remarks> /// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param> /// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param> /// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture /// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it /// when invoking the <paramref name="callback"/>.</param> /// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can /// be used to unregister the callback.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> #if CORECLR private #else [MethodImpl(MethodImplOptions.NoInlining)] public #endif CancellationTokenRegistration Register(Action<object> callback, object state, bool useSynchronizationContext, bool useExecutionContext) { if (callback == null) throw new ArgumentNullException(nameof(callback)); CancellationTokenSource source = _source; return source != null ? source.InternalRegister(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) : default; // Nothing to do for tokens than can never reach the canceled state. Give back a dummy registration. } /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified token. /// </summary> /// <param name="other">The other <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to which to compare this /// instance.</param> /// <returns>True if the instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> public bool Equals(CancellationToken other) => _source == other._source; /// <summary> /// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the /// specified <see cref="T:System.Object"/>. /// </summary> /// <param name="other">The other object to which to compare this instance.</param> /// <returns>True if <paramref name="other"/> is a <see cref="T:System.Threading.CancellationToken">CancellationToken</see> /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated /// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed /// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public override bool Equals(object other) => other is CancellationToken && Equals((CancellationToken)other); /// <summary> /// Serves as a hash function for a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>. /// </summary> /// <returns>A hash code for the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance.</returns> public override int GetHashCode() => (_source ?? CancellationTokenSource.s_neverCanceledSource).GetHashCode(); /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator ==(CancellationToken left, CancellationToken right) => left.Equals(right); /// <summary> /// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are not equal. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True if the instances are not equal; otherwise, false.</returns> /// <exception cref="T:System.ObjectDisposedException">An associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public static bool operator !=(CancellationToken left, CancellationToken right) => !left.Equals(right); /// <summary> /// Throws a <see cref="T:System.OperationCanceledException">OperationCanceledException</see> if /// this token has had cancellation requested. /// </summary> /// <remarks> /// This method provides functionality equivalent to: /// <code> /// if (token.IsCancellationRequested) /// throw new OperationCanceledException(token); /// </code> /// </remarks> /// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception> /// <exception cref="T:System.ObjectDisposedException">The associated <see /// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception> public void ThrowIfCancellationRequested() { if (IsCancellationRequested) ThrowOperationCanceledException(); } // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested private void ThrowOperationCanceledException() => throw new OperationCanceledException(SR.OperationCanceled, this); } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using MyWebPlayground.Models; namespace MyWebPlayground.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("MyWebPlayground.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("MyWebPlayground.Models.Document", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Author") .IsRequired(); b.Property<string>("Css") .IsRequired(); b.Property<string>("CssMode") .IsRequired(); b.Property<string>("Description") .IsRequired(); b.Property<string>("Html") .IsRequired(); b.Property<string>("HtmlMode") .IsRequired(); b.Property<string>("Javascript") .IsRequired(); b.Property<string>("JavascriptMode") .IsRequired(); b.Property<string>("MarkupChoice") .IsRequired(); b.Property<string>("ScriptChoice") .IsRequired(); b.Property<string>("StyleChoice") .IsRequired(); b.Property<string>("Title") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("MyWebPlayground.Models.DocumentCssLibrary", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CssLibrary") .IsRequired(); b.Property<int?>("DocumentId"); b.HasKey("Id"); }); modelBuilder.Entity("MyWebPlayground.Models.DocumentJavascriptLibrary", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("DocumentId"); b.Property<string>("JavascriptLibrary") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("MyWebPlayground.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("MyWebPlayground.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("MyWebPlayground.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("MyWebPlayground.Models.DocumentCssLibrary", b => { b.HasOne("MyWebPlayground.Models.Document") .WithMany() .HasForeignKey("DocumentId"); }); modelBuilder.Entity("MyWebPlayground.Models.DocumentJavascriptLibrary", b => { b.HasOne("MyWebPlayground.Models.Document") .WithMany() .HasForeignKey("DocumentId"); }); } } }
// Created by Paul Gonzalez Becerra using System; using System.Runtime.InteropServices; using Saserdote.Mathematics.Collision; namespace Saserdote.Mathematics { [StructLayout(LayoutKind.Sequential)] public struct Point2i { #region --- Field Variables --- // Variables public int x; public int y; public readonly static Point2i ORIGIN= new Point2i(0); #endregion // Field Variables #region --- Constructors --- public Point2i(int pmX, int pmY) { x= pmX; y= pmY; } internal Point2i(int all):this(all, all) {} #endregion // Constructors #region --- Static Methods --- // Gets an acuaml point from the given system point public static Point2i fromSysPoint(System.Drawing.Point pt) { return new Point2i(pt.X, pt.Y); } #endregion // Static Methods #region --- Methods --- // Converts the point into a system point public System.Drawing.Point toSysPoint() { return new System.Drawing.Point(x, y); } // Converts the point into an integer point public Point2f toPoint2f() { return new Point2f((float)x, (float) y); } // Converts the 2d point into a 3d point public Point3f toPoint3f() { return new Point3f((float)x, (float)y, 0f); } // Converts the 3d point into a 3d point public Point3i toPoint3i() { return new Point3i(x, y, 0); } // Converts the point into a vector public Vector3 toVector3() { return new Vector3((float)x, (float)y, 0f); } // Converts the point into a vector public Vector2 toVector2() { return new Vector2((float)x, (float)y); } // Adds the point with the vector to get another point public Point2i add(Vector3 vec) { return new Point2i(x+(int)vec.x, y+(int)vec.y); } // Adds the point with the vector to get another point public Point2i add(Vector2 vec) { return new Point2i(x+(int)vec.x, y+(int)vec.y); } // Adds the point with a size to get another point public Point2i add(Size3f size) { return new Point2i(x+(int)size.width, y+(int)size.height); } // Adds the point with a size to get another point public Point2i add(Size3i size) { return new Point2i(x+size.width, y+size.height); } // Adds the point with a size to get another point public Point2i add(Size2f size) { return new Point2f(x+(int)size.width, y+(int)size.height); } // Adds the point with a size to get another point public Point2i add(Size2i size) { return new Point2i(x+size.width, y+size.height); } // Subtracts the point with the vector to get another point public Point2i subtract(Vector3 vec) { return new Point2i(x-(int)vec.x, y-(int)vec.x); } // Subtracts the point with the vector to get another point public Point2i subtract(Vector2 vec) { return new Point2i(x-(int)vec.x, y-(int)vec.x); } // Subtracts the point with a size to get another point public Point2i subtract(Size3f size) { return new Point2i(x-(int)size.width, y-(int)size.height); } // Subtracts the point with a size to get another point public Point2i subtract(Size3i size) { return new Point2i(x-size.width, y-size.height); } // Subtracts the point with a size to get another point public Point2i subtract(Size2f size) { return new Point2i(x-(int)size.width, y-(int)size.height); } // Subtracts the point with a size to get another point public Point2i subtract(Size2i size) { return new Point2i(x-size.width, y-size.height); } // Subtracts the two points to get a vector pointing in between both public Vector2 subtract(Point2i pt) { return new Vector2((float)(x-pt.x), (float)(y-pt.y)); } // Subtracts the two points to get a vector pointing in between both public Vector2 subtract(Point2f pt) { return new Vector2((float)x-pt.x, (float)y-pt.y); } // Subtracts the two points to get a vector pointing in between both public Vector3 subtract(Point3i pt) { return new Vector3((float)(x-pt.x), (float)(y-pt.y), 0f-(float)pt.z); } // Subtracts the two points to get a vector pointing in between both public Vector3 subtract(Point3f pt) { return new Vector3((float)x-pt.x, (float)y-pt.y, 0f-pt.z); } // Gets the midpoint of the two points public Point3f getMidpoint(Point3f pt) { return new Point3f(((float)x+pt.x)/2f, ((float)y+pt.y)/2f, (0+pt.z)/2f); } // Gets the midpoint of the two points public Point3f getMidpoint(Point3i pt) { return new Point3f((float)(x+pt.x)/2f, (float)(y+pt.y)/2f, (float)(0+pt.z)/2f); } // Gets the midpoint of the two points public Point2f getMidpoint(Point2f pt) { return new Point2f(((float)x+pt.x)/2f, ((float)y+pt.y)/2f); } // Gets the midpoint of the two points public Point2f getMidpoint(Point2i pt) { return new Point2f((float)(x+pt.x)/2f, (float)(y+pt.y)/2f); } // Finds if the two points are equal public bool equals(Point2i pt) { return (x== pt.x && y== pt.y); } // Finds if the two points are equal public bool equals(Point2f pt) { return (x== (int)pt.x && y== (int)pt.y); } #endregion // Methods #region --- Inherited Methods --- // Finds out if the given object is equal to the point public override bool Equals(object obj) { if(obj== null) return false; if(obj is Point2f) return equals((Point2f)obj); if(obj is Point2i) return equals((Point2i)obj); return false; } // Gets the hash code public override int GetHashCode() { return (x^y); } // Prints out the contents of the point public override string ToString() { return "X:"+x+",Y:"+y; } #endregion // Inherited Methods #region --- Operators --- // Equality operators public static bool operator ==(Point2i left, Point2i right) { return left.equals(right); } public static bool operator ==(Point2i left, Point2f right) { return left.equals(right); } // Inequality operators public static bool operator !=(Point2i left, Point2i right) { return !left.equals(right); } public static bool operator !=(Point2i left, Point2f right) { return !left.equals(right); } // Addition operators public static Point2i operator +(Point2i left, Vector3 right) { return left.add(right); } public static Point2i operator +(Point2i left, Vector2 right) { return left.add(right); } public static Point2i operator +(Point2i left, Size3f right) { return left.add(right); } public static Point2i operator +(Point2i left, Size3i right) { return left.add(right); } public static Point2i operator +(Point2i left, Size2f right) { return left.add(right); } public static Point2i operator +(Point2i left, Size2i right) { return left.add(right); } // Subtration operators public static Point2i operator -(Point2i left, Vector3 right) { return left.subtract(right); } public static Point2i operator -(Point2i left, Vector2 right) { return left.subtract(right); } public static Point2i operator -(Point2i left, Size3f right) { return left.subtract(right); } public static Point2i operator -(Point2i left, Size3i right) { return left.subtract(right); } public static Point2i operator -(Point2i left, Size2f right) { return left.subtract(right); } public static Point2i operator -(Point2i left, Size2i right) { return left.subtract(right); } public static Vector3 operator -(Point2i left, Point3f right) { return left.subtract(right); } public static Vector3 operator -(Point2i left, Point3i right) { return left.subtract(right); } public static Vector2 operator -(Point2i left, Point2f right) { return left.subtract(right); } public static Vector2 operator -(Point2i left, Point2i right) { return left.subtract(right); } // Multiplication operators public static bool operator *(Point2i left, BoundingVolume right) { return right.contains(left); } // Unkown name operators public static Point3f operator |(Point2i left, Point3f right) { return left.getMidpoint(right); } public static Point3f operator |(Point2i left, Point3i right) { return left.getMidpoint(right); } public static Point2f operator |(Point2i left, Point2f right) { return left.getMidpoint(right); } public static Point2f operator |(Point2i left, Point2i right) { return left.getMidpoint(right); } // Conversion operators // [Point2i to Vector3] public static explicit operator Vector3(Point2i castee) { return castee.toVector3(); } // [Point2i to Vector2] public static explicit operator Vector2(Point2i castee) { return castee.toVector2(); } // [Point2i to Point3f] public static explicit operator Point3f(Point2i castee) { return castee.toPoint3f(); } // [Point2i to Point3i] public static explicit operator Point3i(Point2i castee) { return castee.toPoint3i(); } // [Point2i to Point2f] public static implicit operator Point2f(Point2i castee) { return castee.toPoint2f(); } // [Point2i to System.Drawing.Point] public static implicit operator System.Drawing.Point(Point2i castee) { return castee.toSysPoint(); } // [System.Drawing.Point to Point2i] public static implicit operator Point2i(System.Drawing.Point castee) { return Point2i.fromSysPoint(castee); } #endregion // Operators } } // End of File
#region Apache License // // 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. // #endregion // Compatibility: // http://msdn.microsoft.com/en-us/library/system.console.foregroundcolor.aspx // Disable for unsupported targets #if !NETCF #if !SSCLI #if !CLI_1_0 #if !MONO_1_0 #if !NET_1_0 #if !NET_1_1 #if !NETMF // The original ColoredConsoleAppender was written before the .NET framework // (and Mono) had built-in support for console colors so it was written using // Win32 API calls. The AnsiColorTerminalAppender, while it works, isn't // understood by the Windows command prompt. // This is a replacement for both that uses the new (.NET 2) Console colors // and works on both platforms. // On Mono/Linux (at least), setting the background color to 'Black' is // not the same as the default background color, as it is after // Console.Reset(). The difference becomes apparent while running in a // terminal application that supports background transparency; the // default color is treated as transparent while 'Black' isn't. // For this reason, we always reset the colors and only set those // explicitly specified in the configuration (Console.BackgroundColor // isn't set if ommited). using System; using log4net.Layout; using log4net.Util; using System.Globalization; namespace log4net.Appender { /// <summary> /// Appends colorful logging events to the console, using the .NET 2 /// built-in capabilities. /// </summary> /// <remarks> /// <para> /// ManagedColoredConsoleAppender appends log events to the standard output stream /// or the error output stream using a layout specified by the /// user. It also allows the color of a specific type of message to be set. /// </para> /// <para> /// By default, all output is written to the console's standard output stream. /// The <see cref="Target"/> property can be set to direct the output to the /// error stream. /// </para> /// <para> /// When configuring the colored console appender, mappings should be /// specified to map logging levels to colors. For example: /// </para> /// <code lang="XML" escaped="true"> /// <mapping> /// <level value="ERROR" /> /// <foreColor value="DarkRed" /> /// <backColor value="White" /> /// </mapping> /// <mapping> /// <level value="WARN" /> /// <foreColor value="Yellow" /> /// </mapping> /// <mapping> /// <level value="INFO" /> /// <foreColor value="White" /> /// </mapping> /// <mapping> /// <level value="DEBUG" /> /// <foreColor value="Blue" /> /// </mapping> /// </code> /// <para> /// The Level is the standard log4net logging level while /// ForeColor and BackColor are the values of <see cref="System.ConsoleColor"/> /// enumeration. /// </para> /// <para> /// Based on the ColoredConsoleAppender /// </para> /// </remarks> /// <author>Rick Hobbs</author> /// <author>Nicko Cadell</author> /// <author>Pavlos Touboulidis</author> public class ManagedColoredConsoleAppender: AppenderSkeleton { /// <summary> /// Initializes a new instance of the <see cref="ManagedColoredConsoleAppender" /> class. /// </summary> /// <remarks> /// The instance of the <see cref="ManagedColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> public ManagedColoredConsoleAppender() { } #region Public Instance Properties /// <summary> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </summary> /// <value> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </value> /// <remarks> /// <para> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </para> /// </remarks> virtual public string Target { get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; } set { string v = value.Trim(); if (string.Compare(ConsoleError, v, true, CultureInfo.InvariantCulture) == 0) { m_writeToErrorStream = true; } else { m_writeToErrorStream = false; } } } /// <summary> /// Add a mapping of level to color - done by the config file /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Add a <see cref="LevelColors"/> mapping to this appender. /// Each mapping defines the foreground and background colors /// for a level. /// </para> /// </remarks> public void AddMapping(LevelColors mapping) { m_levelMapping.Add(mapping); } #endregion // Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(log4net.Core.LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to the console. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> override protected void Append(log4net.Core.LoggingEvent loggingEvent) { System.IO.TextWriter writer; if (m_writeToErrorStream) writer = Console.Error; else writer = Console.Out; // Reset color Console.ResetColor(); // see if there is a specified lookup LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; if (levelColors != null) { // if the backColor has been explicitly set if (levelColors.HasBackColor) Console.BackgroundColor = levelColors.BackColor; // if the foreColor has been explicitly set if (levelColors.HasForeColor) Console.ForegroundColor = levelColors.ForeColor; } // Render the event to a string string strLoggingMessage = RenderLoggingEvent(loggingEvent); // and write it writer.Write(strLoggingMessage); // Reset color again Console.ResetColor(); } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } /// <summary> /// Initialize the options for this appender /// </summary> /// <remarks> /// <para> /// Initialize the level to color mappings set on this appender. /// </para> /// </remarks> public override void ActivateOptions() { base.ActivateOptions(); m_levelMapping.ActivateOptions(); } #endregion // Override implementation of AppenderSkeleton #region Public Static Fields /// <summary> /// The <see cref="ManagedColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </summary> /// <remarks> /// <para> /// The <see cref="ManagedColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </para> /// </remarks> public const string ConsoleOut = "Console.Out"; /// <summary> /// The <see cref="ManagedColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </summary> /// <remarks> /// <para> /// The <see cref="ManagedColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </para> /// </remarks> public const string ConsoleError = "Console.Error"; #endregion // Public Static Fields #region Private Instances Fields /// <summary> /// Flag to write output to the error stream rather than the standard output stream /// </summary> private bool m_writeToErrorStream = false; /// <summary> /// Mapping from level object to color value /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); #endregion // Private Instances Fields #region LevelColors LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the color it should be displayed as. /// </summary> /// <remarks> /// <para> /// Defines the mapping between a level and the color it should be displayed in. /// </para> /// </remarks> public class LevelColors : LevelMappingEntry { /// <summary> /// The mapped foreground color for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped foreground color for the specified level. /// </para> /// </remarks> public ConsoleColor ForeColor { get { return (this.foreColor); } // Keep a flag that the color has been set // and is no longer the default. set { this.foreColor = value; this.hasForeColor = true; } } private ConsoleColor foreColor; private bool hasForeColor; internal bool HasForeColor { get { return hasForeColor; } } /// <summary> /// The mapped background color for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped background color for the specified level. /// </para> /// </remarks> public ConsoleColor BackColor { get { return (this.backColor); } // Keep a flag that the color has been set // and is no longer the default. set { this.backColor = value; this.hasBackColor = true; } } private ConsoleColor backColor; private bool hasBackColor; internal bool HasBackColor { get { return hasBackColor; } } } #endregion // LevelColors LevelMapping Entry } } #endif #endif #endif // !MONO_1_0 #endif // !CLI_1_0 #endif // !SSCLI #endif // !NETCF #endif // !NETMF
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void XorInt16() { var test = new SimpleBinaryOpTest__XorInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__XorInt16 testClass) { var result = Sse2.Xor(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__XorInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__XorInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__XorInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Xor( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Xor( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pClsVar1)), Sse2.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Xor(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__XorInt16(); var result = Sse2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__XorInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Xor( Sse2.LoadVector128((Int16*)(&test._fld1)), Sse2.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] ^ right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] ^ right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // IndexedSelectQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// A variant of the Select operator that supplies element index while performing the /// projection operation. This requires cooperation with partitioning and merging to /// guarantee ordering is preserved. /// /// </summary> /// <typeparam name="TInput"></typeparam> /// <typeparam name="TOutput"></typeparam> internal sealed class IndexedSelectQueryOperator<TInput, TOutput> : UnaryQueryOperator<TInput, TOutput> { // Selector function. Used to project elements to a transformed view during execution. private readonly Func<TInput, int, TOutput> _selector; private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private bool _limitsParallelism = false; // Whether this operator limits parallelism //--------------------------------------------------------------------------------------- // Initializes a new select operator. // // Arguments: // child - the child operator or data source from which to pull data // selector - a delegate representing the selector function // // Assumptions: // selector must be non null. // internal IndexedSelectQueryOperator(IEnumerable<TInput> child, Func<TInput, int, TOutput> selector) : base(child) { Contract.Assert(child != null, "child data source cannot be null"); Contract.Assert(selector != null, "need a selector function"); _selector = selector; // In an indexed Select, elements must be returned in the order in which // indices were assigned. _outputOrdered = true; InitOrdinalIndexState(); } private void InitOrdinalIndexState() { OrdinalIndexState childIndexState = Child.OrdinalIndexState; OrdinalIndexState indexState = childIndexState; if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct)) { _prematureMerge = true; _limitsParallelism = childIndexState != OrdinalIndexState.Shuffled; indexState = OrdinalIndexState.Correct; } Contract.Assert(!ExchangeUtilities.IsWorseThan(indexState, OrdinalIndexState.Correct)); SetOrdinalIndexState(indexState); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TOutput> Open( QuerySettings settings, bool preferStriping) { QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping); return IndexedSelectQueryOperatorResults.NewResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<TOutput> recipient, bool preferStriping, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // If the index is not correct, we need to reindex. PartitionedStream<TInput, int> inputStreamInt; if (_prematureMerge) { ListQueryResults<TInput> listResults = QueryOperator<TInput>.ExecuteAndCollectResults( inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings); inputStreamInt = listResults.GetPartitionedStream(); } else { Contract.Assert(typeof(TKey) == typeof(int)); inputStreamInt = (PartitionedStream<TInput, int>)(object)inputStream; } // Since the index is correct, the type of the index must be int PartitionedStream<TOutput, int> outputStream = new PartitionedStream<TOutput, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new IndexedSelectQueryOperatorEnumerator(inputStreamInt[i], _selector); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for projecting elements as it is walked. // class IndexedSelectQueryOperatorEnumerator : QueryOperatorEnumerator<TOutput, int> { private readonly QueryOperatorEnumerator<TInput, int> _source; // The data source to enumerate. private readonly Func<TInput, int, TOutput> _selector; // The actual select function. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal IndexedSelectQueryOperatorEnumerator(QueryOperatorEnumerator<TInput, int> source, Func<TInput, int, TOutput> selector) { Contract.Assert(source != null); Contract.Assert(selector != null); _source = source; _selector = selector; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TOutput currentElement, ref int currentKey) { // So long as the source has a next element, we have an element. TInput element = default(TInput); if (_source.MoveNext(ref element, ref currentKey)) { Contract.Assert(_selector != null, "expected a compiled selection function"); currentElement = _selector(element, currentKey); return true; } return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token) { return Child.AsSequentialQuery(token).Select(_selector); } //----------------------------------------------------------------------------------- // Query results for an indexed Select operator. The results are indexible if the child // results were indexible. // class IndexedSelectQueryOperatorResults : UnaryQueryOperatorResults { private IndexedSelectQueryOperator<TInput, TOutput> _selectOp; // Operator that generated the results private int _childCount; // The number of elements in child results public static QueryResults<TOutput> NewResults( QueryResults<TInput> childQueryResults, IndexedSelectQueryOperator<TInput, TOutput> op, QuerySettings settings, bool preferStriping) { if (childQueryResults.IsIndexible) { return new IndexedSelectQueryOperatorResults( childQueryResults, op, settings, preferStriping); } else { return new UnaryQueryOperatorResults( childQueryResults, op, settings, preferStriping); } } private IndexedSelectQueryOperatorResults( QueryResults<TInput> childQueryResults, IndexedSelectQueryOperator<TInput, TOutput> op, QuerySettings settings, bool preferStriping) : base(childQueryResults, op, settings, preferStriping) { _selectOp = op; Contract.Assert(_childQueryResults.IsIndexible); _childCount = _childQueryResults.ElementsCount; } internal override int ElementsCount { get { Contract.Assert(_childCount >= 0); return _childQueryResults.ElementsCount; } } internal override bool IsIndexible { get { return true; } } internal override TOutput GetElement(int index) { return _selectOp._selector(_childQueryResults.GetElement(index), index); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; namespace System.Numerics { /// <summary> /// A structure encapsulating a four-dimensional vector (x,y,z,w), /// which is used to efficiently rotate an object about the (x,y,z) vector by the angle theta, where w = cos(theta/2). /// </summary> public struct Quaternion : IEquatable<Quaternion> { /// <summary> /// Specifies the X-value of the vector component of the Quaternion. /// </summary> public float X; /// <summary> /// Specifies the Y-value of the vector component of the Quaternion. /// </summary> public float Y; /// <summary> /// Specifies the Z-value of the vector component of the Quaternion. /// </summary> public float Z; /// <summary> /// Specifies the rotation component of the Quaternion. /// </summary> public float W; /// <summary> /// Returns a Quaternion representing no rotation. /// </summary> public static Quaternion Identity { get { return new Quaternion(0, 0, 0, 1); } } /// <summary> /// Returns whether the Quaternion is the identity Quaternion. /// </summary> public bool IsIdentity { get { return X == 0f && Y == 0f && Z == 0f && W == 1f; } } /// <summary> /// Constructs a Quaternion from the given components. /// </summary> /// <param name="x">The X component of the Quaternion.</param> /// <param name="y">The Y component of the Quaternion.</param> /// <param name="z">The Z component of the Quaternion.</param> /// <param name="w">The W component of the Quaternion.</param> public Quaternion(float x, float y, float z, float w) { this.X = x; this.Y = y; this.Z = z; this.W = w; } /// <summary> /// Constructs a Quaternion from the given vector and rotation parts. /// </summary> /// <param name="vectorPart">The vector part of the Quaternion.</param> /// <param name="scalarPart">The rotation part of the Quaternion.</param> public Quaternion(Vector3 vectorPart, float scalarPart) { X = vectorPart.X; Y = vectorPart.Y; Z = vectorPart.Z; W = scalarPart; } /// <summary> /// Calculates the length of the Quaternion. /// </summary> /// <returns>The computed length of the Quaternion.</returns> public float Length() { float ls = X * X + Y * Y + Z * Z + W * W; return (float)Math.Sqrt((double)ls); } /// <summary> /// Calculates the length squared of the Quaternion. This operation is cheaper than Length(). /// </summary> /// <returns>The length squared of the Quaternion.</returns> public float LengthSquared() { return X * X + Y * Y + Z * Z + W * W; } /// <summary> /// Divides each component of the Quaternion by the length of the Quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The normalized Quaternion.</returns> public static Quaternion Normalize(Quaternion value) { Quaternion ans; float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float invNorm = 1.0f / (float)Math.Sqrt((double)ls); ans.X = value.X * invNorm; ans.Y = value.Y * invNorm; ans.Z = value.Z * invNorm; ans.W = value.W * invNorm; return ans; } /// <summary> /// Creates the conjugate of a specified Quaternion. /// </summary> /// <param name="value">The Quaternion of which to return the conjugate.</param> /// <returns>A new Quaternion that is the conjugate of the specified one.</returns> public static Quaternion Conjugate(Quaternion value) { Quaternion ans; ans.X = -value.X; ans.Y = -value.Y; ans.Z = -value.Z; ans.W = value.W; return ans; } /// <summary> /// Returns the inverse of a Quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The inverted Quaternion.</returns> public static Quaternion Inverse(Quaternion value) { // -1 ( a -v ) // q = ( ------------- ------------- ) // ( a^2 + |v|^2 , a^2 + |v|^2 ) Quaternion ans; float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float invNorm = 1.0f / ls; ans.X = -value.X * invNorm; ans.Y = -value.Y * invNorm; ans.Z = -value.Z * invNorm; ans.W = value.W * invNorm; return ans; } /// <summary> /// Creates a Quaternion from a vector and an angle to rotate about the vector. /// </summary> /// <param name="axis">The vector to rotate around.</param> /// <param name="angle">The angle, in radians, to rotate around the vector.</param> /// <returns>The created Quaternion.</returns> public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) { Quaternion ans; float halfAngle = angle * 0.5f; float s = (float)Math.Sin(halfAngle); float c = (float)Math.Cos(halfAngle); ans.X = axis.X * s; ans.Y = axis.Y * s; ans.Z = axis.Z * s; ans.W = c; return ans; } /// <summary> /// Creates a new Quaternion from the given yaw, pitch, and roll, in radians. /// </summary> /// <param name="yaw">The yaw angle, in radians, around the Y-axis.</param> /// <param name="pitch">The pitch angle, in radians, around the X-axis.</param> /// <param name="roll">The roll angle, in radians, around the Z-axis.</param> /// <returns></returns> public static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll) { // Roll first, about axis the object is facing, then // pitch upward, then yaw to face into the new heading float sr, cr, sp, cp, sy, cy; float halfRoll = roll * 0.5f; sr = (float)Math.Sin(halfRoll); cr = (float)Math.Cos(halfRoll); float halfPitch = pitch * 0.5f; sp = (float)Math.Sin(halfPitch); cp = (float)Math.Cos(halfPitch); float halfYaw = yaw * 0.5f; sy = (float)Math.Sin(halfYaw); cy = (float)Math.Cos(halfYaw); Quaternion result; result.X = cy * sp * cr + sy * cp * sr; result.Y = sy * cp * cr - cy * sp * sr; result.Z = cy * cp * sr - sy * sp * cr; result.W = cy * cp * cr + sy * sp * sr; return result; } /// <summary> /// Creates a Quaternion from the given rotation matrix. /// </summary> /// <param name="matrix">The rotation matrix.</param> /// <returns>The created Quaternion.</returns> public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix) { float trace = matrix.M11 + matrix.M22 + matrix.M33; Quaternion q = new Quaternion(); if (trace > 0.0f) { float s = (float)Math.Sqrt(trace + 1.0f); q.W = s * 0.5f; s = 0.5f / s; q.X = (matrix.M23 - matrix.M32) * s; q.Y = (matrix.M31 - matrix.M13) * s; q.Z = (matrix.M12 - matrix.M21) * s; } else { if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33) { float s = (float)Math.Sqrt(1.0f + matrix.M11 - matrix.M22 - matrix.M33); float invS = 0.5f / s; q.X = 0.5f * s; q.Y = (matrix.M12 + matrix.M21) * invS; q.Z = (matrix.M13 + matrix.M31) * invS; q.W = (matrix.M23 - matrix.M32) * invS; } else if (matrix.M22 > matrix.M33) { float s = (float)Math.Sqrt(1.0f + matrix.M22 - matrix.M11 - matrix.M33); float invS = 0.5f / s; q.X = (matrix.M21 + matrix.M12) * invS; q.Y = 0.5f * s; q.Z = (matrix.M32 + matrix.M23) * invS; q.W = (matrix.M31 - matrix.M13) * invS; } else { float s = (float)Math.Sqrt(1.0f + matrix.M33 - matrix.M11 - matrix.M22); float invS = 0.5f / s; q.X = (matrix.M31 + matrix.M13) * invS; q.Y = (matrix.M32 + matrix.M23) * invS; q.Z = 0.5f * s; q.W = (matrix.M12 - matrix.M21) * invS; } } return q; } /// <summary> /// Calculates the dot product of two Quaternions. /// </summary> /// <param name="quaternion1">The first source Quaternion.</param> /// <param name="quaternion2">The second source Quaternion.</param> /// <returns>The dot product of the Quaternions.</returns> public static float Dot(Quaternion quaternion1, Quaternion quaternion2) { return quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; } /// <summary> /// Interpolates between two quaternions, using spherical linear interpolation. /// </summary> /// <param name="quaternion1">The first source Quaternion.</param> /// <param name="quaternion2">The second source Quaternion.</param> /// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param> /// <returns>The interpolated Quaternion.</returns> public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { const float epsilon = 1e-6f; float t = amount; float cosOmega = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; bool flip = false; if (cosOmega < 0.0f) { flip = true; cosOmega = -cosOmega; } float s1, s2; if (cosOmega > (1.0f - epsilon)) { // Too close, do straight linear interpolation. s1 = 1.0f - t; s2 = (flip) ? -t : t; } else { float omega = (float)Math.Acos(cosOmega); float invSinOmega = (float)(1 / Math.Sin(omega)); s1 = (float)Math.Sin((1.0f - t) * omega) * invSinOmega; s2 = (flip) ? (float)-Math.Sin(t * omega) * invSinOmega : (float)Math.Sin(t * omega) * invSinOmega; } Quaternion ans; ans.X = s1 * quaternion1.X + s2 * quaternion2.X; ans.Y = s1 * quaternion1.Y + s2 * quaternion2.Y; ans.Z = s1 * quaternion1.Z + s2 * quaternion2.Z; ans.W = s1 * quaternion1.W + s2 * quaternion2.W; return ans; } /// <summary> /// Linearly interpolates between two quaternions. /// </summary> /// <param name="quaternion1">The first source Quaternion.</param> /// <param name="quaternion2">The second source Quaternion.</param> /// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param> /// <returns>The interpolated Quaternion.</returns> public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { float t = amount; float t1 = 1.0f - t; Quaternion r = new Quaternion(); float dot = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; if (dot >= 0.0f) { r.X = t1 * quaternion1.X + t * quaternion2.X; r.Y = t1 * quaternion1.Y + t * quaternion2.Y; r.Z = t1 * quaternion1.Z + t * quaternion2.Z; r.W = t1 * quaternion1.W + t * quaternion2.W; } else { r.X = t1 * quaternion1.X - t * quaternion2.X; r.Y = t1 * quaternion1.Y - t * quaternion2.Y; r.Z = t1 * quaternion1.Z - t * quaternion2.Z; r.W = t1 * quaternion1.W - t * quaternion2.W; } // Normalize it. float ls = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W; float invNorm = 1.0f / (float)Math.Sqrt((double)ls); r.X *= invNorm; r.Y *= invNorm; r.Z *= invNorm; r.W *= invNorm; return r; } /// <summary> /// Concatenates two Quaternions; the result represents the value1 rotation followed by the value2 rotation. /// </summary> /// <param name="value1">The first Quaternion rotation in the series.</param> /// <param name="value2">The second Quaternion rotation in the series.</param> /// <returns>A new Quaternion representing the concatenation of the value1 rotation followed by the value2 rotation.</returns> public static Quaternion Concatenate(Quaternion value1, Quaternion value2) { Quaternion ans; // Concatenate rotation is actually q2 * q1 instead of q1 * q2. // So that's why value2 goes q1 and value1 goes q2. float q1x = value2.X; float q1y = value2.Y; float q1z = value2.Z; float q1w = value2.W; float q2x = value1.X; float q2y = value1.Y; float q2z = value1.Z; float q2w = value1.W; // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Flips the sign of each component of the quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The negated Quaternion.</returns> public static Quaternion Negate(Quaternion value) { Quaternion ans; ans.X = -value.X; ans.Y = -value.Y; ans.Z = -value.Z; ans.W = -value.W; return ans; } /// <summary> /// Adds two Quaternions element-by-element. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second source Quaternion.</param> /// <returns>The result of adding the Quaternions.</returns> public static Quaternion Add(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X + value2.X; ans.Y = value1.Y + value2.Y; ans.Z = value1.Z + value2.Z; ans.W = value1.W + value2.W; return ans; } /// <summary> /// Subtracts one Quaternion from another. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second Quaternion, to be subtracted from the first.</param> /// <returns>The result of the subtraction.</returns> public static Quaternion Subtract(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X - value2.X; ans.Y = value1.Y - value2.Y; ans.Z = value1.Z - value2.Z; ans.W = value1.W - value2.W; return ans; } /// <summary> /// Multiplies two Quaternions together. /// </summary> /// <param name="value1">The Quaternion on the left side of the multiplication.</param> /// <param name="value2">The Quaternion on the right side of the multiplication.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion Multiply(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; float q2x = value2.X; float q2y = value2.Y; float q2z = value2.Z; float q2w = value2.W; // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Multiplies a Quaternion by a scalar value. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The scalar value.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion Multiply(Quaternion value1, float value2) { Quaternion ans; ans.X = value1.X * value2; ans.Y = value1.Y * value2; ans.Z = value1.Z * value2; ans.W = value1.W * value2; return ans; } /// <summary> /// Divides a Quaternion by another Quaternion. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The divisor.</param> /// <returns>The result of the division.</returns> public static Quaternion Divide(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; //------------------------------------- // Inverse part. float ls = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float invNorm = 1.0f / ls; float q2x = -value2.X * invNorm; float q2y = -value2.Y * invNorm; float q2z = -value2.Z * invNorm; float q2w = value2.W * invNorm; //------------------------------------- // Multiply part. // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Flips the sign of each component of the quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The negated Quaternion.</returns> public static Quaternion operator -(Quaternion value) { Quaternion ans; ans.X = -value.X; ans.Y = -value.Y; ans.Z = -value.Z; ans.W = -value.W; return ans; } /// <summary> /// Adds two Quaternions element-by-element. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second source Quaternion.</param> /// <returns>The result of adding the Quaternions.</returns> public static Quaternion operator +(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X + value2.X; ans.Y = value1.Y + value2.Y; ans.Z = value1.Z + value2.Z; ans.W = value1.W + value2.W; return ans; } /// <summary> /// Subtracts one Quaternion from another. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second Quaternion, to be subtracted from the first.</param> /// <returns>The result of the subtraction.</returns> public static Quaternion operator -(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X - value2.X; ans.Y = value1.Y - value2.Y; ans.Z = value1.Z - value2.Z; ans.W = value1.W - value2.W; return ans; } /// <summary> /// Multiplies two Quaternions together. /// </summary> /// <param name="value1">The Quaternion on the left side of the multiplication.</param> /// <param name="value2">The Quaternion on the right side of the multiplication.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion operator *(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; float q2x = value2.X; float q2y = value2.Y; float q2z = value2.Z; float q2w = value2.W; // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Multiplies a Quaternion by a scalar value. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The scalar value.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion operator *(Quaternion value1, float value2) { Quaternion ans; ans.X = value1.X * value2; ans.Y = value1.Y * value2; ans.Z = value1.Z * value2; ans.W = value1.W * value2; return ans; } /// <summary> /// Divides a Quaternion by another Quaternion. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The divisor.</param> /// <returns>The result of the division.</returns> public static Quaternion operator /(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; //------------------------------------- // Inverse part. float ls = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float invNorm = 1.0f / ls; float q2x = -value2.X * invNorm; float q2y = -value2.Y * invNorm; float q2z = -value2.Z * invNorm; float q2w = value2.W * invNorm; //------------------------------------- // Multiply part. // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Returns a boolean indicating whether the two given Quaternions are equal. /// </summary> /// <param name="value1">The first Quaternion to compare.</param> /// <param name="value2">The second Quaternion to compare.</param> /// <returns>True if the Quaternions are equal; False otherwise.</returns> public static bool operator ==(Quaternion value1, Quaternion value2) { return (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z && value1.W == value2.W); } /// <summary> /// Returns a boolean indicating whether the two given Quaternions are not equal. /// </summary> /// <param name="value1">The first Quaternion to compare.</param> /// <param name="value2">The second Quaternion to compare.</param> /// <returns>True if the Quaternions are not equal; False if they are equal.</returns> public static bool operator !=(Quaternion value1, Quaternion value2) { return (value1.X != value2.X || value1.Y != value2.Y || value1.Z != value2.Z || value1.W != value2.W); } /// <summary> /// Returns a boolean indicating whether the given Quaternion is equal to this Quaternion instance. /// </summary> /// <param name="other">The Quaternion to compare this instance to.</param> /// <returns>True if the other Quaternion is equal to this instance; False otherwise.</returns> public bool Equals(Quaternion other) { return (X == other.X && Y == other.Y && Z == other.Z && W == other.W); } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Quaternion instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Quaternion; False otherwise.</returns> public override bool Equals(object obj) { if (obj is Quaternion) { return Equals((Quaternion)obj); } return false; } /// <summary> /// Returns a String representing this Quaternion instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { CultureInfo ci = CultureInfo.CurrentCulture; return String.Format(ci, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X.ToString(ci), Y.ToString(ci), Z.ToString(ci), W.ToString(ci)); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode(); } } }
// 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 gcoc = Google.Cloud.OsLogin.Common; using sys = System; namespace Google.Cloud.OsLogin.Common { /// <summary>Resource name for the <c>PosixAccount</c> resource.</summary> public sealed partial class PosixAccountName : gax::IResourceName, sys::IEquatable<PosixAccountName> { /// <summary>The possible contents of <see cref="PosixAccountName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>users/{user}/projects/{project}</c>.</summary> UserProject = 1, } private static gax::PathTemplate s_userProject = new gax::PathTemplate("users/{user}/projects/{project}"); /// <summary>Creates a <see cref="PosixAccountName"/> 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="PosixAccountName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static PosixAccountName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new PosixAccountName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="PosixAccountName"/> with the pattern <c>users/{user}/projects/{project}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PosixAccountName"/> constructed from the provided ids.</returns> public static PosixAccountName FromUserProject(string userId, string projectId) => new PosixAccountName(ResourceNameType.UserProject, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PosixAccountName"/> with pattern /// <c>users/{user}/projects/{project}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PosixAccountName"/> with pattern /// <c>users/{user}/projects/{project}</c>. /// </returns> public static string Format(string userId, string projectId) => FormatUserProject(userId, projectId); /// <summary> /// Formats the IDs into the string representation of this <see cref="PosixAccountName"/> with pattern /// <c>users/{user}/projects/{project}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PosixAccountName"/> with pattern /// <c>users/{user}/projects/{project}</c>. /// </returns> public static string FormatUserProject(string userId, string projectId) => s_userProject.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId))); /// <summary>Parses the given resource name string into a new <see cref="PosixAccountName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>users/{user}/projects/{project}</c></description></item></list> /// </remarks> /// <param name="posixAccountName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="PosixAccountName"/> if successful.</returns> public static PosixAccountName Parse(string posixAccountName) => Parse(posixAccountName, false); /// <summary> /// Parses the given resource name string into a new <see cref="PosixAccountName"/> 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>users/{user}/projects/{project}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="posixAccountName">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="PosixAccountName"/> if successful.</returns> public static PosixAccountName Parse(string posixAccountName, bool allowUnparsed) => TryParse(posixAccountName, allowUnparsed, out PosixAccountName 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="PosixAccountName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>users/{user}/projects/{project}</c></description></item></list> /// </remarks> /// <param name="posixAccountName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="PosixAccountName"/>, 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 posixAccountName, out PosixAccountName result) => TryParse(posixAccountName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PosixAccountName"/> 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>users/{user}/projects/{project}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="posixAccountName">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="PosixAccountName"/>, 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 posixAccountName, bool allowUnparsed, out PosixAccountName result) { gax::GaxPreconditions.CheckNotNull(posixAccountName, nameof(posixAccountName)); gax::TemplatedResourceName resourceName; if (s_userProject.TryParseName(posixAccountName, out resourceName)) { result = FromUserProject(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(posixAccountName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private PosixAccountName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string userId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; UserId = userId; } /// <summary> /// Constructs a new instance of a <see cref="PosixAccountName"/> class from the component parts of pattern /// <c>users/{user}/projects/{project}</c> /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> public PosixAccountName(string userId, string projectId) : this(ResourceNameType.UserProject, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId))) { } /// <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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string UserId { 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.UserProject: return s_userProject.Expand(UserId, ProjectId); 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 PosixAccountName); /// <inheritdoc/> public bool Equals(PosixAccountName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(PosixAccountName a, PosixAccountName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(PosixAccountName a, PosixAccountName b) => !(a == b); } /// <summary>Resource name for the <c>SshPublicKey</c> resource.</summary> public sealed partial class SshPublicKeyName : gax::IResourceName, sys::IEquatable<SshPublicKeyName> { /// <summary>The possible contents of <see cref="SshPublicKeyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>users/{user}/sshPublicKeys/{fingerprint}</c>.</summary> UserFingerprint = 1, } private static gax::PathTemplate s_userFingerprint = new gax::PathTemplate("users/{user}/sshPublicKeys/{fingerprint}"); /// <summary>Creates a <see cref="SshPublicKeyName"/> 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="SshPublicKeyName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static SshPublicKeyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SshPublicKeyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SshPublicKeyName"/> with the pattern <c>users/{user}/sshPublicKeys/{fingerprint}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SshPublicKeyName"/> constructed from the provided ids.</returns> public static SshPublicKeyName FromUserFingerprint(string userId, string fingerprintId) => new SshPublicKeyName(ResourceNameType.UserFingerprint, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), fingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(fingerprintId, nameof(fingerprintId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SshPublicKeyName"/> with pattern /// <c>users/{user}/sshPublicKeys/{fingerprint}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SshPublicKeyName"/> with pattern /// <c>users/{user}/sshPublicKeys/{fingerprint}</c>. /// </returns> public static string Format(string userId, string fingerprintId) => FormatUserFingerprint(userId, fingerprintId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SshPublicKeyName"/> with pattern /// <c>users/{user}/sshPublicKeys/{fingerprint}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SshPublicKeyName"/> with pattern /// <c>users/{user}/sshPublicKeys/{fingerprint}</c>. /// </returns> public static string FormatUserFingerprint(string userId, string fingerprintId) => s_userFingerprint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(fingerprintId, nameof(fingerprintId))); /// <summary>Parses the given resource name string into a new <see cref="SshPublicKeyName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>users/{user}/sshPublicKeys/{fingerprint}</c></description></item> /// </list> /// </remarks> /// <param name="sshPublicKeyName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SshPublicKeyName"/> if successful.</returns> public static SshPublicKeyName Parse(string sshPublicKeyName) => Parse(sshPublicKeyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SshPublicKeyName"/> 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>users/{user}/sshPublicKeys/{fingerprint}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sshPublicKeyName">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="SshPublicKeyName"/> if successful.</returns> public static SshPublicKeyName Parse(string sshPublicKeyName, bool allowUnparsed) => TryParse(sshPublicKeyName, allowUnparsed, out SshPublicKeyName 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="SshPublicKeyName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>users/{user}/sshPublicKeys/{fingerprint}</c></description></item> /// </list> /// </remarks> /// <param name="sshPublicKeyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SshPublicKeyName"/>, 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 sshPublicKeyName, out SshPublicKeyName result) => TryParse(sshPublicKeyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SshPublicKeyName"/> 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>users/{user}/sshPublicKeys/{fingerprint}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sshPublicKeyName">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="SshPublicKeyName"/>, 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 sshPublicKeyName, bool allowUnparsed, out SshPublicKeyName result) { gax::GaxPreconditions.CheckNotNull(sshPublicKeyName, nameof(sshPublicKeyName)); gax::TemplatedResourceName resourceName; if (s_userFingerprint.TryParseName(sshPublicKeyName, out resourceName)) { result = FromUserFingerprint(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(sshPublicKeyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SshPublicKeyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string fingerprintId = null, string userId = null) { Type = type; UnparsedResource = unparsedResourceName; FingerprintId = fingerprintId; UserId = userId; } /// <summary> /// Constructs a new instance of a <see cref="SshPublicKeyName"/> class from the component parts of pattern /// <c>users/{user}/sshPublicKeys/{fingerprint}</c> /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fingerprintId">The <c>Fingerprint</c> ID. Must not be <c>null</c> or empty.</param> public SshPublicKeyName(string userId, string fingerprintId) : this(ResourceNameType.UserFingerprint, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), fingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(fingerprintId, nameof(fingerprintId))) { } /// <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>Fingerprint</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FingerprintId { get; } /// <summary> /// The <c>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string UserId { 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.UserFingerprint: return s_userFingerprint.Expand(UserId, FingerprintId); 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 SshPublicKeyName); /// <inheritdoc/> public bool Equals(SshPublicKeyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SshPublicKeyName a, SshPublicKeyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SshPublicKeyName a, SshPublicKeyName b) => !(a == b); } /// <summary>Resource name for the <c>User</c> resource.</summary> public sealed partial class UserName : gax::IResourceName, sys::IEquatable<UserName> { /// <summary>The possible contents of <see cref="UserName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>users/{user}</c>.</summary> User = 1, } private static gax::PathTemplate s_user = new gax::PathTemplate("users/{user}"); /// <summary>Creates a <see cref="UserName"/> 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="UserName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static UserName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new UserName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary>Creates a <see cref="UserName"/> with the pattern <c>users/{user}</c>.</summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="UserName"/> constructed from the provided ids.</returns> public static UserName FromUser(string userId) => new UserName(ResourceNameType.User, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c> /// . /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c>. /// </returns> public static string Format(string userId) => FormatUser(userId); /// <summary> /// Formats the IDs into the string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c> /// . /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="UserName"/> with pattern <c>users/{user}</c>. /// </returns> public static string FormatUser(string userId) => s_user.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId))); /// <summary>Parses the given resource name string into a new <see cref="UserName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>users/{user}</c></description></item></list> /// </remarks> /// <param name="userName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="UserName"/> if successful.</returns> public static UserName Parse(string userName) => Parse(userName, false); /// <summary> /// Parses the given resource name string into a new <see cref="UserName"/> 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>users/{user}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="userName">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="UserName"/> if successful.</returns> public static UserName Parse(string userName, bool allowUnparsed) => TryParse(userName, allowUnparsed, out UserName 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="UserName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>users/{user}</c></description></item></list> /// </remarks> /// <param name="userName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="UserName"/>, 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 userName, out UserName result) => TryParse(userName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="UserName"/> 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>users/{user}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="userName">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="UserName"/>, 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 userName, bool allowUnparsed, out UserName result) { gax::GaxPreconditions.CheckNotNull(userName, nameof(userName)); gax::TemplatedResourceName resourceName; if (s_user.TryParseName(userName, out resourceName)) { result = FromUser(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(userName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private UserName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string userId = null) { Type = type; UnparsedResource = unparsedResourceName; UserId = userId; } /// <summary> /// Constructs a new instance of a <see cref="UserName"/> class from the component parts of pattern /// <c>users/{user}</c> /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> public UserName(string userId) : this(ResourceNameType.User, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId))) { } /// <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>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string UserId { 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.User: return s_user.Expand(UserId); 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 UserName); /// <inheritdoc/> public bool Equals(UserName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(UserName a, UserName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(UserName a, UserName b) => !(a == b); } public partial class PosixAccount { /// <summary> /// <see cref="gcoc::PosixAccountName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcoc::PosixAccountName PosixAccountName { get => string.IsNullOrEmpty(Name) ? null : gcoc::PosixAccountName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class SshPublicKey { /// <summary> /// <see cref="gcoc::SshPublicKeyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcoc::SshPublicKeyName SshPublicKeyName { get => string.IsNullOrEmpty(Name) ? null : gcoc::SshPublicKeyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using FlatRedBall; using FlatRedBall.Math; using FlatRedBall.Utilities; using Microsoft.Xna.Framework; namespace FlatRedBall.AI.Pathfinding { #region Enums public enum AStarState { Unused, Open, Closed } #endregion /// <summary> /// An object which has position properties /// </summary> public class PositionedNode : IStaticPositionable, INameable { #region Fields string mName; public Vector3 Position; // made internal for speed boosts protected internal List<Link> mLinks = new List<Link>(); public int PropertyField; public AStarState AStarState; #region XML Docs /// <summary> /// The node that links to this node. This is reset every time the /// containing NodeNetwork searches for a path. /// </summary> #endregion protected internal PositionedNode mParentNode; #region XML Docs /// <summary> /// The cost to get to this node from the start node. This variable is /// set when the containing NodeNetwork searches for a path. /// </summary> #endregion protected internal float mCostToGetHere; /// <summary> /// Only active nodes are included in pathfinding and find node searches. /// </summary> /// Update February 10, 2013 /// Nodes should always start /// out as active. private bool mActive = true; #endregion #region Properties /// <summary> /// Returns the cost to get to this node from the start node. This /// value is only accurate if the node is contained in list returned /// by the last call to NodeNetwork.GetPath. /// </summary> /// <remarks> /// This value is reset anytime GetPath is called on the containing NodeNetwork. /// </remarks> public float CostToGetHere { get { return mCostToGetHere; } } /// <summary> /// The Node's name. Mainly used for saving NodeNetworks since saved Links reference /// PositionedNodes by name. /// </summary> public string Name { get { return mName; } set { mName = value; } } /// <summary> /// The X position of the PositionedNode. /// </summary> public float X { get { return Position.X; } set { Position.X = value ; } } /// <summary> /// The Y position of the PositionedNode. /// </summary> public float Y { get { return Position.Y; } set { Position.Y = value; ; } } /// <summary> /// The Z position of the PositionedNode. /// </summary> public float Z { get { return Position.Z; } set { Position.Z = value ; } } /// <summary> /// The links belonging to this PositionedNode. /// </summary> /// <remarks> /// This is a list of Links which reference the PositionedNodes that this links to. /// Links are one-way and PositionedNodes that this links to do not necessarily contain /// Links back to this. /// /// This list is provided for advanced scenarios, such as when when adding a subclassed Link. Otherwise /// use functions like LinkTo and LinkToOneWay /// </remarks> public List<Link> Links { get => mLinks; } /// <summary> /// Only active nodes are included in pathfinding and find node searches. /// </summary> public virtual bool Active { get { return mActive; } set { mActive = value; } } #endregion #region Methods #region XML Docs /// <summary> /// Creates a new PositionedNode. /// </summary> #endregion public PositionedNode() { } #region XML Docs /// <summary> /// Disconnects all Links between this and the argument node. /// </summary> /// <param name="node">The PositionedNode to break links between.</param> #endregion public void BreakLinkBetween(PositionedNode node) { for (int i = 0; i < node.mLinks.Count; i++) { if (node.mLinks[i].NodeLinkingTo == this) { node.mLinks.RemoveAt(i); break; } } for (int i = 0; i < mLinks.Count; i++) { if (mLinks[i].NodeLinkingTo == node) { mLinks.RemoveAt(i); break; } } } public PositionedNode Clone() { PositionedNode newNode = (PositionedNode)this.MemberwiseClone(); newNode.mLinks = new List<Link>(); newNode.mParentNode = null; newNode.mCostToGetHere = 0; return newNode; } public Link GetLinkTo(PositionedNode node) { foreach (Link link in mLinks) { if (link.NodeLinkingTo == node) { return link; } } return null; } #region XML Docs /// <summary> /// Returns whether this has a Link to the argument PositionedNode. /// </summary> /// <remarks> /// If this does not link to the argument PositionedNode, but the argument /// links back to this, the method will return false. It only checks links one-way. /// </remarks> /// <param name="node">The argument to test linking.</param> /// <returns>Whether this PositionedNode links to the argument node.</returns> #endregion public bool IsLinkedTo(PositionedNode node) { foreach (Link link in mLinks) { if (link.NodeLinkingTo == node) { return true; } } return false; } public void LinkTo(PositionedNode nodeToLinkTo) { float distanceToTravel = (Position - nodeToLinkTo.Position).Length(); LinkTo(nodeToLinkTo, distanceToTravel); } #region XML Docs /// <summary> /// Creates Links from this to the argument nodeToLinkTo, and another Link from the /// argument nodeToLinkTo back to this. /// </summary> /// <remarks> /// If either this or the argument nodeToLinkTo already contains a link to the other /// PositionedNode, then the cost of the link is set to the argument costTo. /// </remarks> /// <param name="nodeToLinkTo">The other PositionedNode to create Links between.</param> /// <param name="costTo">The cost to travel between this and the argument nodeToLinkTo.</param> #endregion public void LinkTo(PositionedNode nodeToLinkTo, float costTo) { LinkTo(nodeToLinkTo, costTo, costTo); } #region XML Docs /// <summary> /// Creates Links from this to the argument nodeToLinkTo, and another Link from the /// argument nodeToLinkTo back to this. /// </summary> /// <remarks> /// If either this or the argument nodeToLinkTo already contains a link to the other /// PositionedNode, then the cost of the link is set to the argument costTo or costFrom as appropriate. /// </remarks> /// <param name="nodeToLinkTo">The other PositionedNode to create the Links between.</param> /// <param name="costTo">The cost to travel from this to the argument nodeToLinkTo.</param> /// <param name="costFrom">The cost to travel from the nodeToLinkTo back to this.</param> #endregion public void LinkTo(PositionedNode nodeToLinkTo, float costTo, float costFrom) { #if DEBUG if (nodeToLinkTo == this) { throw new ArgumentException("Cannot have a node link to itself"); } #endif bool updated = false; for (int i = 0; i < mLinks.Count; i++) { if (mLinks[i].NodeLinkingTo == nodeToLinkTo) { mLinks[i].Cost = costTo; updated = true; break; } } if (!updated) { mLinks.Add(new Link(nodeToLinkTo, costTo)); } // Now do the same for the other node updated = false; for (int i = 0; i < nodeToLinkTo.mLinks.Count; i++) { if (nodeToLinkTo.mLinks[i].NodeLinkingTo == this) { nodeToLinkTo.mLinks[i].Cost = costFrom; updated = true; break; } } if (!updated) { nodeToLinkTo.mLinks.Add(new Link(this, costFrom)); } } #region XML Docs /// <summary> /// Creates a link from this PositionedNode to the argument nodeToLinkTo. Links /// on the argument nodeToLinkTo are not modified. /// </summary> /// <remarks> /// If this already links to the arugment nodeToLinkTo, the cost is set to the argument /// costTo. /// </remarks> /// <param name="nodeToLinkTo">The PositionedNode to create a link to.</param> /// <param name="costTo">The cost to travel from this to the argument nodeToLinkTo.</param> #endregion public void LinkToOneWay(PositionedNode nodeToLinkTo, float costTo) { foreach (Link link in mLinks) { if (link.NodeLinkingTo == nodeToLinkTo) { link.Cost = costTo; return; } } mLinks.Add(new Link(nodeToLinkTo, costTo)); } #region XML Docs /// <summary> /// Returns the string representation of this. /// </summary> /// <returns>The string representation of this.</returns> #endregion public override string ToString() { return mName + string.Format(" ({0},{1},{2})", X, Y, Z); } #endregion } public static class PositionedNodeListExtensionMethods { public static float PathDistanceSquared(this List<PositionedNode> path) { float total = 0; for (int i = 0; i < path.Count - 1; i++) { total += (path[i].Position - path[i + 1].Position).LengthSquared(); } return total; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmMonthEnd { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmMonthEnd() : base() { Load += frmMonthEnd_Load; KeyPress += frmMonthEnd_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.PictureBox Picture2; public System.Windows.Forms.GroupBox _frmMode_3; public System.Windows.Forms.Label _Label1_7; public System.Windows.Forms.Label _Label1_6; public System.Windows.Forms.GroupBox _frmMode_1; public System.Windows.Forms.Label _Label1_4; public System.Windows.Forms.Label _Label1_5; public System.Windows.Forms.GroupBox _frmMode_0; public System.Windows.Forms.Label _Label1_1; public System.Windows.Forms.Label _Label1_2; public System.Windows.Forms.GroupBox _frmMode_2; private System.Windows.Forms.Button withEventsField_cmdBack; public System.Windows.Forms.Button cmdBack { get { return withEventsField_cmdBack; } set { if (withEventsField_cmdBack != null) { withEventsField_cmdBack.Click -= cmdBack_Click; } withEventsField_cmdBack = value; if (withEventsField_cmdBack != null) { withEventsField_cmdBack.Click += cmdBack_Click; } } } private System.Windows.Forms.Button withEventsField_cmdNext; public System.Windows.Forms.Button cmdNext { get { return withEventsField_cmdNext; } set { if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click -= cmdNext_Click; } withEventsField_cmdNext = value; if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click += cmdNext_Click; } } } //Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents frmMode As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmMonthEnd)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this._frmMode_3 = new System.Windows.Forms.GroupBox(); this.Picture2 = new System.Windows.Forms.PictureBox(); this._frmMode_1 = new System.Windows.Forms.GroupBox(); this._Label1_7 = new System.Windows.Forms.Label(); this._Label1_6 = new System.Windows.Forms.Label(); this._frmMode_0 = new System.Windows.Forms.GroupBox(); this._Label1_4 = new System.Windows.Forms.Label(); this._Label1_5 = new System.Windows.Forms.Label(); this._frmMode_2 = new System.Windows.Forms.GroupBox(); this._Label1_1 = new System.Windows.Forms.Label(); this._Label1_2 = new System.Windows.Forms.Label(); this.cmdBack = new System.Windows.Forms.Button(); this.cmdNext = new System.Windows.Forms.Button(); //Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.frmMode = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components) this._frmMode_3.SuspendLayout(); this._frmMode_1.SuspendLayout(); this._frmMode_0.SuspendLayout(); this._frmMode_2.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.Label1, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.frmMode, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Text = "Month End Run"; this.ClientSize = new System.Drawing.Size(654, 497); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmMonthEnd"; this._frmMode_3.Text = "Month End Run Complete"; this._frmMode_3.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmMode_3.Size = new System.Drawing.Size(196, 256); this._frmMode_3.Location = new System.Drawing.Point(354, 147); this._frmMode_3.TabIndex = 3; this._frmMode_3.BackColor = System.Drawing.SystemColors.Control; this._frmMode_3.Enabled = true; this._frmMode_3.ForeColor = System.Drawing.SystemColors.ControlText; this._frmMode_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmMode_3.Visible = true; this._frmMode_3.Padding = new System.Windows.Forms.Padding(0); this._frmMode_3.Name = "_frmMode_3"; this.Picture2.Size = new System.Drawing.Size(140, 205); this.Picture2.Location = new System.Drawing.Point(27, 24); this.Picture2.Image = (System.Drawing.Image)resources.GetObject("Picture2.Image"); this.Picture2.TabIndex = 4; this.Picture2.Dock = System.Windows.Forms.DockStyle.None; this.Picture2.BackColor = System.Drawing.SystemColors.Control; this.Picture2.CausesValidation = true; this.Picture2.Enabled = true; this.Picture2.ForeColor = System.Drawing.SystemColors.ControlText; this.Picture2.Cursor = System.Windows.Forms.Cursors.Default; this.Picture2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Picture2.TabStop = true; this.Picture2.Visible = true; this.Picture2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.Picture2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Picture2.Name = "Picture2"; this._frmMode_1.Text = "Outstanding Day End Run"; this._frmMode_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmMode_1.Size = new System.Drawing.Size(196, 256); this._frmMode_1.Location = new System.Drawing.Point(204, 120); this._frmMode_1.TabIndex = 9; this._frmMode_1.BackColor = System.Drawing.SystemColors.Control; this._frmMode_1.Enabled = true; this._frmMode_1.ForeColor = System.Drawing.SystemColors.ControlText; this._frmMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmMode_1.Visible = true; this._frmMode_1.Padding = new System.Windows.Forms.Padding(0); this._frmMode_1.Name = "_frmMode_1"; this._Label1_7.Text = "There have been no Point Of Sale transactions since the last time this Month End Run procedure was run."; this._Label1_7.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._Label1_7.ForeColor = System.Drawing.Color.Red; this._Label1_7.Size = new System.Drawing.Size(178, 70); this._Label1_7.Location = new System.Drawing.Point(12, 30); this._Label1_7.TabIndex = 11; this._Label1_7.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_7.BackColor = System.Drawing.SystemColors.Control; this._Label1_7.Enabled = true; this._Label1_7.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_7.UseMnemonic = true; this._Label1_7.Visible = true; this._Label1_7.AutoSize = false; this._Label1_7.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_7.Name = "_Label1_7"; this._Label1_6.Text = "There is no need to run your Month End Run."; this._Label1_6.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._Label1_6.ForeColor = System.Drawing.Color.Red; this._Label1_6.Size = new System.Drawing.Size(178, 70); this._Label1_6.Location = new System.Drawing.Point(12, 102); this._Label1_6.TabIndex = 10; this._Label1_6.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_6.BackColor = System.Drawing.SystemColors.Control; this._Label1_6.Enabled = true; this._Label1_6.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_6.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_6.UseMnemonic = true; this._Label1_6.Visible = true; this._Label1_6.AutoSize = false; this._Label1_6.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_6.Name = "_Label1_6"; this._frmMode_0.Text = "Outstanding Day End Run"; this._frmMode_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmMode_0.Size = new System.Drawing.Size(196, 256); this._frmMode_0.Location = new System.Drawing.Point(9, 12); this._frmMode_0.TabIndex = 6; this._frmMode_0.BackColor = System.Drawing.SystemColors.Control; this._frmMode_0.Enabled = true; this._frmMode_0.ForeColor = System.Drawing.SystemColors.ControlText; this._frmMode_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmMode_0.Visible = true; this._frmMode_0.Padding = new System.Windows.Forms.Padding(0); this._frmMode_0.Name = "_frmMode_0"; this._Label1_4.Text = "Please complete the Day End Run before proceeding with your Month End."; this._Label1_4.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._Label1_4.ForeColor = System.Drawing.Color.Red; this._Label1_4.Size = new System.Drawing.Size(178, 70); this._Label1_4.Location = new System.Drawing.Point(12, 102); this._Label1_4.TabIndex = 8; this._Label1_4.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_4.BackColor = System.Drawing.SystemColors.Control; this._Label1_4.Enabled = true; this._Label1_4.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_4.UseMnemonic = true; this._Label1_4.Visible = true; this._Label1_4.AutoSize = false; this._Label1_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_4.Name = "_Label1_4"; this._Label1_5.Text = "There is an outstanding Day End Run."; this._Label1_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._Label1_5.ForeColor = System.Drawing.Color.Red; this._Label1_5.Size = new System.Drawing.Size(178, 70); this._Label1_5.Location = new System.Drawing.Point(12, 30); this._Label1_5.TabIndex = 7; this._Label1_5.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_5.BackColor = System.Drawing.SystemColors.Control; this._Label1_5.Enabled = true; this._Label1_5.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_5.UseMnemonic = true; this._Label1_5.Visible = true; this._Label1_5.AutoSize = false; this._Label1_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_5.Name = "_Label1_5"; this._frmMode_2.Text = "Confirm Month End Run"; this._frmMode_2.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmMode_2.Size = new System.Drawing.Size(196, 256); this._frmMode_2.Location = new System.Drawing.Point(228, 24); this._frmMode_2.TabIndex = 2; this._frmMode_2.BackColor = System.Drawing.SystemColors.Control; this._frmMode_2.Enabled = true; this._frmMode_2.ForeColor = System.Drawing.SystemColors.ControlText; this._frmMode_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmMode_2.Visible = true; this._frmMode_2.Padding = new System.Windows.Forms.Padding(0); this._frmMode_2.Name = "_frmMode_2"; this._Label1_1.Text = "Are you sure you wish to run the Month End. This action will move your current month details into a last month position and update all your account appropriately."; this._Label1_1.Size = new System.Drawing.Size(178, 121); this._Label1_1.Location = new System.Drawing.Point(9, 27); this._Label1_1.TabIndex = 12; this._Label1_1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_1.BackColor = System.Drawing.SystemColors.Control; this._Label1_1.Enabled = true; this._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_1.UseMnemonic = true; this._Label1_1.Visible = true; this._Label1_1.AutoSize = false; this._Label1_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_1.Name = "_Label1_1"; this._Label1_2.Text = "By pressing 'Next' you will commit the Month End Run."; this._Label1_2.Size = new System.Drawing.Size(178, 34); this._Label1_2.Location = new System.Drawing.Point(9, 198); this._Label1_2.TabIndex = 5; this._Label1_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._Label1_2.BackColor = System.Drawing.SystemColors.Control; this._Label1_2.Enabled = true; this._Label1_2.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_2.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_2.UseMnemonic = true; this._Label1_2.Visible = true; this._Label1_2.AutoSize = false; this._Label1_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._Label1_2.Name = "_Label1_2"; this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBack.Text = "E&xit"; this.cmdBack.Size = new System.Drawing.Size(85, 25); this.cmdBack.Location = new System.Drawing.Point(6, 279); this.cmdBack.TabIndex = 1; this.cmdBack.BackColor = System.Drawing.SystemColors.Control; this.cmdBack.CausesValidation = true; this.cmdBack.Enabled = true; this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBack.TabStop = true; this.cmdBack.Name = "cmdBack"; this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNext.Text = "&Next >>"; this.cmdNext.Size = new System.Drawing.Size(84, 25); this.cmdNext.Location = new System.Drawing.Point(117, 279); this.cmdNext.TabIndex = 0; this.cmdNext.BackColor = System.Drawing.SystemColors.Control; this.cmdNext.CausesValidation = true; this.cmdNext.Enabled = true; this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNext.TabStop = true; this.cmdNext.Name = "cmdNext"; this.Controls.Add(_frmMode_3); this.Controls.Add(_frmMode_1); this.Controls.Add(_frmMode_0); this.Controls.Add(_frmMode_2); this.Controls.Add(cmdBack); this.Controls.Add(cmdNext); this._frmMode_3.Controls.Add(Picture2); this._frmMode_1.Controls.Add(_Label1_7); this._frmMode_1.Controls.Add(_Label1_6); this._frmMode_0.Controls.Add(_Label1_4); this._frmMode_0.Controls.Add(_Label1_5); this._frmMode_2.Controls.Add(_Label1_1); this._frmMode_2.Controls.Add(_Label1_2); //Me.Label1.SetIndex(_Label1_7, CType(7, Short)) //Me.Label1.SetIndex(_Label1_6, CType(6, Short)) //Me.Label1.SetIndex(_Label1_4, CType(4, Short)) //Me.Label1.SetIndex(_Label1_5, CType(5, Short)) //Me.Label1.SetIndex(_Label1_1, CType(1, Short)) //Me.Label1.SetIndex(_Label1_2, CType(2, Short)) //Me.frmMode.SetIndex(_frmMode_3, CType(3, Short)) //Me.frmMode.SetIndex(_frmMode_1, CType(1, Short)) //Me.frmMode.SetIndex(_frmMode_0, CType(0, Short)) //Me.frmMode.SetIndex(_frmMode_2, CType(2, Short)) //CType(Me.frmMode, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.Label1, System.ComponentModel.ISupportInitialize).EndInit() this._frmMode_3.ResumeLayout(false); this._frmMode_1.ResumeLayout(false); this._frmMode_0.ResumeLayout(false); this._frmMode_2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Rendering/Screen Space Reflection")] public class ScreenSpaceReflection : PostEffectsBase { public enum SSRDebugMode { None = 0, IncomingRadiance = 1, SSRResult = 2, FinalGlossyTerm = 3, SSRMask = 4, Roughness = 5, BaseColor = 6, SpecColor = 7, Reflectivity = 8, ReflectionProbeOnly = 9, ReflectionProbeMinusSSR = 10, SSRMinusReflectionProbe = 11, NoGlossy = 12, NegativeNoGlossy = 13, MipLevel = 14, } public enum SSRResolution { FullResolution = 0, HalfTraceFullResolve = 1, HalfResolution = 2, } [Serializable] public struct SSRSettings { [AttributeUsage(AttributeTargets.Field)] public class LayoutAttribute : Attribute { public enum Category { Basic, Reflections, Advanced, Debug, Undefined } public readonly Category category; public readonly int priority; public LayoutAttribute(Category category, int priority) { this.category = category; this.priority = priority; } } /// BASIC SETTINGS [Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")] [Range(0.0f, 2.0f)] [Layout(LayoutAttribute.Category.Basic, 1)] public float reflectionMultiplier; [Tooltip("Maximum reflection distance in world units.")] [Range(0.5f, 1000.0f)] [Layout(LayoutAttribute.Category.Basic, 2)] public float maxDistance; [Tooltip("How far away from the maxDistance to begin fading SSR.")] [Range(0.0f, 1000.0f)] [Layout(LayoutAttribute.Category.Basic, 3)] public float fadeDistance; [Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")] [Range(0.0f, 1.0f)] [Layout(LayoutAttribute.Category.Basic, 4)] public float screenEdgeFading; [Tooltip("Enable for better reflections of very bright objects at a performance cost")] [Layout(LayoutAttribute.Category.Basic, 5)] public bool enableHDR; // When enabled, we just add our reflections on top of the existing ones. This is physically incorrect, but several // popular demos and games have taken this approach, and it does hide some artifacts. [Tooltip("Add reflections on top of existing ones. Not physically correct.")] [Layout(LayoutAttribute.Category.Basic, 6)] public bool additiveReflection; /// REFLECTIONS [Tooltip("Max raytracing length.")] [Range(16, 2048)] [Layout(LayoutAttribute.Category.Reflections, 1)] public int maxSteps; [Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")] [Range(0, 4)] [Layout(LayoutAttribute.Category.Reflections, 2)] public int rayStepSize; [Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")] [Range(0.01f, 10.0f)] [Layout(LayoutAttribute.Category.Reflections, 3)] public float widthModifier; [Tooltip("Increase if reflections flicker on very rough surfaces.")] [Range(0.0f, 1.0f)] [Layout(LayoutAttribute.Category.Reflections, 4)] public float smoothFallbackThreshold; [Tooltip("Start falling back to non-SSR value solution at smoothFallbackThreshold - smoothFallbackDistance, with full fallback occuring at smoothFallbackThreshold.")] [Range(0.0f, 0.2f)] [Layout(LayoutAttribute.Category.Reflections, 5)] public float smoothFallbackDistance; [Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")] [Range(0.0f, 1.0f)] [Layout(LayoutAttribute.Category.Reflections, 6)] public float fresnelFade; [Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")] [Range(0.1f, 10.0f)] [Layout(LayoutAttribute.Category.Reflections, 7)] public float fresnelFadePower; [Tooltip("Controls how blurry reflections get as objects are further from the camera. 0 is constant blur no matter trace distance or distance from camera. 1 fully takes into account both factors.")] [Range(0.0f, 1.0f)] [Layout(LayoutAttribute.Category.Reflections, 8)] public float distanceBlur; /// ADVANCED [Range(0.0f, 0.99f)] [Tooltip("Increase to decrease flicker in scenes; decrease to prevent ghosting (especially in dynamic scenes). 0 gives maximum performance.")] [Layout(LayoutAttribute.Category.Advanced, 1)] public float temporalFilterStrength; [Tooltip("Enable to limit ghosting from applying the temporal filter.")] [Layout(LayoutAttribute.Category.Advanced, 2)] public bool useTemporalConfidence; [Tooltip("Improves quality in scenes with varying smoothness, at a potential performance cost.")] [Layout(LayoutAttribute.Category.Advanced, 3)] public bool traceEverywhere; [Tooltip("Enable to force more surfaces to use reflection probes if you see streaks on the sides of objects or bad reflections of their backs.")] [Layout(LayoutAttribute.Category.Advanced, 4)] public bool treatBackfaceHitAsMiss; [Tooltip("Enable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave off for scenes with glossy vertical objects.")] [Layout(LayoutAttribute.Category.Advanced, 5)] public bool suppressBackwardsRays; [Tooltip("Improve visual fidelity of reflections on rough surfaces near corners in the scene, at the cost of a small amount of performance.")] [Layout(LayoutAttribute.Category.Advanced, 6)] public bool improveCorners; [Tooltip("Half resolution SSRR is much faster, but less accurate. Quality can be reclaimed for some performance by doing the resolve at full resolution.")] [Layout(LayoutAttribute.Category.Advanced, 7)] public SSRResolution resolution; [Tooltip("Drastically improves reflection reconstruction quality at the expense of some performance.")] [Layout(LayoutAttribute.Category.Advanced, 8)] public bool bilateralUpsample; [Tooltip("Improve visual fidelity of mirror reflections at the cost of a small amount of performance.")] [Layout(LayoutAttribute.Category.Advanced, 9)] public bool reduceBanding; [Tooltip("Enable to limit the effect a few bright pixels can have on rougher surfaces")] [Layout(LayoutAttribute.Category.Advanced, 10)] public bool highlightSuppression; /// DEBUG [Tooltip("Various Debug Visualizations")] [Layout(LayoutAttribute.Category.Debug, 1)] public SSRDebugMode debugMode; // If false, just uses the glossy GI buffer results [Tooltip("Uncheck to disable SSR without disabling the entire component")] [Layout(LayoutAttribute.Category.Debug, 2)] public bool enable; private static readonly SSRSettings s_Performance = new SSRSettings { maxSteps = 64, rayStepSize = 4, widthModifier = 0.5f, screenEdgeFading = 0, maxDistance = 10.0f, fadeDistance = 10.0f, reflectionMultiplier = 1.0f, treatBackfaceHitAsMiss = false, suppressBackwardsRays = true, enableHDR = false, smoothFallbackThreshold = 0.4f, traceEverywhere = false, distanceBlur = 1.0f, fresnelFade = 0.2f, resolution = SSRResolution.HalfResolution, bilateralUpsample = false, fresnelFadePower = 2.0f, smoothFallbackDistance = 0.05f, improveCorners = false, reduceBanding = false, additiveReflection = false, debugMode = SSRDebugMode.None, enable = true }; private static readonly SSRSettings s_Default = new SSRSettings { maxSteps = 128, rayStepSize = 3, widthModifier = 0.5f, screenEdgeFading = 0.03f, maxDistance = 100.0f, fadeDistance = 100.0f, reflectionMultiplier = 1.0f, treatBackfaceHitAsMiss = false, suppressBackwardsRays = false, enableHDR = true, smoothFallbackThreshold = 0.2f, traceEverywhere = true, distanceBlur = 1.0f, fresnelFade = 0.2f, resolution = SSRResolution.HalfTraceFullResolve, bilateralUpsample = true, fresnelFadePower = 2.0f, smoothFallbackDistance = 0.05f, improveCorners = true, reduceBanding = true, additiveReflection = false, debugMode = SSRDebugMode.None, enable = true }; private static readonly SSRSettings s_HighQuality = new SSRSettings { maxSteps = 512, rayStepSize = 1, widthModifier = 0.5f, screenEdgeFading = 0.03f, maxDistance = 100.0f, fadeDistance = 100.0f, reflectionMultiplier = 1.0f, treatBackfaceHitAsMiss = false, suppressBackwardsRays = false, enableHDR = true, smoothFallbackThreshold = 0.2f, traceEverywhere = true, distanceBlur = 1.0f, fresnelFade = 0.2f, resolution = SSRResolution.FullResolution, bilateralUpsample = true, fresnelFadePower = 2.0f, smoothFallbackDistance = 0.05f, improveCorners = true, reduceBanding = true, additiveReflection = false, debugMode = SSRDebugMode.None, enable = true }; public static SSRSettings performanceSettings { get { return s_Performance; } } public static SSRSettings defaultSettings { get { return s_Default; } } public static SSRSettings highQualitySettings { get { return s_HighQuality; } } } [SerializeField] public SSRSettings settings = SSRSettings.defaultSettings; ///////////// Unexposed Variables ////////////////// // Perf optimization we still need to test across platforms [Tooltip("Enable to try and bypass expensive bilateral upsampling away from edges. There is a slight performance hit for generating the edge buffers, but a potentially high performance savings from bypassing bilateral upsampling where it is unneeded. Test on your target platforms to see if performance improves.")] private bool useEdgeDetector = false; // Debug variable, useful for forcing all surfaces in a scene to reflection with arbitrary sharpness/roughness [Range(-4.0f, 4.0f)] private float mipBias = 0.0f; // Flag for whether to knock down the reflection term by occlusion stored in the gbuffer. Currently consistently gives // better results when true, so this flag is private for now. private bool useOcclusion = true; // When enabled, all filtering is performed at the highest resolution. This is extraordinarily slow, and should only be used during development. private bool fullResolutionFiltering = false; // Crude sky fallback, feature-gated until next revision private bool fallbackToSky = false; // For next release; will improve quality at the expense of performance private bool computeAverageRayDistance = false; // Internal values for temporal filtering private bool m_HasInformationFromPreviousFrame; private Matrix4x4 m_PreviousWorldToCameraMatrix; private RenderTexture m_PreviousDepthBuffer; private RenderTexture m_PreviousHitBuffer; private RenderTexture m_PreviousReflectionBuffer; public Shader ssrShader; private Material ssrMaterial; // Shader pass indices used by the effect private enum PassIndex { RayTraceStep1 = 0, RayTraceStep2 = 1, RayTraceStep4 = 2, RayTraceStep8 = 3, RayTraceStep16 = 4, CompositeFinal = 5, Blur = 6, CompositeSSR = 7, Blit = 8, EdgeGeneration = 9, MinMipGeneration = 10, HitPointToReflections = 11, BilateralKeyPack = 12, BlitDepthAsCSZ = 13, TemporalFilter = 14, AverageRayDistanceGeneration = 15, } public override bool CheckResources() { CheckSupport(true); ssrMaterial = CheckShaderAndCreateMaterial(ssrShader, ssrMaterial); if (!isSupported) ReportAutoDisable(); return isSupported; } void OnDisable() { if (ssrMaterial) DestroyImmediate(ssrMaterial); if (m_PreviousDepthBuffer) DestroyImmediate(m_PreviousDepthBuffer); if (m_PreviousHitBuffer) DestroyImmediate(m_PreviousHitBuffer); if (m_PreviousReflectionBuffer) DestroyImmediate(m_PreviousReflectionBuffer); ssrMaterial = null; m_PreviousDepthBuffer = null; m_PreviousHitBuffer = null; m_PreviousReflectionBuffer = null; } private void PreparePreviousBuffers(int w, int h) { if (m_PreviousDepthBuffer != null) { if ((m_PreviousDepthBuffer.width != w) || (m_PreviousDepthBuffer.height != h)) { DestroyImmediate(m_PreviousDepthBuffer); DestroyImmediate(m_PreviousHitBuffer); DestroyImmediate(m_PreviousReflectionBuffer); m_PreviousDepthBuffer = null; m_PreviousHitBuffer = null; m_PreviousReflectionBuffer = null; } } if (m_PreviousDepthBuffer == null) { m_PreviousDepthBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.RFloat); m_PreviousHitBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf); m_PreviousReflectionBuffer = new RenderTexture(w, h, 0, RenderTextureFormat.ARGBHalf); } } [ImageEffectOpaque] public void OnRenderImage(RenderTexture source, RenderTexture destination) { bool doTemporalFilterThisFrame = m_HasInformationFromPreviousFrame && settings.temporalFilterStrength > 0.0; m_HasInformationFromPreviousFrame = false; // No shaders set up, or not supported? Just blit source to destination. if (CheckResources() == false) { Graphics.Blit(source, destination); return; } // Not using deferred shading? Just blit source to destination. if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading) { Graphics.Blit(source, destination); return; } var rtW = source.width; var rtH = source.height; // RGB: Normals, A: Roughness. // Has the nice benefit of allowing us to control the filtering mode as well. RenderTexture bilateralKeyTexture = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGB32); bilateralKeyTexture.filterMode = FilterMode.Point; Graphics.Blit(source, bilateralKeyTexture, ssrMaterial, (int)PassIndex.BilateralKeyPack); ssrMaterial.SetTexture("_NormalAndRoughnessTexture", bilateralKeyTexture); float sWidth = source.width; float sHeight = source.height; Vector2 sourceToTempUV = new Vector2(sWidth / rtW, sHeight / rtH); int downsampleAmount = (settings.resolution == SSRResolution.FullResolution) ? 1 : 2; rtW = rtW / downsampleAmount; rtH = rtH / downsampleAmount; ssrMaterial.SetVector("_SourceToTempUV", new Vector4(sourceToTempUV.x, sourceToTempUV.y, 1.0f / sourceToTempUV.x, 1.0f / sourceToTempUV.y)); Matrix4x4 P = GetComponent<Camera>().projectionMatrix; Vector4 projInfo = new Vector4 ((-2.0f / (Screen.width * P[0])), (-2.0f / (Screen.height * P[5])), ((1.0f - P[2]) / P[0]), ((1.0f + P[6]) / P[5])); /** The height in pixels of a 1m object if viewed from 1m away. */ float pixelsPerMeterAtOneMeter = sWidth / (-2.0f * (float)(Math.Tan(GetComponent<Camera>().fieldOfView/180.0 * Math.PI * 0.5))); ssrMaterial.SetFloat("_PixelsPerMeterAtOneMeter", pixelsPerMeterAtOneMeter); float sx = Screen.width / 2.0f; float sy = Screen.height / 2.0f; Matrix4x4 warpToScreenSpaceMatrix = new Matrix4x4(); warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0.0f, 0.0f, sx)); warpToScreenSpaceMatrix.SetRow(1, new Vector4(0.0f, sy, 0.0f, sy)); warpToScreenSpaceMatrix.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); warpToScreenSpaceMatrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); Matrix4x4 projectToPixelMatrix = warpToScreenSpaceMatrix * P; ssrMaterial.SetVector("_ScreenSize", new Vector2(Screen.width, Screen.height)); ssrMaterial.SetVector("_ReflectionBufferSize", new Vector2(rtW, rtH)); Vector2 invScreenSize = new Vector2((float)(1.0 / (double)Screen.width), (float)(1.0 / (double)Screen.height)); Matrix4x4 worldToCameraMatrix = GetComponent<Camera>().worldToCameraMatrix; Matrix4x4 cameraToWorldMatrix = GetComponent< Camera > ().worldToCameraMatrix.inverse; ssrMaterial.SetVector("_InvScreenSize", invScreenSize); ssrMaterial.SetVector("_ProjInfo", projInfo); // used for unprojection ssrMaterial.SetMatrix("_ProjectToPixelMatrix", projectToPixelMatrix); ssrMaterial.SetMatrix("_WorldToCameraMatrix", worldToCameraMatrix); ssrMaterial.SetMatrix("_CameraToWorldMatrix", cameraToWorldMatrix); ssrMaterial.SetInt("_EnableRefine", settings.reduceBanding ? 1 : 0); ssrMaterial.SetInt("_AdditiveReflection", settings.additiveReflection ? 1 : 0); ssrMaterial.SetInt("_ImproveCorners", settings.improveCorners ? 1 : 0); ssrMaterial.SetFloat("_ScreenEdgeFading", settings.screenEdgeFading); ssrMaterial.SetFloat("_MipBias", mipBias); ssrMaterial.SetInt("_UseOcclusion", useOcclusion ? 1 : 0); ssrMaterial.SetInt("_BilateralUpsampling", settings.bilateralUpsample ? 1 : 0); ssrMaterial.SetInt("_FallbackToSky", fallbackToSky ? 1 : 0); ssrMaterial.SetInt("_TreatBackfaceHitAsMiss", settings.treatBackfaceHitAsMiss ? 1 : 0); ssrMaterial.SetInt("_SuppressBackwardsRays", settings.suppressBackwardsRays ? 1 : 0); ssrMaterial.SetInt("_TraceEverywhere", settings.traceEverywhere ? 1 : 0); float z_f = GetComponent<Camera>().farClipPlane; float z_n = GetComponent<Camera>().nearClipPlane; Vector3 cameraClipInfo = (float.IsPositiveInfinity(z_f)) ? new Vector3(z_n, -1.0f, 1.0f) : new Vector3(z_n * z_f, z_n - z_f, z_f); ssrMaterial.SetVector("_CameraClipInfo", cameraClipInfo); ssrMaterial.SetFloat("_MaxRayTraceDistance", settings.maxDistance); ssrMaterial.SetFloat("_FadeDistance", settings.fadeDistance); ssrMaterial.SetFloat("_LayerThickness", settings.widthModifier); const int maxMip = 5; RenderTexture[] reflectionBuffers; RenderTextureFormat intermediateFormat = settings.enableHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32; reflectionBuffers = new RenderTexture[maxMip]; for (int i = 0; i < maxMip; ++i) { if (fullResolutionFiltering) reflectionBuffers[i] = RenderTexture.GetTemporary(rtW, rtH, 0, intermediateFormat); else reflectionBuffers[i] = RenderTexture.GetTemporary(rtW >> i, rtH >> i, 0, intermediateFormat); // We explicitly interpolate during bilateral upsampling. reflectionBuffers[i].filterMode = settings.bilateralUpsample ? FilterMode.Point : FilterMode.Bilinear; } ssrMaterial.SetInt("_EnableSSR", settings.enable ? 1 : 0); ssrMaterial.SetInt("_DebugMode", (int)settings.debugMode); ssrMaterial.SetInt("_MaxSteps", settings.maxSteps); RenderTexture rayHitTexture = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); // We have 5 passes for different step sizes int tracePass = Mathf.Clamp(settings.rayStepSize, 0, 4); Graphics.Blit(source, rayHitTexture, ssrMaterial, tracePass); ssrMaterial.SetTexture("_HitPointTexture", rayHitTexture); // Resolve the hitpoints into the mirror reflection buffer Graphics.Blit(source, reflectionBuffers[0], ssrMaterial, (int)PassIndex.HitPointToReflections); ssrMaterial.SetTexture("_ReflectionTexture0", reflectionBuffers[0]); ssrMaterial.SetInt("_FullResolutionFiltering", fullResolutionFiltering ? 1 : 0); ssrMaterial.SetFloat("_MaxRoughness", 1.0f - settings.smoothFallbackThreshold); ssrMaterial.SetFloat("_RoughnessFalloffRange", settings.smoothFallbackDistance); ssrMaterial.SetFloat("_SSRMultiplier", settings.reflectionMultiplier); RenderTexture[] edgeTextures = new RenderTexture[maxMip]; if (settings.bilateralUpsample && useEdgeDetector) { edgeTextures[0] = RenderTexture.GetTemporary(rtW, rtH); Graphics.Blit(source, edgeTextures[0], ssrMaterial, (int)PassIndex.EdgeGeneration); for (int i = 1; i < maxMip; ++i) { edgeTextures[i] = RenderTexture.GetTemporary(rtW >> i, rtH >> i); ssrMaterial.SetInt("_LastMip", i - 1); Graphics.Blit(edgeTextures[i - 1], edgeTextures[i], ssrMaterial, (int)PassIndex.MinMipGeneration); } } // Generate the blurred low-resolution buffers for (int i = 1; i < maxMip; ++i) { RenderTexture inputTex = reflectionBuffers[i - 1]; RenderTexture hBlur; if (fullResolutionFiltering) hBlur = RenderTexture.GetTemporary(rtW, rtH, 0, intermediateFormat); else { int lowMip = i; hBlur = RenderTexture.GetTemporary(rtW >> lowMip, rtH >> (i - 1), 0, intermediateFormat); } for (int j = 0; j < (fullResolutionFiltering ? (i * i) : 1); ++j) { // Currently we blur at the resolution of the previous mip level, we could save bandwidth by blurring directly to the lower resolution. ssrMaterial.SetVector("_Axis", new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); ssrMaterial.SetFloat("_CurrentMipLevel", i - 1.0f); Graphics.Blit(inputTex, hBlur, ssrMaterial, (int)PassIndex.Blur); ssrMaterial.SetVector("_Axis", new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); inputTex = reflectionBuffers[i]; Graphics.Blit(hBlur, inputTex, ssrMaterial, (int)PassIndex.Blur); } ssrMaterial.SetTexture("_ReflectionTexture" + i, reflectionBuffers[i]); RenderTexture.ReleaseTemporary(hBlur); } if (settings.bilateralUpsample && useEdgeDetector) { for (int i = 0; i < maxMip; ++i) ssrMaterial.SetTexture("_EdgeTexture" + i, edgeTextures[i]); } ssrMaterial.SetInt("_UseEdgeDetector", useEdgeDetector ? 1 : 0); RenderTexture averageRayDistanceBuffer = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.RHalf); if (computeAverageRayDistance) { Graphics.Blit(source, averageRayDistanceBuffer, ssrMaterial, (int)PassIndex.AverageRayDistanceGeneration); } ssrMaterial.SetInt("_UseAverageRayDistance", computeAverageRayDistance ? 1 : 0); ssrMaterial.SetTexture("_AverageRayDistanceBuffer", averageRayDistanceBuffer); bool resolveDiffersFromTraceRes = (settings.resolution == SSRResolution.HalfTraceFullResolve); RenderTexture finalReflectionBuffer = RenderTexture.GetTemporary(resolveDiffersFromTraceRes ? source.width : rtW, resolveDiffersFromTraceRes ? source.height : rtH, 0, intermediateFormat); ssrMaterial.SetFloat("_FresnelFade", settings.fresnelFade); ssrMaterial.SetFloat("_FresnelFadePower", settings.fresnelFadePower); ssrMaterial.SetFloat("_DistanceBlur", settings.distanceBlur); ssrMaterial.SetInt("_HalfResolution", (settings.resolution != SSRResolution.FullResolution) ? 1 : 0); ssrMaterial.SetInt("_HighlightSuppression", settings.highlightSuppression ? 1 : 0); Graphics.Blit(reflectionBuffers[0], finalReflectionBuffer, ssrMaterial, (int)PassIndex.CompositeSSR); ssrMaterial.SetTexture("_FinalReflectionTexture", finalReflectionBuffer); RenderTexture temporallyFilteredBuffer = RenderTexture.GetTemporary(resolveDiffersFromTraceRes ? source.width : rtW, resolveDiffersFromTraceRes ? source.height : rtH, 0, intermediateFormat); if (doTemporalFilterThisFrame) { ssrMaterial.SetInt("_UseTemporalConfidence", settings.useTemporalConfidence ? 1 : 0); ssrMaterial.SetFloat("_TemporalAlpha", settings.temporalFilterStrength); ssrMaterial.SetMatrix("_CurrentCameraToPreviousCamera", m_PreviousWorldToCameraMatrix * cameraToWorldMatrix); ssrMaterial.SetTexture("_PreviousReflectionTexture", m_PreviousReflectionBuffer); ssrMaterial.SetTexture("_PreviousCSZBuffer", m_PreviousDepthBuffer); Graphics.Blit(source, temporallyFilteredBuffer, ssrMaterial, (int) PassIndex.TemporalFilter); ssrMaterial.SetTexture("_FinalReflectionTexture", temporallyFilteredBuffer); Graphics.Blit(source, destination, ssrMaterial, (int) PassIndex.CompositeFinal); } else Graphics.Blit(source, destination, ssrMaterial, (int) PassIndex.CompositeFinal); if (settings.temporalFilterStrength > 0.0) { m_PreviousWorldToCameraMatrix = worldToCameraMatrix; PreparePreviousBuffers(source.width, source.height); Graphics.Blit(source, m_PreviousDepthBuffer, ssrMaterial, (int)PassIndex.BlitDepthAsCSZ); Graphics.Blit(rayHitTexture, m_PreviousHitBuffer); Graphics.Blit(doTemporalFilterThisFrame ? temporallyFilteredBuffer : finalReflectionBuffer, m_PreviousReflectionBuffer); m_HasInformationFromPreviousFrame = true; } RenderTexture.ReleaseTemporary(temporallyFilteredBuffer); RenderTexture.ReleaseTemporary(averageRayDistanceBuffer); RenderTexture.ReleaseTemporary(bilateralKeyTexture); RenderTexture.ReleaseTemporary(rayHitTexture); if (settings.bilateralUpsample && useEdgeDetector) { for (int i = 0; i < maxMip; ++i) { RenderTexture.ReleaseTemporary(edgeTextures[i]); } } RenderTexture.ReleaseTemporary(finalReflectionBuffer); for (int i = 0; i < maxMip; ++i) { RenderTexture.ReleaseTemporary(reflectionBuffers[i]); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Correspondence.Mementos; using Correspondence.Networking; using Correspondence.Queries; using Correspondence.Strategy; using Correspondence.Debugging; using System.ComponentModel; using Correspondence.WorkQueues; using Correspondence.Threading; using Correspondence.Service; namespace Correspondence { /// <summary> /// </summary> public partial class Community : ICommunity { private IWorkQueue _userWorkQueue; private IWorkQueue _storageWorkQueue; private IWorkQueue _outgoingNetworkWorkQueue; private IWorkQueue _incomingNetworkWorkQueue; private Model _model; private Network _network; private IDictionary<Type, IFieldSerializer> _fieldSerializerByType = new Dictionary<Type, IFieldSerializer>(); private List<Process> _services = new List<Process>(); public Community(IStorageStrategy storageStrategy) { if (storageStrategy.IsSynchronous) { _userWorkQueue = new SynchronousWorkQueue(); _storageWorkQueue = new SynchronousWorkQueue(); } else { _userWorkQueue = new AsynchronousWorkQueue(); _storageWorkQueue = new AsynchronousWorkQueue(); } _outgoingNetworkWorkQueue = new AsynchronousWorkQueue(); _incomingNetworkWorkQueue = new AsynchronousWorkQueue(); _model = new Model(this, storageStrategy, _storageWorkQueue); _network = new Network(_model, storageStrategy, _storageWorkQueue, _outgoingNetworkWorkQueue, _incomingNetworkWorkQueue); // Register the default types. RegisterDefaultTypes(); } partial void RegisterDefaultTypes(); public bool ClientApp { get { return _model.ClientApp; } set { _model.ClientApp = value; } } public Community AddCommunicationStrategy(ICommunicationStrategy communicationStrategy) { _network.AddCommunicationStrategy(communicationStrategy); return this; } public Community AddAsynchronousCommunicationStrategy(IAsynchronousCommunicationStrategy asynchronousCommunicationStrategy) { _network.AddAsynchronousCommunicationStrategy(asynchronousCommunicationStrategy); return this; } public Community AddFieldSerializer<T>(IFieldSerializer fieldSerializer) { _fieldSerializerByType.Add(typeof(T), fieldSerializer); return this; } public Community AddType(CorrespondenceFactType type, ICorrespondenceFactFactory factory, FactMetadata factMetadata) { _model.AddType(type, factory, factMetadata); return this; } public Community AddQuery(CorrespondenceFactType type, QueryDefinition query) { _model.AddQuery(type, query); return this; } public Community AddUnpublisher(Role role, Condition publishCondition) { _model.AddUnpublisher(role.RoleMemento, publishCondition); return this; } public Community Subscribe<T>(Func<IEnumerable<T>> pivots) where T : CorrespondenceFact { _network.Subscribe(new Subscription(this, () => pivots().OfType<CorrespondenceFact>())); return this; } public Community Subscribe<T>(Func<Result<T>> pivots) where T : CorrespondenceFact { _network.Subscribe(new Subscription(this, () => pivots().OfType<CorrespondenceFact>())); return this; } public Community Subscribe<T>(Func<T> pivot) where T : CorrespondenceFact { _network.Subscribe(new Subscription(this, () => Enumerable.Repeat(pivot(), 1).OfType<CorrespondenceFact>())); return this; } public Community Register<T>() where T : ICorrespondenceModel, new() { ICorrespondenceModel model = new T(); model.RegisterAllFactTypes(this, _fieldSerializerByType); return this; } public async Task<T> AddFactAsync<T>(T prototype) where T : CorrespondenceFact { return await _model.AddFactAsync<T>(prototype); } public T FindFact<T>(T prototype) where T : CorrespondenceFact { return _model.FindFact<T>(prototype); } public async Task<T> LoadFactAsync<T>(string factName) where T : CorrespondenceFact { CorrespondenceFact fact = await _model.LoadFactAsync(factName); if (fact != null && fact is T) return (T)fact; return null; } public async Task SetFactAsync( string objectName, CorrespondenceFact fact ) { await _model.SetFactAsync(objectName, fact); } public event Action<CorrespondenceFact> FactAdded { add { _model.FactAdded += value; } remove { _model.FactAdded -= value; } } public event Action FactReceived { add { _model.FactReceived += value; } remove { _model.FactReceived -= value; } } public async Task<bool> SynchronizeAsync() { return await _network.SynchronizeAsync(); } public void BeginReceiving() { _network.BeginReceiving(); } public void BeginSending() { _network.BeginSending(); } public bool Synchronizing { get { return _network.Synchronizing; } } public Exception LastException { get { return _network.LastException ?? _model.LastException ?? _storageWorkQueue.LastException ?? _userWorkQueue.LastException; } } public void Perform(Func<Task> asyncDelegate) { _userWorkQueue.Perform(asyncDelegate); } public async Task QuiesceAsync() { await Task.WhenAll( _storageWorkQueue.JoinAsync(), _outgoingNetworkWorkQueue.JoinAsync(), _incomingNetworkWorkQueue.JoinAsync(), _userWorkQueue.JoinAsync()); } public void Notify(CorrespondenceFact pivot, string text1, string text2) { _network.Notify(pivot, text1, text2); } public Community AddService<TFact>( Func<IEnumerable<TFact>> queue, Func<TFact, Task> asyncAction) where TFact: CorrespondenceFact { _services.Add(new FactService<TFact>( () => (!Synchronizing && LastException == null) ? queue().ToList() : null, asyncAction)); return this; } internal IDictionary<Type, IFieldSerializer> FieldSerializerByType { get { return _fieldSerializerByType; } } internal async Task<CorrespondenceFact> GetFactByIDAsync( FactID id ) { return await _model.GetFactByIDAsync(id); } internal void ExecuteQuery( FactID startingId, QueryDefinition queryDefinition, QueryOptions options, Action<List<CorrespondenceFact>> doneLoading) { _storageWorkQueue.Perform(async delegate { var facts = await _model.ExecuteQueryAsync( queryDefinition, startingId, options); doneLoading(facts); }); } [Obsolete("This property is only for debugging. Do not code against it.")] [EditorBrowsable(EditorBrowsableState.Never)] public TypeDescriptor[] BrowseTheDataStore { get { return _model.TypeDescriptors; } } internal FactDescriptor BrowseTheDataStoreFromThisPoint(CorrespondenceFact fact) { return _model.LoadFactDescriptorById(fact); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Pipelines.DataMapperResolver; using NUnit.Framework; using Glass.Mapper.Configuration; using NSubstitute; namespace Glass.Mapper.Tests { [TestFixture] public class ContextFixture { [TearDown] public void TearDown() { Context.Clear(); } [SetUp] public void Setup() { } #region Create [Test] public void Create_CreateContext_CanGetContextFromContextDictionary() { //Assign string contextName = "testContext"; bool isDefault = false; Context.Clear(); //Act Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault); //Assert Assert.IsTrue(Context.Contexts.ContainsKey(contextName)); Assert.IsNotNull(Context.Contexts[contextName]); Assert.IsNull(Context.Default); } [Test] public void Create_LoadContextAsDefault_CanGetContextFromContextDictionary() { //Assign string contextName = "testContext"; bool isDefault = true; //Act Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault); //Assert Assert.IsTrue(Context.Contexts.ContainsKey(contextName)); Assert.IsNotNull(Context.Contexts[contextName]); Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[contextName], Context.Default); } [Test] public void Create_LoadContextAsDefault_CanGetContextFromContextDictionaryUsingDefault() { //Assign //Act Context.Create(Substitute.For<IDependencyResolver>()); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); } #endregion #region Load [Test] public void Load_LoadContextWithTypeConfigs_CanGetTypeConfigsFromContext() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = Substitute.For<AbstractTypeConfiguration>(); config1.Type = typeof (StubClass1); loader1.Load().Returns(new[]{config1}); var loader2 = Substitute.For<IConfigurationLoader>(); var config2 = Substitute.For<AbstractTypeConfiguration>(); config2.Type = typeof(StubClass2); loader2.Load().Returns(new[] { config2 }); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Load(loader1, loader2); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.AreEqual(config1, Context.Default.TypeConfigurations[config1.Type]); Assert.AreEqual(config2, Context.Default.TypeConfigurations[config2.Type]); } #endregion #region Indexers [Test] public void Indexer_UseTypeIndexerWithValidConfig_ReturnsTypeConfiguration() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); var config1 = Substitute.For<AbstractTypeConfiguration>(); config1.Type = typeof(StubClass1); loader1.Load().Returns(new[] { config1 }); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.AreEqual(config1, Context.Default[config1.Type]); } [Test] public void Indexer_UseTypeIndexerWithInvalidConfig_ReturnsNull() { //Assign var loader1 = Substitute.For<IConfigurationLoader>(); //Act var context = Context.Create(Substitute.For<IDependencyResolver>()); context.Load(loader1); //Assert Assert.IsNotNull(Context.Default); Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default); Assert.IsNull( Context.Default[typeof(StubClass1)]); } #endregion #region GetTypeConfiguration [Test] public void GetTypeConfiguration_BaseTypeNullForInterface_AutoLoadsConfig() { //Arrange string contextName = "testContext"; bool isDefault = true; var type = typeof (IStubInterface1); Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault); var context = Context.Contexts[contextName]; //Act var config = context.GetTypeConfiguration<StubAbstractTypeConfiguration>(type); //Assert Assert.IsNotNull(config); } #endregion #region Stubs public interface IStubInterface1 { } public class StubClass1 { } public class StubClass2 { } public class StubAbstractDataMapper : AbstractDataMapper { public Func<AbstractPropertyConfiguration, bool> CanHandleFunction { get; set; } public override bool CanHandle(AbstractPropertyConfiguration configuration, Context context) { return CanHandleFunction(configuration); } public override void MapToCms(AbstractDataMappingContext mappingContext) { throw new NotImplementedException(); } public override object MapToProperty(AbstractDataMappingContext mappingContext) { throw new NotImplementedException(); } public override void Setup(DataMapperResolverArgs args) { throw new NotImplementedException(); } } public class StubAbstractTypeConfiguration : AbstractTypeConfiguration { } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Reflection; using System.Xml; using System.Workflow.ComponentModel.Serialization; using System.Drawing; namespace System.Workflow.ComponentModel.Design { #region Class ActivityDesignerLayoutSerializer [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ActivityDesignerLayoutSerializer : WorkflowMarkupSerializer { protected override void OnBeforeSerialize(WorkflowMarkupSerializationManager serializationManager, object obj) { base.OnBeforeSerialize(serializationManager, obj); //For root activity we will go through all the nested activities and put the namespaces at the top level ActivityDesigner activityDesigner = obj as ActivityDesigner; XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter; if (activityDesigner.Activity != null && activityDesigner.Activity.Parent == null && writer != null) { string prefix = String.Empty; XmlQualifiedName xmlQualifiedName = serializationManager.GetXmlQualifiedName(typeof(Point), out prefix); writer.WriteAttributeString("xmlns", prefix, null, xmlQualifiedName.Namespace); } } protected override object CreateInstance(WorkflowMarkupSerializationManager serializationManager, Type type) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (type == null) throw new ArgumentNullException("type"); object designer = null; IDesignerHost host = serializationManager.GetService(typeof(IDesignerHost)) as IDesignerHost; XmlReader reader = serializationManager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader; if (host != null && reader != null) { //Find the associated activity string associatedActivityName = String.Empty; while (reader.MoveToNextAttribute() && !reader.LocalName.Equals("Name", StringComparison.Ordinal)); if (reader.LocalName.Equals("Name", StringComparison.Ordinal) && reader.ReadAttributeValue()) associatedActivityName = reader.Value; reader.MoveToElement(); if (!String.IsNullOrEmpty(associatedActivityName)) { CompositeActivityDesigner parentDesigner = serializationManager.Context[typeof(CompositeActivityDesigner)] as CompositeActivityDesigner; if (parentDesigner == null) { Activity activity = host.RootComponent as Activity; if (activity != null && !associatedActivityName.Equals(activity.Name, StringComparison.Ordinal)) { foreach (IComponent component in host.Container.Components) { activity = component as Activity; if (activity != null && associatedActivityName.Equals(activity.Name, StringComparison.Ordinal)) break; } } if (activity != null) designer = host.GetDesigner(activity); } else { CompositeActivity compositeActivity = parentDesigner.Activity as CompositeActivity; if (compositeActivity != null) { Activity matchingActivity = null; foreach (Activity activity in compositeActivity.Activities) { if (associatedActivityName.Equals(activity.Name, StringComparison.Ordinal)) { matchingActivity = activity; break; } } if (matchingActivity != null) designer = host.GetDesigner(matchingActivity); } } if (designer == null) serializationManager.ReportError(SR.GetString(SR.Error_LayoutSerializationActivityNotFound, reader.LocalName, associatedActivityName, "Name")); } else { serializationManager.ReportError(SR.GetString(SR.Error_LayoutSerializationAssociatedActivityNotFound, reader.LocalName, "Name")); } } return designer; } protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (obj == null) throw new ArgumentNullException("obj"); List<PropertyInfo> properties = new List<PropertyInfo>(base.GetProperties(serializationManager, obj)); ActivityDesigner activityDesigner = obj as ActivityDesigner; if (activityDesigner != null) { PropertyInfo nameProperty = activityDesigner.GetType().GetProperty("Name", BindingFlags.Instance | BindingFlags.NonPublic); if (nameProperty != null) properties.Insert(0, nameProperty); } return properties.ToArray(); } } #endregion #region Class CompositeActivityDesignerLayoutSerializer [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class CompositeActivityDesignerLayoutSerializer : ActivityDesignerLayoutSerializer { protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj) { List<PropertyInfo> properties = new List<PropertyInfo>(base.GetProperties(serializationManager, obj)); properties.Add(typeof(CompositeActivityDesigner).GetProperty("Designers", BindingFlags.Instance | BindingFlags.NonPublic)); return properties.ToArray(); } } #endregion #region Class FreeformActivityDesignerLayoutSerializer [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class FreeformActivityDesignerLayoutSerializer : CompositeActivityDesignerLayoutSerializer { protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (obj == null) throw new ArgumentNullException("obj"); XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter; PropertyInfo[] properties = base.GetProperties(serializationManager, obj); FreeformActivityDesigner freeformDesigner = obj as FreeformActivityDesigner; if (freeformDesigner != null) { List<PropertyInfo> serializableProperties = new List<PropertyInfo>(); foreach (PropertyInfo property in properties) { //Only filter this property out when we are writting if (writer != null && property.Name.Equals("AutoSizeMargin", StringComparison.Ordinal) && freeformDesigner.AutoSizeMargin == FreeformActivityDesigner.DefaultAutoSizeMargin) { continue; } serializableProperties.Add(property); } serializableProperties.Add(typeof(FreeformActivityDesigner).GetProperty("DesignerConnectors", BindingFlags.Instance | BindingFlags.NonPublic)); properties = serializableProperties.ToArray(); } return properties; } } #endregion #region ConnectorLayoutSerializer [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ConnectorLayoutSerializer : WorkflowMarkupSerializer { protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (obj == null) throw new ArgumentNullException("obj"); List<PropertyInfo> properties = new List<PropertyInfo>(base.GetProperties(serializationManager, obj)); properties.Add(typeof(Connector).GetProperty("SourceActivity", BindingFlags.Instance | BindingFlags.NonPublic)); properties.Add(typeof(Connector).GetProperty("SourceConnectionIndex", BindingFlags.Instance | BindingFlags.NonPublic)); properties.Add(typeof(Connector).GetProperty("SourceConnectionEdge", BindingFlags.Instance | BindingFlags.NonPublic)); properties.Add(typeof(Connector).GetProperty("TargetActivity", BindingFlags.Instance | BindingFlags.NonPublic)); properties.Add(typeof(Connector).GetProperty("TargetConnectionIndex", BindingFlags.Instance | BindingFlags.NonPublic)); properties.Add(typeof(Connector).GetProperty("TargetConnectionEdge", BindingFlags.Instance | BindingFlags.NonPublic)); properties.Add(typeof(Connector).GetProperty("Segments", BindingFlags.Instance | BindingFlags.NonPublic)); return properties.ToArray(); } protected override object CreateInstance(WorkflowMarkupSerializationManager serializationManager, Type type) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (type == null) throw new ArgumentNullException("type"); Connector connector = null; IReferenceService referenceService = serializationManager.GetService(typeof(IReferenceService)) as IReferenceService; FreeformActivityDesigner freeformDesigner = serializationManager.Context[typeof(FreeformActivityDesigner)] as FreeformActivityDesigner; if (freeformDesigner != null && referenceService != null) { ConnectionPoint sourceConnection = null; ConnectionPoint targetConnection = null; try { Dictionary<string, string> constructionArguments = GetConnectorConstructionArguments(serializationManager, type); if (constructionArguments.ContainsKey("SourceActivity") && constructionArguments.ContainsKey("SourceConnectionIndex") && constructionArguments.ContainsKey("SourceConnectionEdge")) { ActivityDesigner sourceDesigner = ActivityDesigner.GetDesigner(referenceService.GetReference(constructionArguments["SourceActivity"] as string) as Activity); DesignerEdges sourceEdge = (DesignerEdges)Enum.Parse(typeof(DesignerEdges), constructionArguments["SourceConnectionEdge"] as string); int sourceIndex = Convert.ToInt32(constructionArguments["SourceConnectionIndex"] as string, System.Globalization.CultureInfo.InvariantCulture); if (sourceDesigner != null && sourceEdge != DesignerEdges.None && sourceIndex >= 0) sourceConnection = new ConnectionPoint(sourceDesigner, sourceEdge, sourceIndex); } if (constructionArguments.ContainsKey("TargetActivity") && constructionArguments.ContainsKey("TargetConnectionIndex") && constructionArguments.ContainsKey("TargetConnectionEdge")) { ActivityDesigner targetDesigner = ActivityDesigner.GetDesigner(referenceService.GetReference(constructionArguments["TargetActivity"] as string) as Activity); DesignerEdges targetEdge = (DesignerEdges)Enum.Parse(typeof(DesignerEdges), constructionArguments["TargetConnectionEdge"] as string); int targetIndex = Convert.ToInt32(constructionArguments["TargetConnectionIndex"] as string, System.Globalization.CultureInfo.InvariantCulture); if (targetDesigner != null && targetEdge != DesignerEdges.None && targetIndex >= 0) targetConnection = new ConnectionPoint(targetDesigner, targetEdge, targetIndex); } } catch { } if (sourceConnection != null && targetConnection != null) connector = freeformDesigner.AddConnector(sourceConnection, targetConnection); } return connector; } protected override void OnAfterDeserialize(WorkflowMarkupSerializationManager serializationManager, object obj) { base.OnAfterDeserialize(serializationManager, obj); //The following code is needed in order to making sure that we set the modification flag correctly after deserialization Connector connector = obj as Connector; if (connector != null) connector.SetConnectorModified(true); } protected Dictionary<string, string> GetConnectorConstructionArguments(WorkflowMarkupSerializationManager serializationManager, Type type) { Dictionary<string, string> argumentDictionary = new Dictionary<string, string>(); XmlReader reader = serializationManager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader; if (reader != null && reader.NodeType == XmlNodeType.Element) { while (reader.MoveToNextAttribute()) { string attributeName = reader.LocalName; if (!argumentDictionary.ContainsKey(attributeName)) { reader.ReadAttributeValue(); argumentDictionary.Add(attributeName, reader.Value); } } reader.MoveToElement(); } return argumentDictionary; } } #endregion #region Class ActivityDesignerLayoutSerializerProvider internal sealed class ActivityDesignerLayoutSerializerProvider : IDesignerSerializationProvider { #region IDesignerSerializationProvider Members object IDesignerSerializationProvider.GetSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType) { if (typeof(System.Drawing.Color) == objectType) currentSerializer = new ColorMarkupSerializer(); else if (typeof(System.Drawing.Size) == objectType) currentSerializer = new SizeMarkupSerializer(); else if (typeof(System.Drawing.Point) == objectType) currentSerializer = new PointMarkupSerializer(); return currentSerializer; } #endregion } #endregion #region Class ColorMarkupSerializer internal sealed class ColorMarkupSerializer : WorkflowMarkupSerializer { protected internal override bool CanSerializeToString(WorkflowMarkupSerializationManager serializationManager, object value) { return (value is System.Drawing.Color); } protected internal override string SerializeToString(WorkflowMarkupSerializationManager serializationManager, object value) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (value == null) throw new ArgumentNullException("value"); string stringValue = String.Empty; if (value is System.Drawing.Color) { System.Drawing.Color color = (System.Drawing.Color)value; long colorValue = (long)((uint)(color.A << 24 | color.R << 16 | color.G << 8 | color.B)) & 0xFFFFFFFF; stringValue = "0X" + colorValue.ToString("X08", System.Globalization.CultureInfo.InvariantCulture); } return stringValue; } protected internal override object DeserializeFromString(WorkflowMarkupSerializationManager serializationManager, Type propertyType, string value) { if (propertyType.IsAssignableFrom(typeof(System.Drawing.Color))) { string colorValue = value as string; if (!String.IsNullOrEmpty(colorValue)) { if (colorValue.StartsWith("0X", StringComparison.OrdinalIgnoreCase)) { long propertyValue = Convert.ToInt64((string)value, 16) & 0xFFFFFFFF; return System.Drawing.Color.FromArgb((Byte)(propertyValue >> 24), (Byte)(propertyValue >> 16), (Byte)(propertyValue >> 8), (Byte)(propertyValue)); } else { return base.DeserializeFromString(serializationManager, propertyType, value); } } } return null; } } #endregion #region Class SizeMarkupSerializer internal sealed class SizeMarkupSerializer : WorkflowMarkupSerializer { protected internal override bool CanSerializeToString(WorkflowMarkupSerializationManager serializationManager, object value) { return (value is System.Drawing.Size); } protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj) { List<PropertyInfo> properties = new List<PropertyInfo>(); if (obj is Size) { properties.Add(typeof(Size).GetProperty("Width")); properties.Add(typeof(Size).GetProperty("Height")); } return properties.ToArray(); } protected internal override string SerializeToString(WorkflowMarkupSerializationManager serializationManager, object value) { string convertedValue = String.Empty; TypeConverter converter = TypeDescriptor.GetConverter(value); if (converter != null && converter.CanConvertTo(typeof(string))) convertedValue = converter.ConvertTo(value, typeof(string)) as string; else convertedValue = base.SerializeToString(serializationManager, value); return convertedValue; } protected internal override object DeserializeFromString(WorkflowMarkupSerializationManager serializationManager, Type propertyType, string value) { object size = Size.Empty; string sizeValue = value as string; if (!String.IsNullOrEmpty(sizeValue)) { TypeConverter converter = TypeDescriptor.GetConverter(typeof(Size)); if (converter != null && converter.CanConvertFrom(typeof(string)) && !IsValidCompactAttributeFormat(sizeValue)) size = converter.ConvertFrom(value); else size = base.SerializeToString(serializationManager, value); } return size; } } #endregion #region Class PointMarkupSerializer internal sealed class PointMarkupSerializer : WorkflowMarkupSerializer { protected internal override bool CanSerializeToString(WorkflowMarkupSerializationManager serializationManager, object value) { return (value is Point); } protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj) { List<PropertyInfo> properties = new List<PropertyInfo>(); if (obj is Point) { properties.Add(typeof(Point).GetProperty("X")); properties.Add(typeof(Point).GetProperty("Y")); } return properties.ToArray(); } protected internal override string SerializeToString(WorkflowMarkupSerializationManager serializationManager, object value) { string convertedValue = String.Empty; TypeConverter converter = TypeDescriptor.GetConverter(value); if (converter != null && converter.CanConvertTo(typeof(string))) convertedValue = converter.ConvertTo(value, typeof(string)) as string; else convertedValue = base.SerializeToString(serializationManager, value); return convertedValue; } protected internal override object DeserializeFromString(WorkflowMarkupSerializationManager serializationManager, Type propertyType, string value) { object point = Point.Empty; string pointValue = value as string; if (!String.IsNullOrEmpty(pointValue)) { TypeConverter converter = TypeDescriptor.GetConverter(typeof(Point)); if (converter != null && converter.CanConvertFrom(typeof(string)) && !IsValidCompactAttributeFormat(pointValue)) point = converter.ConvertFrom(value); else point = base.SerializeToString(serializationManager, value); } return point; } } #endregion }
// Shared source file using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace NuGet.CatalogReader { internal class TaskUtils { /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), token: CancellationToken.None); } /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks, CancellationToken token) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), useTaskRun: false, token: token); } /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks, bool useTaskRun, CancellationToken token) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), useTaskRun: false, token: token); } /// <summary> /// Run tasks in parallel. /// </summary> public static Task RunAsync(IEnumerable<Func<Task>> tasks, bool useTaskRun, int maxThreads, CancellationToken token) { return RunAsync( tasks: tasks.Select(GetFuncWithReturnValue), useTaskRun: false, maxThreads: maxThreads, token: token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks) { return RunAsync(tasks, CancellationToken.None); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks, CancellationToken token) { return RunAsync(tasks, useTaskRun: false, token: token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks, bool useTaskRun, CancellationToken token) { var maxThreads = Environment.ProcessorCount * 2; return RunAsync(tasks, useTaskRun, maxThreads, token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public static Task<T[]> RunAsync<T>(IEnumerable<Func<Task<T>>> tasks, bool useTaskRun, int maxThreads, CancellationToken token) { return RunAsync(tasks, useTaskRun, maxThreads, DefaultProcess, token); } /// <summary> /// Run tasks in parallel and returns the results in the original order. /// </summary> public async static Task<R[]> RunAsync<T, R>(IEnumerable<Func<Task<T>>> tasks, bool useTaskRun, int maxThreads, Func<Task<T>, Task<R>> process, CancellationToken token) { var toRun = new ConcurrentQueue<WorkItem<T>>(); var index = 0; foreach (var task in tasks) { // Create work items, save the original position. toRun.Enqueue(new WorkItem<T>(task, index)); index++; } var totalCount = index; // Create an array for the results, at this point index is the count. var results = new R[totalCount]; List<Task> threads = null; var taskCount = GetAdditionalThreadCount(maxThreads, totalCount); if (taskCount > 0) { threads = new List<Task>(taskCount); // Create long running tasks to run work on. for (var i = 0; i < taskCount; i++) { Task task = null; if (useTaskRun) { // Start a new task task = Task.Run(() => RunTaskAsync(toRun, results, process, token)); } else { // Run directly task = RunTaskAsync(toRun, results, process, token); } threads.Add(task); } } // Run tasks on the current thread // This is used both for parallel and non-parallel. await RunTaskAsync(toRun, results, process, token); // After all work completes on this thread, wait for the rest. if (threads != null) { await Task.WhenAll(threads); } return results; } private static int GetAdditionalThreadCount(int maxThreads, int index) { // Number of threads total var x = Math.Min(index, maxThreads); // Remove one for the current thread x--; // Avoid -1 x = Math.Max(0, x); return x; } /// <summary> /// Run tasks on a single thread. /// </summary> private static async Task RunTaskAsync<T, R>(ConcurrentQueue<WorkItem<T>> toRun, R[] results, Func<Task<T>, Task<R>> process, CancellationToken token) { // Run until cancelled or we are out of work. while (!token.IsCancellationRequested && toRun.TryDequeue(out var item)) { var result = await process(item.Item()); results[item.Index] = result; } } private static Task<T> DefaultProcess<T>(Task<T> result) { return result; } private static Func<Task<bool>> GetFuncWithReturnValue(Func<Task> task) { return new Func<Task<bool>>(() => { return RunWithReturnValue(task); }); } private static async Task<bool> RunWithReturnValue(Func<Task> task) { await task(); return true; } /// <summary> /// Contains a Func to run and the original position in the queue. /// </summary> private sealed class WorkItem<T> { internal Func<Task<T>> Item { get; } internal int Index { get; } public WorkItem(Func<Task<T>> item, int index) { Item = item; Index = index; } } } }
namespace SharpFlame { partial class frmGenerator : System.Windows.Forms.Form { //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()]protected override void Dispose(bool disposing) { try { if (disposing && components != null) { components.Dispose(); } } finally { base.Dispose(disposing); } } //Required by the Windows Form Designer private System.ComponentModel.Container components = null; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent() { this.Label1 = new System.Windows.Forms.Label(); this.FormClosing += frmGenerator_FormClosing; this.Load += frmWZMapGen_Load; this.txtWidth = new System.Windows.Forms.TextBox(); this.txtHeight = new System.Windows.Forms.TextBox(); this.Label2 = new System.Windows.Forms.Label(); this.txt1x = new System.Windows.Forms.TextBox(); this.Label3 = new System.Windows.Forms.Label(); this.Label4 = new System.Windows.Forms.Label(); this.Label5 = new System.Windows.Forms.Label(); this.rdoPlayer2 = new System.Windows.Forms.RadioButton(); this.rdoPlayer2.CheckedChanged += this.rdoPlayer2_CheckedChanged; this.txt1y = new System.Windows.Forms.TextBox(); this.txt2y = new System.Windows.Forms.TextBox(); this.txt2x = new System.Windows.Forms.TextBox(); this.txt3y = new System.Windows.Forms.TextBox(); this.txt3x = new System.Windows.Forms.TextBox(); this.rdoPlayer3 = new System.Windows.Forms.RadioButton(); this.rdoPlayer3.CheckedChanged += this.rdoPlayer3_CheckedChanged; this.txt4y = new System.Windows.Forms.TextBox(); this.txt4x = new System.Windows.Forms.TextBox(); this.rdoPlayer4 = new System.Windows.Forms.RadioButton(); this.rdoPlayer4.CheckedChanged += this.rdoPlayer4_CheckedChanged; this.txt5y = new System.Windows.Forms.TextBox(); this.txt5x = new System.Windows.Forms.TextBox(); this.rdoPlayer5 = new System.Windows.Forms.RadioButton(); this.rdoPlayer5.CheckedChanged += this.rdoPlayer5_CheckedChanged; this.txt6y = new System.Windows.Forms.TextBox(); this.txt6x = new System.Windows.Forms.TextBox(); this.rdoPlayer6 = new System.Windows.Forms.RadioButton(); this.rdoPlayer6.CheckedChanged += this.rdoPlayer6_CheckedChanged; this.txt7y = new System.Windows.Forms.TextBox(); this.txt7x = new System.Windows.Forms.TextBox(); this.rdoPlayer7 = new System.Windows.Forms.RadioButton(); this.rdoPlayer7.CheckedChanged += this.rdoPlayer7_CheckedChanged; this.txt8y = new System.Windows.Forms.TextBox(); this.txt8x = new System.Windows.Forms.TextBox(); this.rdoPlayer8 = new System.Windows.Forms.RadioButton(); this.rdoPlayer8.CheckedChanged += this.rdoPlayer8_CheckedChanged; this.Label7 = new System.Windows.Forms.Label(); this.txtLevels = new System.Windows.Forms.TextBox(); this.txtLevelFrequency = new System.Windows.Forms.TextBox(); this.Label8 = new System.Windows.Forms.Label(); this.txtRampDistance = new System.Windows.Forms.TextBox(); this.Label9 = new System.Windows.Forms.Label(); this.txtBaseOil = new System.Windows.Forms.TextBox(); this.Label10 = new System.Windows.Forms.Label(); this.txtOilElsewhere = new System.Windows.Forms.TextBox(); this.Label11 = new System.Windows.Forms.Label(); this.txtOilClusterMin = new System.Windows.Forms.TextBox(); this.Label12 = new System.Windows.Forms.Label(); this.Label13 = new System.Windows.Forms.Label(); this.Label14 = new System.Windows.Forms.Label(); this.txtOilClusterMax = new System.Windows.Forms.TextBox(); this.txtBaseLevel = new System.Windows.Forms.TextBox(); this.Label17 = new System.Windows.Forms.Label(); this.txtOilDispersion = new System.Windows.Forms.TextBox(); this.Label18 = new System.Windows.Forms.Label(); this.txtFScatterChance = new System.Windows.Forms.TextBox(); this.Label19 = new System.Windows.Forms.Label(); this.txtFClusterChance = new System.Windows.Forms.TextBox(); this.Label20 = new System.Windows.Forms.Label(); this.txtFClusterMin = new System.Windows.Forms.TextBox(); this.Label21 = new System.Windows.Forms.Label(); this.txtFClusterMax = new System.Windows.Forms.TextBox(); this.Label22 = new System.Windows.Forms.Label(); this.txtTrucks = new System.Windows.Forms.TextBox(); this.Label23 = new System.Windows.Forms.Label(); this.Label24 = new System.Windows.Forms.Label(); this.cboTileset = new System.Windows.Forms.ComboBox(); this.txtFlatness = new System.Windows.Forms.TextBox(); this.Label25 = new System.Windows.Forms.Label(); this.txtWaterQuantity = new System.Windows.Forms.TextBox(); this.Label26 = new System.Windows.Forms.Label(); this.Label27 = new System.Windows.Forms.Label(); this.txtVariation = new System.Windows.Forms.TextBox(); this.Label28 = new System.Windows.Forms.Label(); this.rdoPlayer1 = new System.Windows.Forms.RadioButton(); this.rdoPlayer1.CheckedChanged += this.rdoPlayer1_CheckedChanged; this.cboSymmetry = new System.Windows.Forms.ComboBox(); this.Label6 = new System.Windows.Forms.Label(); this.txtOilAtATime = new System.Windows.Forms.TextBox(); this.Label31 = new System.Windows.Forms.Label(); this.txtRampBase = new System.Windows.Forms.TextBox(); this.Label33 = new System.Windows.Forms.Label(); this.txtConnectedWater = new System.Windows.Forms.TextBox(); this.Label34 = new System.Windows.Forms.Label(); this.txt9y = new System.Windows.Forms.TextBox(); this.txt9x = new System.Windows.Forms.TextBox(); this.rdoPlayer9 = new System.Windows.Forms.RadioButton(); this.rdoPlayer9.CheckedChanged += this.rdoPlayer9_CheckedChanged; this.txt10y = new System.Windows.Forms.TextBox(); this.txt10x = new System.Windows.Forms.TextBox(); this.rdoPlayer10 = new System.Windows.Forms.RadioButton(); this.rdoPlayer10.CheckedChanged += this.rdoPlayer10_CheckedChanged; this.cbxMasterTexture = new System.Windows.Forms.CheckBox(); this.txtBaseArea = new System.Windows.Forms.TextBox(); this.Label15 = new System.Windows.Forms.Label(); this.btnGenerateLayout = new System.Windows.Forms.Button(); this.btnGenerateLayout.Click += this.btnGenerateLayout_Click; this.btnGenerateObjects = new System.Windows.Forms.Button(); this.btnGenerateObjects.Click += this.btnGenerateObjects_Click; this.btnStop = new System.Windows.Forms.Button(); this.btnStop.Click += this.btnStop_Click; this.lstResult = new System.Windows.Forms.ListBox(); this.btnGenerateRamps = new System.Windows.Forms.Button(); this.btnGenerateRamps.Click += this.btnGenerateRamps_Click; this.TabControl1 = new System.Windows.Forms.TabControl(); this.TabPage1 = new System.Windows.Forms.TabPage(); this.TabPage2 = new System.Windows.Forms.TabPage(); this.TabPage4 = new System.Windows.Forms.TabPage(); this.btnGenerateTextures = new System.Windows.Forms.Button(); this.btnGenerateTextures.Click += this.btnGenerateTextures_Click; this.TabPage3 = new System.Windows.Forms.TabPage(); this.Label16 = new System.Windows.Forms.Label(); this.txtFScatterGap = new System.Windows.Forms.TextBox(); this.TabControl1.SuspendLayout(); this.TabPage1.SuspendLayout(); this.TabPage2.SuspendLayout(); this.TabPage4.SuspendLayout(); this.TabPage3.SuspendLayout(); this.SuspendLayout(); // //Label1 // this.Label1.AutoSize = true; this.Label1.Location = new System.Drawing.Point(36, 40); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(39, 20); this.Label1.TabIndex = 5; this.Label1.Text = "Width"; this.Label1.UseCompatibleTextRendering = true; // //txtWidth // this.txtWidth.Location = new System.Drawing.Point(86, 37); this.txtWidth.Name = "txtWidth"; this.txtWidth.Size = new System.Drawing.Size(46, 22); this.txtWidth.TabIndex = 1; this.txtWidth.Text = "128"; this.txtWidth.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txtHeight // this.txtHeight.Location = new System.Drawing.Point(188, 37); this.txtHeight.Name = "txtHeight"; this.txtHeight.Size = new System.Drawing.Size(46, 22); this.txtHeight.TabIndex = 2; this.txtHeight.Text = "128"; this.txtHeight.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label2 // this.Label2.AutoSize = true; this.Label2.Location = new System.Drawing.Point(138, 40); this.Label2.Name = "Label2"; this.Label2.Size = new System.Drawing.Size(44, 20); this.Label2.TabIndex = 8; this.Label2.Text = "Height"; this.Label2.UseCompatibleTextRendering = true; // //txt1x // this.txt1x.Location = new System.Drawing.Point(123, 97); this.txt1x.Name = "txt1x"; this.txt1x.Size = new System.Drawing.Size(46, 22); this.txt1x.TabIndex = 4; this.txt1x.Text = "0"; this.txt1x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label3 // this.Label3.AutoSize = true; this.Label3.Location = new System.Drawing.Point(13, 77); this.Label3.Name = "Label3"; this.Label3.Size = new System.Drawing.Size(93, 20); this.Label3.TabIndex = 10; this.Label3.Text = "Base Positions"; this.Label3.UseCompatibleTextRendering = true; // //Label4 // this.Label4.AutoSize = true; this.Label4.Location = new System.Drawing.Point(120, 76); this.Label4.Name = "Label4"; this.Label4.Size = new System.Drawing.Size(12, 20); this.Label4.TabIndex = 12; this.Label4.Text = "x"; this.Label4.UseCompatibleTextRendering = true; // //Label5 // this.Label5.AutoSize = true; this.Label5.Location = new System.Drawing.Point(172, 76); this.Label5.Name = "Label5"; this.Label5.Size = new System.Drawing.Size(12, 20); this.Label5.TabIndex = 13; this.Label5.Text = "y"; this.Label5.UseCompatibleTextRendering = true; // //rdoPlayer2 // this.rdoPlayer2.AutoSize = true; this.rdoPlayer2.Location = new System.Drawing.Point(28, 126); this.rdoPlayer2.Name = "rdoPlayer2"; this.rdoPlayer2.Size = new System.Drawing.Size(75, 21); this.rdoPlayer2.TabIndex = 54; this.rdoPlayer2.Text = "Player 2"; this.rdoPlayer2.UseCompatibleTextRendering = true; this.rdoPlayer2.UseVisualStyleBackColor = true; // //txt1y // this.txt1y.Location = new System.Drawing.Point(175, 96); this.txt1y.Name = "txt1y"; this.txt1y.Size = new System.Drawing.Size(46, 22); this.txt1y.TabIndex = 5; this.txt1y.Text = "0"; this.txt1y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt2y // this.txt2y.Location = new System.Drawing.Point(175, 124); this.txt2y.Name = "txt2y"; this.txt2y.Size = new System.Drawing.Size(46, 22); this.txt2y.TabIndex = 8; this.txt2y.Text = "999"; this.txt2y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt2x // this.txt2x.Location = new System.Drawing.Point(123, 125); this.txt2x.Name = "txt2x"; this.txt2x.Size = new System.Drawing.Size(46, 22); this.txt2x.TabIndex = 7; this.txt2x.Text = "999"; this.txt2x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt3y // this.txt3y.Location = new System.Drawing.Point(175, 152); this.txt3y.Name = "txt3y"; this.txt3y.Size = new System.Drawing.Size(46, 22); this.txt3y.TabIndex = 11; this.txt3y.Text = "0"; this.txt3y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt3x // this.txt3x.Location = new System.Drawing.Point(123, 153); this.txt3x.Name = "txt3x"; this.txt3x.Size = new System.Drawing.Size(46, 22); this.txt3x.TabIndex = 10; this.txt3x.Text = "999"; this.txt3x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer3 // this.rdoPlayer3.AutoSize = true; this.rdoPlayer3.Location = new System.Drawing.Point(28, 154); this.rdoPlayer3.Name = "rdoPlayer3"; this.rdoPlayer3.Size = new System.Drawing.Size(75, 21); this.rdoPlayer3.TabIndex = 55; this.rdoPlayer3.Text = "Player 3"; this.rdoPlayer3.UseCompatibleTextRendering = true; this.rdoPlayer3.UseVisualStyleBackColor = true; // //txt4y // this.txt4y.Location = new System.Drawing.Point(175, 180); this.txt4y.Name = "txt4y"; this.txt4y.Size = new System.Drawing.Size(46, 22); this.txt4y.TabIndex = 14; this.txt4y.Text = "999"; this.txt4y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt4x // this.txt4x.Location = new System.Drawing.Point(123, 181); this.txt4x.Name = "txt4x"; this.txt4x.Size = new System.Drawing.Size(46, 22); this.txt4x.TabIndex = 13; this.txt4x.Text = "0"; this.txt4x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer4 // this.rdoPlayer4.AutoSize = true; this.rdoPlayer4.Checked = true; this.rdoPlayer4.Location = new System.Drawing.Point(28, 182); this.rdoPlayer4.Name = "rdoPlayer4"; this.rdoPlayer4.Size = new System.Drawing.Size(75, 21); this.rdoPlayer4.TabIndex = 56; this.rdoPlayer4.TabStop = true; this.rdoPlayer4.Text = "Player 4"; this.rdoPlayer4.UseCompatibleTextRendering = true; this.rdoPlayer4.UseVisualStyleBackColor = true; // //txt5y // this.txt5y.Location = new System.Drawing.Point(175, 208); this.txt5y.Name = "txt5y"; this.txt5y.Size = new System.Drawing.Size(46, 22); this.txt5y.TabIndex = 17; this.txt5y.Text = "y"; this.txt5y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt5x // this.txt5x.Location = new System.Drawing.Point(123, 209); this.txt5x.Name = "txt5x"; this.txt5x.Size = new System.Drawing.Size(46, 22); this.txt5x.TabIndex = 16; this.txt5x.Text = "x"; this.txt5x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer5 // this.rdoPlayer5.AutoSize = true; this.rdoPlayer5.Location = new System.Drawing.Point(28, 210); this.rdoPlayer5.Name = "rdoPlayer5"; this.rdoPlayer5.Size = new System.Drawing.Size(75, 21); this.rdoPlayer5.TabIndex = 57; this.rdoPlayer5.Text = "Player 5"; this.rdoPlayer5.UseCompatibleTextRendering = true; this.rdoPlayer5.UseVisualStyleBackColor = true; // //txt6y // this.txt6y.Location = new System.Drawing.Point(175, 236); this.txt6y.Name = "txt6y"; this.txt6y.Size = new System.Drawing.Size(46, 22); this.txt6y.TabIndex = 20; this.txt6y.Text = "y"; this.txt6y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt6x // this.txt6x.Location = new System.Drawing.Point(123, 237); this.txt6x.Name = "txt6x"; this.txt6x.Size = new System.Drawing.Size(46, 22); this.txt6x.TabIndex = 19; this.txt6x.Text = "x"; this.txt6x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer6 // this.rdoPlayer6.AutoSize = true; this.rdoPlayer6.Location = new System.Drawing.Point(28, 238); this.rdoPlayer6.Name = "rdoPlayer6"; this.rdoPlayer6.Size = new System.Drawing.Size(75, 21); this.rdoPlayer6.TabIndex = 58; this.rdoPlayer6.Text = "Player 6"; this.rdoPlayer6.UseCompatibleTextRendering = true; this.rdoPlayer6.UseVisualStyleBackColor = true; // //txt7y // this.txt7y.Location = new System.Drawing.Point(175, 264); this.txt7y.Name = "txt7y"; this.txt7y.Size = new System.Drawing.Size(46, 22); this.txt7y.TabIndex = 23; this.txt7y.Text = "y"; this.txt7y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt7x // this.txt7x.Location = new System.Drawing.Point(123, 265); this.txt7x.Name = "txt7x"; this.txt7x.Size = new System.Drawing.Size(46, 22); this.txt7x.TabIndex = 22; this.txt7x.Text = "x"; this.txt7x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer7 // this.rdoPlayer7.AutoSize = true; this.rdoPlayer7.Location = new System.Drawing.Point(28, 266); this.rdoPlayer7.Name = "rdoPlayer7"; this.rdoPlayer7.Size = new System.Drawing.Size(75, 21); this.rdoPlayer7.TabIndex = 59; this.rdoPlayer7.Text = "Player 7"; this.rdoPlayer7.UseCompatibleTextRendering = true; this.rdoPlayer7.UseVisualStyleBackColor = true; // //txt8y // this.txt8y.Location = new System.Drawing.Point(175, 292); this.txt8y.Name = "txt8y"; this.txt8y.Size = new System.Drawing.Size(46, 22); this.txt8y.TabIndex = 26; this.txt8y.Text = "y"; this.txt8y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt8x // this.txt8x.Location = new System.Drawing.Point(123, 293); this.txt8x.Name = "txt8x"; this.txt8x.Size = new System.Drawing.Size(46, 22); this.txt8x.TabIndex = 25; this.txt8x.Text = "x"; this.txt8x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer8 // this.rdoPlayer8.AutoSize = true; this.rdoPlayer8.Location = new System.Drawing.Point(28, 294); this.rdoPlayer8.Name = "rdoPlayer8"; this.rdoPlayer8.Size = new System.Drawing.Size(75, 21); this.rdoPlayer8.TabIndex = 60; this.rdoPlayer8.Text = "Player 8"; this.rdoPlayer8.UseCompatibleTextRendering = true; this.rdoPlayer8.UseVisualStyleBackColor = true; // //Label7 // this.Label7.Location = new System.Drawing.Point(253, 23); this.Label7.Name = "Label7"; this.Label7.Size = new System.Drawing.Size(115, 20); this.Label7.TabIndex = 37; this.Label7.Text = "Height Levels"; this.Label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label7.UseCompatibleTextRendering = true; // //txtLevels // this.txtLevels.Location = new System.Drawing.Point(374, 24); this.txtLevels.Name = "txtLevels"; this.txtLevels.Size = new System.Drawing.Size(46, 22); this.txtLevels.TabIndex = 28; this.txtLevels.Text = "4"; this.txtLevels.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txtLevelFrequency // this.txtLevelFrequency.Location = new System.Drawing.Point(374, 168); this.txtLevelFrequency.Name = "txtLevelFrequency"; this.txtLevelFrequency.Size = new System.Drawing.Size(46, 22); this.txtLevelFrequency.TabIndex = 31; this.txtLevelFrequency.Text = "1"; this.txtLevelFrequency.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label8 // this.Label8.Location = new System.Drawing.Point(282, 167); this.Label8.Name = "Label8"; this.Label8.Size = new System.Drawing.Size(86, 20); this.Label8.TabIndex = 39; this.Label8.Text = "Passages"; this.Label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label8.UseCompatibleTextRendering = true; // //txtRampDistance // this.txtRampDistance.Location = new System.Drawing.Point(129, 41); this.txtRampDistance.Name = "txtRampDistance"; this.txtRampDistance.Size = new System.Drawing.Size(46, 22); this.txtRampDistance.TabIndex = 36; this.txtRampDistance.Text = "80"; this.txtRampDistance.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label9 // this.Label9.Location = new System.Drawing.Point(0, 18); this.Label9.Name = "Label9"; this.Label9.Size = new System.Drawing.Size(176, 20); this.Label9.TabIndex = 41; this.Label9.Text = "Ramp Distance At Base"; this.Label9.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label9.UseCompatibleTextRendering = true; // //txtBaseOil // this.txtBaseOil.Location = new System.Drawing.Point(186, 25); this.txtBaseOil.Name = "txtBaseOil"; this.txtBaseOil.Size = new System.Drawing.Size(46, 22); this.txtBaseOil.TabIndex = 38; this.txtBaseOil.Text = "4"; this.txtBaseOil.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label10 // this.Label10.Location = new System.Drawing.Point(74, 24); this.Label10.Name = "Label10"; this.Label10.Size = new System.Drawing.Size(106, 20); this.Label10.TabIndex = 43; this.Label10.Text = "Oil In Base"; this.Label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label10.UseCompatibleTextRendering = true; // //txtOilElsewhere // this.txtOilElsewhere.Location = new System.Drawing.Point(186, 53); this.txtOilElsewhere.Name = "txtOilElsewhere"; this.txtOilElsewhere.Size = new System.Drawing.Size(46, 22); this.txtOilElsewhere.TabIndex = 39; this.txtOilElsewhere.Text = "40"; this.txtOilElsewhere.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label11 // this.Label11.Location = new System.Drawing.Point(61, 52); this.Label11.Name = "Label11"; this.Label11.Size = new System.Drawing.Size(119, 20); this.Label11.TabIndex = 45; this.Label11.Text = "Oil Elsewhere"; this.Label11.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label11.UseCompatibleTextRendering = true; // //txtOilClusterMin // this.txtOilClusterMin.Location = new System.Drawing.Point(186, 81); this.txtOilClusterMin.Name = "txtOilClusterMin"; this.txtOilClusterMin.Size = new System.Drawing.Size(22, 22); this.txtOilClusterMin.TabIndex = 40; this.txtOilClusterMin.Text = "1"; this.txtOilClusterMin.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label12 // this.Label12.Location = new System.Drawing.Point(18, 80); this.Label12.Name = "Label12"; this.Label12.Size = new System.Drawing.Size(114, 20); this.Label12.TabIndex = 47; this.Label12.Text = "Oil Cluster Size"; this.Label12.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label12.UseCompatibleTextRendering = true; // //Label13 // this.Label13.AutoSize = true; this.Label13.Location = new System.Drawing.Point(150, 84); this.Label13.Name = "Label13"; this.Label13.Size = new System.Drawing.Size(26, 20); this.Label13.TabIndex = 49; this.Label13.Text = "Min"; this.Label13.UseCompatibleTextRendering = true; // //Label14 // this.Label14.AutoSize = true; this.Label14.Location = new System.Drawing.Point(223, 84); this.Label14.Name = "Label14"; this.Label14.Size = new System.Drawing.Size(33, 17); this.Label14.TabIndex = 51; this.Label14.Text = "Max"; // //txtOilClusterMax // this.txtOilClusterMax.Location = new System.Drawing.Point(259, 81); this.txtOilClusterMax.Name = "txtOilClusterMax"; this.txtOilClusterMax.Size = new System.Drawing.Size(22, 22); this.txtOilClusterMax.TabIndex = 41; this.txtOilClusterMax.Text = "1"; this.txtOilClusterMax.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txtBaseLevel // this.txtBaseLevel.Location = new System.Drawing.Point(374, 50); this.txtBaseLevel.Name = "txtBaseLevel"; this.txtBaseLevel.Size = new System.Drawing.Size(46, 22); this.txtBaseLevel.TabIndex = 29; this.txtBaseLevel.Text = "-1"; this.txtBaseLevel.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label17 // this.Label17.Location = new System.Drawing.Point(237, 49); this.Label17.Name = "Label17"; this.Label17.Size = new System.Drawing.Size(131, 20); this.Label17.TabIndex = 58; this.Label17.Text = "Base Height Level"; this.Label17.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label17.UseCompatibleTextRendering = true; // //txtOilDispersion // this.txtOilDispersion.Location = new System.Drawing.Point(186, 109); this.txtOilDispersion.Name = "txtOilDispersion"; this.txtOilDispersion.Size = new System.Drawing.Size(46, 22); this.txtOilDispersion.TabIndex = 42; this.txtOilDispersion.Text = "100"; this.txtOilDispersion.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label18 // this.Label18.Location = new System.Drawing.Point(44, 108); this.Label18.Name = "Label18"; this.Label18.Size = new System.Drawing.Size(136, 20); this.Label18.TabIndex = 60; this.Label18.Text = "Oil Dispersion"; this.Label18.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label18.UseCompatibleTextRendering = true; // //txtFScatterChance // this.txtFScatterChance.Location = new System.Drawing.Point(186, 185); this.txtFScatterChance.Name = "txtFScatterChance"; this.txtFScatterChance.Size = new System.Drawing.Size(46, 22); this.txtFScatterChance.TabIndex = 43; this.txtFScatterChance.Text = "9999"; this.txtFScatterChance.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label19 // this.Label19.Location = new System.Drawing.Point(18, 184); this.Label19.Name = "Label19"; this.Label19.Size = new System.Drawing.Size(162, 20); this.Label19.TabIndex = 62; this.Label19.Text = "Scattered Features"; this.Label19.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label19.UseCompatibleTextRendering = true; // //txtFClusterChance // this.txtFClusterChance.Location = new System.Drawing.Point(186, 240); this.txtFClusterChance.Name = "txtFClusterChance"; this.txtFClusterChance.Size = new System.Drawing.Size(46, 22); this.txtFClusterChance.TabIndex = 44; this.txtFClusterChance.Text = "0"; this.txtFClusterChance.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label20 // this.Label20.Location = new System.Drawing.Point(-4, 239); this.Label20.Name = "Label20"; this.Label20.Size = new System.Drawing.Size(184, 20); this.Label20.TabIndex = 64; this.Label20.Text = "Feature Cluster Chance %"; this.Label20.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label20.UseCompatibleTextRendering = true; // //txtFClusterMin // this.txtFClusterMin.Location = new System.Drawing.Point(186, 292); this.txtFClusterMin.Name = "txtFClusterMin"; this.txtFClusterMin.Size = new System.Drawing.Size(46, 22); this.txtFClusterMin.TabIndex = 45; this.txtFClusterMin.Text = "2"; this.txtFClusterMin.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label21 // this.Label21.Location = new System.Drawing.Point(44, 269); this.Label21.Name = "Label21"; this.Label21.Size = new System.Drawing.Size(164, 20); this.Label21.TabIndex = 66; this.Label21.Text = "Feature Cluster Size"; this.Label21.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label21.UseCompatibleTextRendering = true; // //txtFClusterMax // this.txtFClusterMax.Location = new System.Drawing.Point(186, 320); this.txtFClusterMax.Name = "txtFClusterMax"; this.txtFClusterMax.Size = new System.Drawing.Size(46, 22); this.txtFClusterMax.TabIndex = 46; this.txtFClusterMax.Text = "5"; this.txtFClusterMax.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label22 // this.Label22.Location = new System.Drawing.Point(130, 291); this.Label22.Name = "Label22"; this.Label22.Size = new System.Drawing.Size(50, 20); this.Label22.TabIndex = 68; this.Label22.Text = "Min"; this.Label22.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label22.UseCompatibleTextRendering = true; // //txtTrucks // this.txtTrucks.Location = new System.Drawing.Point(398, 25); this.txtTrucks.Name = "txtTrucks"; this.txtTrucks.Size = new System.Drawing.Size(46, 22); this.txtTrucks.TabIndex = 47; this.txtTrucks.Text = "2"; this.txtTrucks.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label23 // this.Label23.Location = new System.Drawing.Point(284, 24); this.Label23.Name = "Label23"; this.Label23.Size = new System.Drawing.Size(108, 20); this.Label23.TabIndex = 70; this.Label23.Text = "Base Trucks"; this.Label23.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label23.UseCompatibleTextRendering = true; // //Label24 // this.Label24.AutoSize = true; this.Label24.Location = new System.Drawing.Point(24, 22); this.Label24.Name = "Label24"; this.Label24.Size = new System.Drawing.Size(44, 20); this.Label24.TabIndex = 72; this.Label24.Text = "Tileset"; this.Label24.UseCompatibleTextRendering = true; // //cboTileset // this.cboTileset.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboTileset.FormattingEnabled = true; this.cboTileset.Items.AddRange(new object[] {"Arizona", "Urban", "Rockies"}); this.cboTileset.Location = new System.Drawing.Point(80, 19); this.cboTileset.Name = "cboTileset"; this.cboTileset.Size = new System.Drawing.Size(149, 24); this.cboTileset.TabIndex = 27; // //txtFlatness // this.txtFlatness.Location = new System.Drawing.Point(374, 140); this.txtFlatness.Name = "txtFlatness"; this.txtFlatness.Size = new System.Drawing.Size(46, 22); this.txtFlatness.TabIndex = 30; this.txtFlatness.Text = "0"; this.txtFlatness.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label25 // this.Label25.Location = new System.Drawing.Point(312, 139); this.Label25.Name = "Label25"; this.Label25.Size = new System.Drawing.Size(56, 20); this.Label25.TabIndex = 74; this.Label25.Text = "Flats"; this.Label25.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label25.UseCompatibleTextRendering = true; // //txtWaterQuantity // this.txtWaterQuantity.Location = new System.Drawing.Point(374, 238); this.txtWaterQuantity.Name = "txtWaterQuantity"; this.txtWaterQuantity.Size = new System.Drawing.Size(46, 22); this.txtWaterQuantity.TabIndex = 35; this.txtWaterQuantity.Text = "0"; this.txtWaterQuantity.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label26 // this.Label26.Location = new System.Drawing.Point(237, 237); this.Label26.Name = "Label26"; this.Label26.Size = new System.Drawing.Size(131, 20); this.Label26.TabIndex = 78; this.Label26.Text = "Water Spawns"; this.Label26.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label26.UseCompatibleTextRendering = true; // //Label27 // this.Label27.Location = new System.Drawing.Point(121, 319); this.Label27.Name = "Label27"; this.Label27.Size = new System.Drawing.Size(59, 20); this.Label27.TabIndex = 80; this.Label27.Text = "Max"; this.Label27.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label27.UseCompatibleTextRendering = true; // //txtVariation // this.txtVariation.Location = new System.Drawing.Point(374, 196); this.txtVariation.Name = "txtVariation"; this.txtVariation.Size = new System.Drawing.Size(46, 22); this.txtVariation.TabIndex = 32; this.txtVariation.Text = "1"; this.txtVariation.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label28 // this.Label28.Location = new System.Drawing.Point(276, 196); this.Label28.Name = "Label28"; this.Label28.Size = new System.Drawing.Size(92, 20); this.Label28.TabIndex = 81; this.Label28.Text = "Variation"; this.Label28.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label28.UseCompatibleTextRendering = true; // //rdoPlayer1 // this.rdoPlayer1.AutoSize = true; this.rdoPlayer1.Location = new System.Drawing.Point(28, 100); this.rdoPlayer1.Name = "rdoPlayer1"; this.rdoPlayer1.Size = new System.Drawing.Size(75, 21); this.rdoPlayer1.TabIndex = 53; this.rdoPlayer1.Text = "Player 1"; this.rdoPlayer1.UseCompatibleTextRendering = true; this.rdoPlayer1.UseVisualStyleBackColor = true; // //cboSymmetry // this.cboSymmetry.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSymmetry.FormattingEnabled = true; this.cboSymmetry.Items.AddRange(new object[] {"None", "Horizontal Rotation", "Vertical Rotation", "Horizontal Flip", "Vertical Flip", "Quarters Rotation", "Quarters Flip"}); this.cboSymmetry.Location = new System.Drawing.Point(85, 7); this.cboSymmetry.Name = "cboSymmetry"; this.cboSymmetry.Size = new System.Drawing.Size(149, 24); this.cboSymmetry.TabIndex = 0; // //Label6 // this.Label6.AutoSize = true; this.Label6.Location = new System.Drawing.Point(9, 10); this.Label6.Name = "Label6"; this.Label6.Size = new System.Drawing.Size(65, 20); this.Label6.TabIndex = 88; this.Label6.Text = "Symmetry"; this.Label6.UseCompatibleTextRendering = true; // //txtOilAtATime // this.txtOilAtATime.Location = new System.Drawing.Point(186, 137); this.txtOilAtATime.Name = "txtOilAtATime"; this.txtOilAtATime.Size = new System.Drawing.Size(46, 22); this.txtOilAtATime.TabIndex = 89; this.txtOilAtATime.Text = "1"; this.txtOilAtATime.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label31 // this.Label31.Location = new System.Drawing.Point(18, 136); this.Label31.Name = "Label31"; this.Label31.Size = new System.Drawing.Size(162, 20); this.Label31.TabIndex = 90; this.Label31.Text = "Oil Clusters At A Time"; this.Label31.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label31.UseCompatibleTextRendering = true; // //txtRampBase // this.txtRampBase.Location = new System.Drawing.Point(129, 96); this.txtRampBase.Name = "txtRampBase"; this.txtRampBase.Size = new System.Drawing.Size(46, 22); this.txtRampBase.TabIndex = 93; this.txtRampBase.Text = "100"; this.txtRampBase.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label33 // this.Label33.Location = new System.Drawing.Point(-4, 73); this.Label33.Name = "Label33"; this.Label33.Size = new System.Drawing.Size(179, 20); this.Label33.TabIndex = 94; this.Label33.Text = "Ramp Multiplier % Per 8"; this.Label33.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label33.UseCompatibleTextRendering = true; // //txtConnectedWater // this.txtConnectedWater.Location = new System.Drawing.Point(374, 266); this.txtConnectedWater.Name = "txtConnectedWater"; this.txtConnectedWater.Size = new System.Drawing.Size(46, 22); this.txtConnectedWater.TabIndex = 95; this.txtConnectedWater.Text = "0"; this.txtConnectedWater.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label34 // this.Label34.Location = new System.Drawing.Point(237, 265); this.Label34.Name = "Label34"; this.Label34.Size = new System.Drawing.Size(131, 20); this.Label34.TabIndex = 96; this.Label34.Text = "Total Water"; this.Label34.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label34.UseCompatibleTextRendering = true; // //txt9y // this.txt9y.Location = new System.Drawing.Point(175, 320); this.txt9y.Name = "txt9y"; this.txt9y.Size = new System.Drawing.Size(46, 22); this.txt9y.TabIndex = 98; this.txt9y.Text = "y"; this.txt9y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt9x // this.txt9x.Location = new System.Drawing.Point(123, 321); this.txt9x.Name = "txt9x"; this.txt9x.Size = new System.Drawing.Size(46, 22); this.txt9x.TabIndex = 97; this.txt9x.Text = "x"; this.txt9x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer9 // this.rdoPlayer9.AutoSize = true; this.rdoPlayer9.Location = new System.Drawing.Point(28, 322); this.rdoPlayer9.Name = "rdoPlayer9"; this.rdoPlayer9.Size = new System.Drawing.Size(75, 21); this.rdoPlayer9.TabIndex = 99; this.rdoPlayer9.Text = "Player 9"; this.rdoPlayer9.UseCompatibleTextRendering = true; this.rdoPlayer9.UseVisualStyleBackColor = true; // //txt10y // this.txt10y.Location = new System.Drawing.Point(175, 348); this.txt10y.Name = "txt10y"; this.txt10y.Size = new System.Drawing.Size(46, 22); this.txt10y.TabIndex = 101; this.txt10y.Text = "y"; this.txt10y.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //txt10x // this.txt10x.Location = new System.Drawing.Point(123, 349); this.txt10x.Name = "txt10x"; this.txt10x.Size = new System.Drawing.Size(46, 22); this.txt10x.TabIndex = 100; this.txt10x.Text = "x"; this.txt10x.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //rdoPlayer10 // this.rdoPlayer10.AutoSize = true; this.rdoPlayer10.Location = new System.Drawing.Point(28, 350); this.rdoPlayer10.Name = "rdoPlayer10"; this.rdoPlayer10.Size = new System.Drawing.Size(82, 21); this.rdoPlayer10.TabIndex = 102; this.rdoPlayer10.Text = "Player 10"; this.rdoPlayer10.UseCompatibleTextRendering = true; this.rdoPlayer10.UseVisualStyleBackColor = true; // //cbxMasterTexture // this.cbxMasterTexture.AutoSize = true; this.cbxMasterTexture.Location = new System.Drawing.Point(45, 64); this.cbxMasterTexture.Name = "cbxMasterTexture"; this.cbxMasterTexture.Size = new System.Drawing.Size(127, 21); this.cbxMasterTexture.TabIndex = 103; this.cbxMasterTexture.Text = "Master Texturing"; this.cbxMasterTexture.UseCompatibleTextRendering = true; this.cbxMasterTexture.UseVisualStyleBackColor = true; // //txtBaseArea // this.txtBaseArea.Location = new System.Drawing.Point(374, 97); this.txtBaseArea.Name = "txtBaseArea"; this.txtBaseArea.Size = new System.Drawing.Size(46, 22); this.txtBaseArea.TabIndex = 104; this.txtBaseArea.Text = "3"; this.txtBaseArea.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //Label15 // this.Label15.Location = new System.Drawing.Point(249, 97); this.Label15.Name = "Label15"; this.Label15.Size = new System.Drawing.Size(119, 20); this.Label15.TabIndex = 105; this.Label15.Text = "Base Flat Area"; this.Label15.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label15.UseCompatibleTextRendering = true; // //btnGenerateLayout // this.btnGenerateLayout.Location = new System.Drawing.Point(253, 338); this.btnGenerateLayout.Name = "btnGenerateLayout"; this.btnGenerateLayout.Size = new System.Drawing.Size(146, 33); this.btnGenerateLayout.TabIndex = 106; this.btnGenerateLayout.Text = "Generate Layout"; this.btnGenerateLayout.UseCompatibleTextRendering = true; this.btnGenerateLayout.UseVisualStyleBackColor = true; // //btnGenerateObjects // this.btnGenerateObjects.Location = new System.Drawing.Point(271, 348); this.btnGenerateObjects.Name = "btnGenerateObjects"; this.btnGenerateObjects.Size = new System.Drawing.Size(146, 33); this.btnGenerateObjects.TabIndex = 107; this.btnGenerateObjects.Text = "Generate Objects"; this.btnGenerateObjects.UseCompatibleTextRendering = true; this.btnGenerateObjects.UseVisualStyleBackColor = true; // //btnStop // this.btnStop.Location = new System.Drawing.Point(406, 338); this.btnStop.Margin = new System.Windows.Forms.Padding(4); this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(58, 33); this.btnStop.TabIndex = 51; this.btnStop.Text = "Stop"; this.btnStop.UseCompatibleTextRendering = true; this.btnStop.UseVisualStyleBackColor = true; // //lstResult // this.lstResult.FormattingEnabled = true; this.lstResult.ItemHeight = 16; this.lstResult.Location = new System.Drawing.Point(12, 442); this.lstResult.Name = "lstResult"; this.lstResult.Size = new System.Drawing.Size(501, 116); this.lstResult.TabIndex = 108; // //btnGenerateRamps // this.btnGenerateRamps.Location = new System.Drawing.Point(270, 343); this.btnGenerateRamps.Name = "btnGenerateRamps"; this.btnGenerateRamps.Size = new System.Drawing.Size(146, 33); this.btnGenerateRamps.TabIndex = 109; this.btnGenerateRamps.Text = "Generate Ramps"; this.btnGenerateRamps.UseCompatibleTextRendering = true; this.btnGenerateRamps.UseVisualStyleBackColor = true; // //TabControl1 // this.TabControl1.Controls.Add(this.TabPage1); this.TabControl1.Controls.Add(this.TabPage2); this.TabControl1.Controls.Add(this.TabPage4); this.TabControl1.Controls.Add(this.TabPage3); this.TabControl1.Location = new System.Drawing.Point(12, 12); this.TabControl1.Name = "TabControl1"; this.TabControl1.SelectedIndex = 0; this.TabControl1.Size = new System.Drawing.Size(501, 424); this.TabControl1.TabIndex = 110; // //TabPage1 // this.TabPage1.Controls.Add(this.Label6); this.TabPage1.Controls.Add(this.Label1); this.TabPage1.Controls.Add(this.txtWidth); this.TabPage1.Controls.Add(this.Label2); this.TabPage1.Controls.Add(this.btnGenerateLayout); this.TabPage1.Controls.Add(this.btnStop); this.TabPage1.Controls.Add(this.txtHeight); this.TabPage1.Controls.Add(this.txtBaseArea); this.TabPage1.Controls.Add(this.txtConnectedWater); this.TabPage1.Controls.Add(this.Label3); this.TabPage1.Controls.Add(this.Label34); this.TabPage1.Controls.Add(this.Label15); this.TabPage1.Controls.Add(this.txt1x); this.TabPage1.Controls.Add(this.Label4); this.TabPage1.Controls.Add(this.txt10y); this.TabPage1.Controls.Add(this.txtWaterQuantity); this.TabPage1.Controls.Add(this.Label5); this.TabPage1.Controls.Add(this.Label26); this.TabPage1.Controls.Add(this.txt10x); this.TabPage1.Controls.Add(this.rdoPlayer2); this.TabPage1.Controls.Add(this.rdoPlayer10); this.TabPage1.Controls.Add(this.txt1y); this.TabPage1.Controls.Add(this.txtVariation); this.TabPage1.Controls.Add(this.txt9y); this.TabPage1.Controls.Add(this.Label28); this.TabPage1.Controls.Add(this.txt2x); this.TabPage1.Controls.Add(this.txt9x); this.TabPage1.Controls.Add(this.txt2y); this.TabPage1.Controls.Add(this.rdoPlayer9); this.TabPage1.Controls.Add(this.txtFlatness); this.TabPage1.Controls.Add(this.Label25); this.TabPage1.Controls.Add(this.rdoPlayer3); this.TabPage1.Controls.Add(this.txt3x); this.TabPage1.Controls.Add(this.txt3y); this.TabPage1.Controls.Add(this.rdoPlayer4); this.TabPage1.Controls.Add(this.txt4x); this.TabPage1.Controls.Add(this.txt4y); this.TabPage1.Controls.Add(this.rdoPlayer5); this.TabPage1.Controls.Add(this.cboSymmetry); this.TabPage1.Controls.Add(this.txt5x); this.TabPage1.Controls.Add(this.txt5y); this.TabPage1.Controls.Add(this.rdoPlayer1); this.TabPage1.Controls.Add(this.rdoPlayer6); this.TabPage1.Controls.Add(this.txt6x); this.TabPage1.Controls.Add(this.txt6y); this.TabPage1.Controls.Add(this.rdoPlayer7); this.TabPage1.Controls.Add(this.txt7x); this.TabPage1.Controls.Add(this.txt7y); this.TabPage1.Controls.Add(this.rdoPlayer8); this.TabPage1.Controls.Add(this.txt8x); this.TabPage1.Controls.Add(this.txt8y); this.TabPage1.Controls.Add(this.Label7); this.TabPage1.Controls.Add(this.txtLevels); this.TabPage1.Controls.Add(this.Label17); this.TabPage1.Controls.Add(this.txtLevelFrequency); this.TabPage1.Controls.Add(this.txtBaseLevel); this.TabPage1.Controls.Add(this.Label8); this.TabPage1.Location = new System.Drawing.Point(4, 25); this.TabPage1.Name = "TabPage1"; this.TabPage1.Padding = new System.Windows.Forms.Padding(3); this.TabPage1.Size = new System.Drawing.Size(493, 395); this.TabPage1.TabIndex = 0; this.TabPage1.Text = "Layout"; this.TabPage1.UseVisualStyleBackColor = true; // //TabPage2 // this.TabPage2.Controls.Add(this.Label9); this.TabPage2.Controls.Add(this.btnGenerateRamps); this.TabPage2.Controls.Add(this.txtRampDistance); this.TabPage2.Controls.Add(this.Label33); this.TabPage2.Controls.Add(this.txtRampBase); this.TabPage2.Location = new System.Drawing.Point(4, 25); this.TabPage2.Name = "TabPage2"; this.TabPage2.Padding = new System.Windows.Forms.Padding(3); this.TabPage2.Size = new System.Drawing.Size(493, 395); this.TabPage2.TabIndex = 1; this.TabPage2.Text = "Ramps"; this.TabPage2.UseVisualStyleBackColor = true; // //TabPage4 // this.TabPage4.Controls.Add(this.btnGenerateTextures); this.TabPage4.Controls.Add(this.cboTileset); this.TabPage4.Controls.Add(this.Label24); this.TabPage4.Controls.Add(this.cbxMasterTexture); this.TabPage4.Location = new System.Drawing.Point(4, 25); this.TabPage4.Name = "TabPage4"; this.TabPage4.Padding = new System.Windows.Forms.Padding(3); this.TabPage4.Size = new System.Drawing.Size(493, 395); this.TabPage4.TabIndex = 3; this.TabPage4.Text = "Textures"; this.TabPage4.UseVisualStyleBackColor = true; // //btnGenerateTextures // this.btnGenerateTextures.Location = new System.Drawing.Point(253, 342); this.btnGenerateTextures.Name = "btnGenerateTextures"; this.btnGenerateTextures.Size = new System.Drawing.Size(146, 33); this.btnGenerateTextures.TabIndex = 108; this.btnGenerateTextures.Text = "Generate Textures"; this.btnGenerateTextures.UseCompatibleTextRendering = true; this.btnGenerateTextures.UseVisualStyleBackColor = true; // //TabPage3 // this.TabPage3.Controls.Add(this.Label16); this.TabPage3.Controls.Add(this.txtFScatterGap); this.TabPage3.Controls.Add(this.Label10); this.TabPage3.Controls.Add(this.txtBaseOil); this.TabPage3.Controls.Add(this.btnGenerateObjects); this.TabPage3.Controls.Add(this.Label11); this.TabPage3.Controls.Add(this.txtOilElsewhere); this.TabPage3.Controls.Add(this.Label12); this.TabPage3.Controls.Add(this.txtOilClusterMin); this.TabPage3.Controls.Add(this.Label27); this.TabPage3.Controls.Add(this.txtOilAtATime); this.TabPage3.Controls.Add(this.txtTrucks); this.TabPage3.Controls.Add(this.Label13); this.TabPage3.Controls.Add(this.Label23); this.TabPage3.Controls.Add(this.Label31); this.TabPage3.Controls.Add(this.txtFClusterMax); this.TabPage3.Controls.Add(this.txtOilClusterMax); this.TabPage3.Controls.Add(this.Label22); this.TabPage3.Controls.Add(this.Label14); this.TabPage3.Controls.Add(this.txtFClusterMin); this.TabPage3.Controls.Add(this.Label18); this.TabPage3.Controls.Add(this.Label21); this.TabPage3.Controls.Add(this.txtOilDispersion); this.TabPage3.Controls.Add(this.txtFClusterChance); this.TabPage3.Controls.Add(this.Label19); this.TabPage3.Controls.Add(this.Label20); this.TabPage3.Controls.Add(this.txtFScatterChance); this.TabPage3.Location = new System.Drawing.Point(4, 25); this.TabPage3.Name = "TabPage3"; this.TabPage3.Size = new System.Drawing.Size(493, 395); this.TabPage3.TabIndex = 2; this.TabPage3.Text = "Objects"; this.TabPage3.UseVisualStyleBackColor = true; // //Label16 // this.Label16.Location = new System.Drawing.Point(-9, 211); this.Label16.Name = "Label16"; this.Label16.Size = new System.Drawing.Size(189, 20); this.Label16.TabIndex = 109; this.Label16.Text = "Scattered Feature Spacing"; this.Label16.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.Label16.UseCompatibleTextRendering = true; // //txtFScatterGap // this.txtFScatterGap.Location = new System.Drawing.Point(186, 212); this.txtFScatterGap.Name = "txtFScatterGap"; this.txtFScatterGap.Size = new System.Drawing.Size(46, 22); this.txtFScatterGap.TabIndex = 108; this.txtFScatterGap.Text = "4"; this.txtFScatterGap.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // //frmGenerator // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(527, 567); this.Controls.Add(this.TabControl1); this.Controls.Add(this.lstResult); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Margin = new System.Windows.Forms.Padding(4); this.MaximizeBox = false; this.Name = "frmGenerator"; this.Text = "Generator"; this.TabControl1.ResumeLayout(false); this.TabPage1.ResumeLayout(false); this.TabPage1.PerformLayout(); this.TabPage2.ResumeLayout(false); this.TabPage2.PerformLayout(); this.TabPage4.ResumeLayout(false); this.TabPage4.PerformLayout(); this.TabPage3.ResumeLayout(false); this.TabPage3.PerformLayout(); this.ResumeLayout(false); } public System.Windows.Forms.Label Label1; public System.Windows.Forms.TextBox txtWidth; public System.Windows.Forms.TextBox txtHeight; public System.Windows.Forms.Label Label2; public System.Windows.Forms.TextBox txt1x; public System.Windows.Forms.Label Label3; public System.Windows.Forms.Label Label4; public System.Windows.Forms.Label Label5; public System.Windows.Forms.RadioButton rdoPlayer2; public System.Windows.Forms.TextBox txt1y; public System.Windows.Forms.TextBox txt2y; public System.Windows.Forms.TextBox txt2x; public System.Windows.Forms.TextBox txt3y; public System.Windows.Forms.TextBox txt3x; public System.Windows.Forms.RadioButton rdoPlayer3; public System.Windows.Forms.TextBox txt4y; public System.Windows.Forms.TextBox txt4x; public System.Windows.Forms.RadioButton rdoPlayer4; public System.Windows.Forms.TextBox txt5y; public System.Windows.Forms.TextBox txt5x; public System.Windows.Forms.RadioButton rdoPlayer5; public System.Windows.Forms.TextBox txt6y; public System.Windows.Forms.TextBox txt6x; public System.Windows.Forms.RadioButton rdoPlayer6; public System.Windows.Forms.TextBox txt7y; public System.Windows.Forms.TextBox txt7x; public System.Windows.Forms.RadioButton rdoPlayer7; public System.Windows.Forms.TextBox txt8y; public System.Windows.Forms.TextBox txt8x; public System.Windows.Forms.RadioButton rdoPlayer8; public System.Windows.Forms.Label Label7; public System.Windows.Forms.TextBox txtLevels; public System.Windows.Forms.TextBox txtLevelFrequency; public System.Windows.Forms.Label Label8; public System.Windows.Forms.TextBox txtRampDistance; public System.Windows.Forms.Label Label9; public System.Windows.Forms.TextBox txtBaseOil; public System.Windows.Forms.Label Label10; public System.Windows.Forms.TextBox txtOilElsewhere; public System.Windows.Forms.Label Label11; public System.Windows.Forms.TextBox txtOilClusterMin; public System.Windows.Forms.Label Label12; public System.Windows.Forms.Label Label13; public System.Windows.Forms.Label Label14; public System.Windows.Forms.TextBox txtOilClusterMax; public System.Windows.Forms.TextBox txtBaseLevel; public System.Windows.Forms.Label Label17; public System.Windows.Forms.TextBox txtOilDispersion; public System.Windows.Forms.Label Label18; public System.Windows.Forms.TextBox txtFScatterChance; public System.Windows.Forms.Label Label19; public System.Windows.Forms.TextBox txtFClusterChance; public System.Windows.Forms.Label Label20; public System.Windows.Forms.TextBox txtFClusterMin; public System.Windows.Forms.Label Label21; public System.Windows.Forms.TextBox txtFClusterMax; public System.Windows.Forms.Label Label22; public System.Windows.Forms.TextBox txtTrucks; public System.Windows.Forms.Label Label23; public System.Windows.Forms.Label Label24; public System.Windows.Forms.ComboBox cboTileset; public System.Windows.Forms.TextBox txtFlatness; public System.Windows.Forms.Label Label25; public System.Windows.Forms.TextBox txtWaterQuantity; public System.Windows.Forms.Label Label26; public System.Windows.Forms.Label Label27; public System.Windows.Forms.TextBox txtVariation; public System.Windows.Forms.Label Label28; public System.Windows.Forms.RadioButton rdoPlayer1; public System.Windows.Forms.ComboBox cboSymmetry; public System.Windows.Forms.Label Label6; public System.Windows.Forms.TextBox txtOilAtATime; public System.Windows.Forms.Label Label31; public System.Windows.Forms.TextBox txtRampBase; public System.Windows.Forms.Label Label33; public System.Windows.Forms.TextBox txtConnectedWater; public System.Windows.Forms.Label Label34; public System.Windows.Forms.TextBox txt9y; public System.Windows.Forms.TextBox txt9x; public System.Windows.Forms.RadioButton rdoPlayer9; public System.Windows.Forms.TextBox txt10y; public System.Windows.Forms.TextBox txt10x; public System.Windows.Forms.RadioButton rdoPlayer10; public System.Windows.Forms.CheckBox cbxMasterTexture; public System.Windows.Forms.TextBox txtBaseArea; public System.Windows.Forms.Label Label15; internal System.Windows.Forms.Button btnGenerateLayout; internal System.Windows.Forms.Button btnGenerateObjects; public System.Windows.Forms.Button btnStop; internal System.Windows.Forms.ListBox lstResult; internal System.Windows.Forms.Button btnGenerateRamps; internal System.Windows.Forms.TabControl TabControl1; internal System.Windows.Forms.TabPage TabPage1; internal System.Windows.Forms.TabPage TabPage2; internal System.Windows.Forms.TabPage TabPage3; internal System.Windows.Forms.TabPage TabPage4; internal System.Windows.Forms.Button btnGenerateTextures; public System.Windows.Forms.Label Label16; public System.Windows.Forms.TextBox txtFScatterGap; } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace SIL.Windows.Forms.SuperToolTip { [ToolboxItem(false)] public partial class SuperToolTipWindowData : UserControl { #region Private Members int bodyPicWidth = 100; private SuperToolTipInfo _superToolTipInfo; #endregion #region Public Properties public SuperToolTipInfo SuperInfo { get { return _superToolTipInfo; } set { //palaso additions _superToolTipInfo.OffsetForWhereToDisplay = value.OffsetForWhereToDisplay; bool redrawBackground = false; // if (!_superToolTipInfo.Equals(value)) { if (_superToolTipInfo.BackgroundGradientBegin != value.BackgroundGradientBegin) { _superToolTipInfo.BackgroundGradientBegin = value.BackgroundGradientBegin; redrawBackground = true; } if (_superToolTipInfo.BackgroundGradientMiddle != value.BackgroundGradientMiddle) { _superToolTipInfo.BackgroundGradientMiddle = value.BackgroundGradientMiddle; redrawBackground = true; } if (_superToolTipInfo.BackgroundGradientEnd != value.BackgroundGradientEnd) { _superToolTipInfo.BackgroundGradientEnd = value.BackgroundGradientEnd; redrawBackground = true; } if (_superToolTipInfo.BodyImage != value.BodyImage || _superToolTipInfo.BodyForeColor != value.BodyForeColor || _superToolTipInfo.BodyFont != value.BodyFont || _superToolTipInfo.BodyText != value.BodyText) { _superToolTipInfo.BodyImage = value.BodyImage; _superToolTipInfo.BodyForeColor = value.BodyForeColor; _superToolTipInfo.BodyText = value.BodyText; _superToolTipInfo.BodyFont = value.BodyFont; picBody.Visible = _superToolTipInfo.BodyImage == null ? false : true; picBody.Image = _superToolTipInfo.BodyImage; SetBodyData(); } if (value.ShowHeader) { _superToolTipInfo.ShowHeader = value.ShowHeader; if (_superToolTipInfo.HeaderFont != value.HeaderFont || _superToolTipInfo.HeaderText != value.HeaderText || _superToolTipInfo.HeaderForeColor != value.HeaderForeColor || _superToolTipInfo.ShowHeaderSeparator != value.ShowHeaderSeparator) { _superToolTipInfo.HeaderText = value.HeaderText; _superToolTipInfo.HeaderForeColor = value.HeaderForeColor; _superToolTipInfo.HeaderFont = value.HeaderFont; _superToolTipInfo.ShowHeaderSeparator = value.ShowHeaderSeparator; SetHeaderData(); } } lblHeader.Visible = value.ShowHeader; if (value.ShowFooter) { _superToolTipInfo.ShowFooter = value.ShowFooter; if (_superToolTipInfo.FooterFont != value.FooterFont || _superToolTipInfo.FooterText != value.FooterText || _superToolTipInfo.FooterForeColor != value.FooterForeColor || _superToolTipInfo.FooterImage != value.FooterImage || _superToolTipInfo.ShowFooterSeparator != value.ShowFooterSeparator) { _superToolTipInfo.FooterText = value.FooterText; _superToolTipInfo.FooterForeColor = value.FooterForeColor; _superToolTipInfo.FooterFont = value.FooterFont; _superToolTipInfo.FooterImage = value.FooterImage; _superToolTipInfo.ShowFooterSeparator = value.ShowFooterSeparator; picFooter.Visible = _superToolTipInfo.FooterImage == null ? false : true; SetFooterData(); } } flwPnlFooter.Visible = value.ShowFooter; if (redrawBackground) RedrawBackground(); } } } #endregion #region Constructors public SuperToolTipWindowData() { InitializeComponent(); _superToolTipInfo = new SuperToolTipInfo(); } #endregion #region Painting protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Rectangle rect1 = new Rectangle(0, Height / 2, Width, Height / 2); Rectangle rect2 = new Rectangle(0, 0, Width, Height / 2); using (LinearGradientBrush b2 = new LinearGradientBrush(new Rectangle(0, Height / 2 - 1, Width, Height / 2), _superToolTipInfo.BackgroundGradientMiddle, _superToolTipInfo.BackgroundGradientEnd, LinearGradientMode.Vertical)) using (LinearGradientBrush b1 = new LinearGradientBrush(new Rectangle(0, 0, Width, Height / 2), _superToolTipInfo.BackgroundGradientBegin, _superToolTipInfo.BackgroundGradientMiddle, LinearGradientMode.Vertical)) { e.Graphics.FillRectangle(b2, rect1); e.Graphics.FillRectangle(b1, rect2); } } #endregion #region Helpers private void RedrawBackground() { } private void SetHeaderData() { lblHeader.Text = _superToolTipInfo.HeaderText; lblHeader.ForeColor = _superToolTipInfo.HeaderForeColor; lblHeader.Font = _superToolTipInfo.HeaderFont; lblHeader.Visible = _superToolTipInfo.ShowHeader; pnlHeaderSeparator.Invalidate(); pnlHeaderSeparator.Visible = _superToolTipInfo.ShowHeader; } private void SetFooterData() { lblFooter.Text = _superToolTipInfo.FooterText; lblFooter.Font = _superToolTipInfo.FooterFont; lblFooter.ForeColor = _superToolTipInfo.FooterForeColor; if (_superToolTipInfo.FooterImage != null) { picFooter.Image = _superToolTipInfo.FooterImage; } pnlFooterSeparator.Invalidate(); flwPnlFooter.Visible = _superToolTipInfo.ShowFooter; pnlFooterSeparator.Visible = _superToolTipInfo.ShowFooter; } private void SetBodyData() { lblBody.Text = _superToolTipInfo.BodyText; lblBody.Font = _superToolTipInfo.BodyFont; lblBody.ForeColor = _superToolTipInfo.BodyForeColor; if (_superToolTipInfo.BodyImage != null) { picBody.Image = _superToolTipInfo.BodyImage; int height = _superToolTipInfo.BodyImage.Height * bodyPicWidth / _superToolTipInfo.BodyImage.Width; picBody.Size = new Size(picBody.Size.Width, height); } //jh lblBody.MaximumSize = new Size(200, 1000); } #endregion private void pnlHeaderSeparator_Paint(object sender, PaintEventArgs e) { if (_superToolTipInfo.ShowHeader && _superToolTipInfo.ShowHeaderSeparator) { DrawSeparator(e.Graphics, pnlHeaderSeparator); } } private void pnlFooterSeparator_Paint(object sender, PaintEventArgs e) { if (_superToolTipInfo.ShowFooter && _superToolTipInfo.ShowFooterSeparator) { DrawSeparator(e.Graphics, pnlFooterSeparator); } } private void DrawSeparator(Graphics graphics, Panel p) { graphics.DrawLine(Pens.White, new Point(0, p.Height / 2), new Point(p.Width, p.Height / 2)); graphics.DrawLine(Pens.Black, new Point(0, p.Height / 2 + 1), new Point(p.Width, p.Height / 2 + 1)); } protected override void OnSizeChanged(EventArgs e) { pnlHeaderSeparator.Width = this.Width * 95 / 100; pnlFooterSeparator.Width = this.Width * 95 / 100; base.OnSizeChanged(e); } } }
// // 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.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.RecoveryServices; using Microsoft.Azure.Management.SiteRecovery.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices { /// <summary> /// Definition of vault extended info operations for the Site Recovery /// extension. /// </summary> internal partial class VaultExtendedInfoOperations : IServiceOperations<RecoveryServicesManagementClient>, IVaultExtendedInfoOperations { /// <summary> /// Initializes a new instance of the VaultExtendedInfoOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VaultExtendedInfoOperations(RecoveryServicesManagementClient client) { this._client = client; } private RecoveryServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.RecoveryServicesManagementClient. /// </summary> public RecoveryServicesManagementClient Client { get { return this._client; } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Required. Create resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </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> CreateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs == null) { throw new ArgumentNullException("extendedInfoArgs"); } if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } // 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("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CreateExtendedInfoAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); 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 httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject resourceExtendedInformationArgsValue = new JObject(); requestDoc = resourceExtendedInformationArgsValue; resourceExtendedInformationArgsValue["ContractVersion"] = extendedInfoArgs.ContractVersion; resourceExtendedInformationArgsValue["ExtendedInfo"] = extendedInfoArgs.ExtendedInfo; resourceExtendedInformationArgsValue["ExtendedInfoETag"] = extendedInfoArgs.ExtendedInfoETag; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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.BadRequest) { 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> GetExtendedInfoAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // 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("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetExtendedInfoAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); 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 httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["ResourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["ExtendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["ExtendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["ResourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["ResourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["SubscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } 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> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Optional. Update resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs != null) { if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } } // 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("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateExtendedInfoAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["ResourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["ExtendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["ExtendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["ResourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["ResourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["SubscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } 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> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='parameters'> /// Required. Upload Vault Certificate input parameters. /// </param> /// <param name='certFriendlyName'> /// Required. Certificate friendly name /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the upload certificate response /// </returns> public async Task<UploadCertificateResponse> UploadCertificateAsync(string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (certFriendlyName == null) { throw new ArgumentNullException("certFriendlyName"); } // 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("resourceName", resourceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("certFriendlyName", certFriendlyName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UploadCertificateAsync", 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 + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certFriendlyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); 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 httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject parametersValue = new JObject(); requestDoc = parametersValue; if (parameters.Properties != null) { if (parameters.Properties is ILazyCollection == false || ((ILazyCollection)parameters.Properties).IsInitialized) { JObject propertiesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties) { string propertiesKey = pair.Key; string propertiesValue = pair.Value; propertiesDictionary[propertiesKey] = propertiesValue; } parametersValue["properties"] = propertiesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UploadCertificateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UploadCertificateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { CertificateProperties propertiesInstance = new CertificateProperties(); result.Properties = propertiesInstance; JToken friendlyNameValue = propertiesValue2["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); propertiesInstance.FriendlyName = friendlyNameInstance; } JToken globalAcsHostNameValue = propertiesValue2["globalAcsHostName"]; if (globalAcsHostNameValue != null && globalAcsHostNameValue.Type != JTokenType.Null) { string globalAcsHostNameInstance = ((string)globalAcsHostNameValue); propertiesInstance.GlobalAcsHostName = globalAcsHostNameInstance; } JToken globalAcsNamespaceValue = propertiesValue2["globalAcsNamespace"]; if (globalAcsNamespaceValue != null && globalAcsNamespaceValue.Type != JTokenType.Null) { string globalAcsNamespaceInstance = ((string)globalAcsNamespaceValue); propertiesInstance.GlobalAcsNamespace = globalAcsNamespaceInstance; } JToken globalAcsRPRealmValue = propertiesValue2["globalAcsRPRealm"]; if (globalAcsRPRealmValue != null && globalAcsRPRealmValue.Type != JTokenType.Null) { string globalAcsRPRealmInstance = ((string)globalAcsRPRealmValue); propertiesInstance.GlobalAcsRPRealm = globalAcsRPRealmInstance; } JToken resourceIdValue = propertiesValue2["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, GetProcessIds()); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { return IsProcessRunning(processId, GetProcessIds(machineName)); } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } return null; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, true) : NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ModuleInfo[] GetModuleInfos(int processId) { return NtProcessManager.GetModuleInfos(processId); } /// <summary>Gets whether the named machine is remote or local.</summary> /// <param name="machineName">The machine name.</param> /// <returns>true if the machine is remote; false if it's local.</returns> public static bool IsRemoteMachine(string machineName) { if (machineName == null) throw new ArgumentNullException("machineName"); if (machineName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, "machineName", machineName)); string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; if (String.Compare(Interop.mincore.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase) == 0) return false; return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.mincore.LUID luid = new Interop.mincore.LUID(); if (!Interop.mincore.LookupPrivilegeValue(null, Interop.mincore.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.mincore.OpenProcessToken( Interop.mincore.GetCurrentProcess(), Interop.mincore.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.mincore.TokenPrivileges tp = new Interop.mincore.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.mincore.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.mincore.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } private static bool IsProcessRunning(int processId, int[] processIds) { return Array.IndexOf(processIds, processId) >= 0; } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.mincore.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.mincore.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.mincore.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static Dictionary<String, ValueId> s_valueIds; static NtProcessManager() { s_valueIds = new Dictionary<String, ValueId>(); s_valueIds.Add("Handle Count", ValueId.HandleCount); s_valueIds.Add("Pool Paged Bytes", ValueId.PoolPagedBytes); s_valueIds.Add("Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes); s_valueIds.Add("Elapsed Time", ValueId.ElapsedTime); s_valueIds.Add("Virtual Bytes Peak", ValueId.VirtualBytesPeak); s_valueIds.Add("Virtual Bytes", ValueId.VirtualBytes); s_valueIds.Add("Private Bytes", ValueId.PrivateBytes); s_valueIds.Add("Page File Bytes", ValueId.PageFileBytes); s_valueIds.Add("Page File Bytes Peak", ValueId.PageFileBytesPeak); s_valueIds.Add("Working Set Peak", ValueId.WorkingSetPeak); s_valueIds.Add("Working Set", ValueId.WorkingSet); s_valueIds.Add("ID Thread", ValueId.ThreadId); s_valueIds.Add("ID Process", ValueId.ProcessId); s_valueIds.Add("Priority Base", ValueId.BasePriority); s_valueIds.Add("Priority Current", ValueId.CurrentPriority); s_valueIds.Add("% User Time", ValueId.UserTime); s_valueIds.Add("% Privileged Time", ValueId.PrivilegedTime); s_valueIds.Add("Start Address", ValueId.StartAddress); s_valueIds.Add("Thread State", ValueId.ThreadState); s_valueIds.Add("Thread Wait Reason", ValueId.ThreadWaitReason); } internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.mincore.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, ids, ids.Length); return ids; } public static ModuleInfo[] GetModuleInfos(int processId) { return GetModuleInfos(processId, false); } public static ModuleInfo GetFirstModuleInfo(int processId) { ModuleInfo[] moduleInfos = GetModuleInfos(processId, true); if (moduleInfos.Length == 0) { return null; } else { return moduleInfos[0]; } } private static ModuleInfo[] GetModuleInfos(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.mincore.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.mincore.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ; ) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.mincore.GetCurrentProcessId()), Interop.mincore.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.mincore.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.mincore.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.mincore.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.mincore.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } List<ModuleInfo> moduleInfos = new List<ModuleInfo>(); int ret; for (int i = 0; i < moduleCount; i++) { try { ModuleInfo moduleInfo = new ModuleInfo(); IntPtr moduleHandle = moduleHandles[i]; Interop.mincore.NtModuleInfo ntModuleInfo = new Interop.mincore.NtModuleInfo(); if (!Interop.mincore.GetModuleInformation(processHandle, moduleHandle, ntModuleInfo, Marshal.SizeOf(ntModuleInfo))) throw new Win32Exception(); moduleInfo._sizeOfImage = ntModuleInfo.SizeOfImage; moduleInfo._entryPoint = ntModuleInfo.EntryPoint; moduleInfo._baseOfDll = ntModuleInfo.BaseOfDll; StringBuilder baseName = new StringBuilder(1024); ret = Interop.mincore.GetModuleBaseName(processHandle, moduleHandle, baseName, baseName.Capacity * 2); if (ret == 0) throw new Win32Exception(); moduleInfo._baseName = baseName.ToString(); StringBuilder fileName = new StringBuilder(1024); ret = Interop.mincore.GetModuleFileNameEx(processHandle, moduleHandle, fileName, fileName.Capacity * 2); if (ret == 0) throw new Win32Exception(); moduleInfo._fileName = fileName.ToString(); if (moduleInfo._fileName != null && moduleInfo._fileName.Length >= 4 && moduleInfo._fileName.StartsWith(@"\\?\", StringComparison.Ordinal)) { moduleInfo._fileName = moduleInfo._fileName.Substring(4); } moduleInfos.Add(moduleInfo); } catch (Win32Exception e) { if (e.NativeErrorCode == Interop.mincore.Errors.ERROR_INVALID_HANDLE || e.NativeErrorCode == Interop.mincore.Errors.ERROR_PARTIAL_COPY) { // It's possible that another thread casued this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. } else { throw; } } // // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. // if (firstModuleOnly) { break; } } ModuleInfo[] temp = new ModuleInfo[moduleInfos.Count]; moduleInfos.CopyTo(temp, 0); return temp; } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo(); int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null); if (status != 0) { throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status)); } // We should change the signature of this function and ID property in process class. return info.UniqueProcessId.ToInt32(); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.mincore.PERF_DATA_BLOCK dataBlock = new Interop.mincore.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.mincore.PERF_INSTANCE_DEFINITION instance = new Interop.mincore.PERF_INSTANCE_DEFINITION(); Interop.mincore.PERF_COUNTER_BLOCK counterBlock = new Interop.mincore.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.mincore.PERF_OBJECT_TYPE type = new Interop.mincore.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.mincore.PERF_COUNTER_DEFINITION> counterList = new List<Interop.mincore.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = new Interop.mincore.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.mincore.PERF_COUNTER_DEFINITION[] counters = new Interop.mincore.PERF_COUNTER_DEFINITION[counterList.Count]; counterList.CopyTo(counters, 0); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpfull to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (int)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.mincore.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.mincore.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.mincore.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.HandleCount: processInfo.HandleCount = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.mincore.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, HandleCount, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } public static ProcessInfo[] GetProcessInfos() { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while ((uint)status == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject()); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; static ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); SystemProcessInformation pi = new SystemProcessInformation(); Marshal.PtrToStructure(currentPtr, pi); // get information for a process ProcessInfo processInfo = new ProcessInfo(); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. processInfo.ProcessId = pi.UniqueProcessId.ToInt32(); processInfo.HandleCount = (int)pi.HandleCount; processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; if (pi.NamePtr == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { SystemThreadInformation ti = new SystemThreadInformation(); Marshal.PtrToStructure(currentPtr, ti); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.UniqueProcess; threadInfo._threadId = (int)ti.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal class SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private long _SpareLi1; private long _SpareLi2; private long _SpareLi3; private long _CreateTime; private long _UserTime; private long _KernelTime; internal ushort NameLength; // UNICODE_STRING internal ushort MaximumNameLength; internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation internal int BasePriority; internal IntPtr UniqueProcessId; internal IntPtr InheritedFromUniqueProcessId; internal uint HandleCount; internal uint SessionId; internal UIntPtr PageDirectoryBase; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; internal uint PageFaultCount; internal UIntPtr PeakWorkingSetSize; internal UIntPtr WorkingSetSize; internal UIntPtr QuotaPeakPagedPoolUsage; internal UIntPtr QuotaPagedPoolUsage; internal UIntPtr QuotaPeakNonPagedPoolUsage; internal UIntPtr QuotaNonPagedPoolUsage; internal UIntPtr PagefileUsage; internal UIntPtr PeakPagefileUsage; internal UIntPtr PrivatePageCount; private long _ReadOperationCount; private long _WriteOperationCount; private long _OtherOperationCount; private long _ReadTransferCount; private long _WriteTransferCount; private long _OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] internal class SystemThreadInformation { private long _KernelTime; private long _UserTime; private long _CreateTime; private uint _WaitTime; internal IntPtr StartAddress; internal IntPtr UniqueProcess; internal IntPtr UniqueThread; internal int Priority; internal int BasePriority; internal uint ContextSwitches; internal uint ThreadState; internal uint WaitReason; } } }
using Godot; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using GodotTools.Core; using GodotTools.Internals; using JetBrains.Annotations; using static GodotTools.Internals.Globals; using Directory = GodotTools.Utils.Directory; using File = GodotTools.Utils.File; using OS = GodotTools.Utils.OS; using Path = System.IO.Path; namespace GodotTools.Export { public class ExportPlugin : EditorExportPlugin { [Flags] enum I18NCodesets : long { None = 0, CJK = 1, MidEast = 2, Other = 4, Rare = 8, West = 16, All = CJK | MidEast | Other | Rare | West } private void AddI18NAssemblies(Godot.Collections.Dictionary<string, string> assemblies, string bclDir) { var codesets = (I18NCodesets)ProjectSettings.GetSetting("mono/export/i18n_codesets"); if (codesets == I18NCodesets.None) return; void AddI18NAssembly(string name) => assemblies.Add(name, Path.Combine(bclDir, $"{name}.dll")); AddI18NAssembly("I18N"); if ((codesets & I18NCodesets.CJK) != 0) AddI18NAssembly("I18N.CJK"); if ((codesets & I18NCodesets.MidEast) != 0) AddI18NAssembly("I18N.MidEast"); if ((codesets & I18NCodesets.Other) != 0) AddI18NAssembly("I18N.Other"); if ((codesets & I18NCodesets.Rare) != 0) AddI18NAssembly("I18N.Rare"); if ((codesets & I18NCodesets.West) != 0) AddI18NAssembly("I18N.West"); } public void RegisterExportSettings() { // TODO: These would be better as export preset options, but that doesn't seem to be supported yet GlobalDef("mono/export/include_scripts_content", false); GlobalDef("mono/export/export_assemblies_inside_pck", true); GlobalDef("mono/export/i18n_codesets", I18NCodesets.All); ProjectSettings.AddPropertyInfo(new Godot.Collections.Dictionary { ["type"] = Variant.Type.Int, ["name"] = "mono/export/i18n_codesets", ["hint"] = PropertyHint.Flags, ["hint_string"] = "CJK,MidEast,Other,Rare,West" }); GlobalDef("mono/export/aot/enabled", false); GlobalDef("mono/export/aot/full_aot", false); GlobalDef("mono/export/aot/use_interpreter", true); // --aot or --aot=opt1,opt2 (use 'mono --aot=help AuxAssembly.dll' to list AOT options) GlobalDef("mono/export/aot/extra_aot_options", new string[] { }); // --optimize/-O=opt1,opt2 (use 'mono --list-opt'' to list optimize options) GlobalDef("mono/export/aot/extra_optimizer_options", new string[] { }); GlobalDef("mono/export/aot/android_toolchain_path", ""); } private string maybeLastExportError; private void AddFile(string srcPath, string dstPath, bool remap = false) { // Add file to the PCK AddFile(dstPath.Replace("\\", "/"), File.ReadAllBytes(srcPath), remap); } // With this method we can override how a file is exported in the PCK public override void _ExportFile(string path, string type, string[] features) { base._ExportFile(path, type, features); if (type != Internal.CSharpLanguageType) return; if (Path.GetExtension(path) != Internal.CSharpLanguageExtension) throw new ArgumentException($"Resource of type {Internal.CSharpLanguageType} has an invalid file extension: {path}", nameof(path)); // TODO What if the source file is not part of the game's C# project bool includeScriptsContent = (bool)ProjectSettings.GetSetting("mono/export/include_scripts_content"); if (!includeScriptsContent) { // We don't want to include the source code on exported games. // Sadly, Godot prints errors when adding an empty file (nothing goes wrong, it's just noise). // Because of this, we add a file which contains a line break. AddFile(path, System.Text.Encoding.UTF8.GetBytes("\n"), remap: false); // Tell the Godot exporter that we already took care of the file Skip(); } } public override void _ExportBegin(string[] features, bool isDebug, string path, int flags) { base._ExportBegin(features, isDebug, path, flags); try { _ExportBeginImpl(features, isDebug, path, flags); } catch (Exception e) { maybeLastExportError = e.Message; // 'maybeLastExportError' cannot be null or empty if there was an error, so we // must consider the possibility of exceptions being thrown without a message. if (string.IsNullOrEmpty(maybeLastExportError)) maybeLastExportError = $"Exception thrown: {e.GetType().Name}"; GD.PushError($"Failed to export project: {maybeLastExportError}"); Console.Error.WriteLine(e); // TODO: Do something on error once _ExportBegin supports failing. } } private void _ExportBeginImpl(string[] features, bool isDebug, string path, int flags) { if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) return; if (!DeterminePlatformFromFeatures(features, out string platform)) throw new NotSupportedException("Target platform not supported"); string outputDir = new FileInfo(path).Directory?.FullName ?? throw new FileNotFoundException("Base directory not found"); string buildConfig = isDebug ? "ExportDebug" : "ExportRelease"; string scriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, $"scripts_metadata.{(isDebug ? "debug" : "release")}"); CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, scriptsMetadataPath); AddFile(scriptsMetadataPath, scriptsMetadataPath); if (!BuildManager.BuildProjectBlocking(buildConfig, platform)) throw new Exception("Failed to build project"); // Add dependency assemblies var assemblies = new Godot.Collections.Dictionary<string, string>(); string projectDllName = GodotSharpEditor.ProjectAssemblyName; string projectDllSrcDir = Path.Combine(GodotSharpDirs.ResTempAssembliesBaseDir, buildConfig); string projectDllSrcPath = Path.Combine(projectDllSrcDir, $"{projectDllName}.dll"); assemblies[projectDllName] = projectDllSrcPath; if (platform == OS.Platforms.Android) { string godotAndroidExtProfileDir = GetBclProfileDir("godot_android_ext"); string monoAndroidAssemblyPath = Path.Combine(godotAndroidExtProfileDir, "Mono.Android.dll"); if (!File.Exists(monoAndroidAssemblyPath)) throw new FileNotFoundException("Assembly not found: 'Mono.Android'", monoAndroidAssemblyPath); assemblies["Mono.Android"] = monoAndroidAssemblyPath; } string bclDir = DeterminePlatformBclDir(platform); var initialAssemblies = assemblies.Duplicate(); internal_GetExportedAssemblyDependencies(initialAssemblies, buildConfig, bclDir, assemblies); AddI18NAssemblies(assemblies, bclDir); string outputDataDir = null; if (PlatformHasTemplateDir(platform)) outputDataDir = ExportDataDirectory(features, platform, isDebug, outputDir); string apiConfig = isDebug ? "Debug" : "Release"; string resAssembliesDir = Path.Combine(GodotSharpDirs.ResAssembliesBaseDir, apiConfig); bool assembliesInsidePck = (bool)ProjectSettings.GetSetting("mono/export/export_assemblies_inside_pck") || outputDataDir == null; if (!assembliesInsidePck) { string outputDataGameAssembliesDir = Path.Combine(outputDataDir, "Assemblies"); if (!Directory.Exists(outputDataGameAssembliesDir)) Directory.CreateDirectory(outputDataGameAssembliesDir); } foreach (var assembly in assemblies) { void AddToAssembliesDir(string fileSrcPath) { if (assembliesInsidePck) { string fileDstPath = Path.Combine(resAssembliesDir, fileSrcPath.GetFile()); AddFile(fileSrcPath, fileDstPath); } else { Debug.Assert(outputDataDir != null); string fileDstPath = Path.Combine(outputDataDir, "Assemblies", fileSrcPath.GetFile()); File.Copy(fileSrcPath, fileDstPath); } } string assemblySrcPath = assembly.Value; string assemblyPathWithoutExtension = Path.ChangeExtension(assemblySrcPath, null); string pdbSrcPath = assemblyPathWithoutExtension + ".pdb"; AddToAssembliesDir(assemblySrcPath); if (File.Exists(pdbSrcPath)) AddToAssembliesDir(pdbSrcPath); } // AOT compilation bool aotEnabled = platform == OS.Platforms.iOS || (bool)ProjectSettings.GetSetting("mono/export/aot/enabled"); if (aotEnabled) { string aotToolchainPath = null; if (platform == OS.Platforms.Android) aotToolchainPath = (string)ProjectSettings.GetSetting("mono/export/aot/android_toolchain_path"); if (aotToolchainPath == string.Empty) aotToolchainPath = null; // Don't risk it being used as current working dir // TODO: LLVM settings are hard-coded and disabled for now var aotOpts = new AotOptions { EnableLLVM = false, LLVMOnly = false, LLVMPath = "", LLVMOutputPath = "", FullAot = platform == OS.Platforms.iOS || (bool)(ProjectSettings.GetSetting("mono/export/aot/full_aot") ?? false), UseInterpreter = (bool)ProjectSettings.GetSetting("mono/export/aot/use_interpreter"), ExtraAotOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_aot_options") ?? new string[] { }, ExtraOptimizerOptions = (string[])ProjectSettings.GetSetting("mono/export/aot/extra_optimizer_options") ?? new string[] { }, ToolchainPath = aotToolchainPath }; AotBuilder.CompileAssemblies(this, aotOpts, features, platform, isDebug, bclDir, outputDir, outputDataDir, assemblies); } } public override void _ExportEnd() { base._ExportEnd(); string aotTempDir = Path.Combine(Path.GetTempPath(), $"godot-aot-{Process.GetCurrentProcess().Id}"); if (Directory.Exists(aotTempDir)) Directory.Delete(aotTempDir, recursive: true); // TODO: Just a workaround until the export plugins can be made to abort with errors if (!string.IsNullOrEmpty(maybeLastExportError)) // Check empty as well, because it's set to empty after hot-reloading { string lastExportError = maybeLastExportError; maybeLastExportError = null; GodotSharpEditor.Instance.ShowErrorDialog(lastExportError, "Failed to export C# project"); } } [NotNull] private static string ExportDataDirectory(string[] features, string platform, bool isDebug, string outputDir) { string target = isDebug ? "release_debug" : "release"; // NOTE: Bits is ok for now as all platforms with a data directory only have one or two architectures. // However, this may change in the future if we add arm linux or windows desktop templates. string bits = features.Contains("64") ? "64" : "32"; string TemplateDirName() => $"data.mono.{platform}.{bits}.{target}"; string templateDirPath = Path.Combine(Internal.FullTemplatesDir, TemplateDirName()); bool validTemplatePathFound = true; if (!Directory.Exists(templateDirPath)) { validTemplatePathFound = false; if (isDebug) { target = "debug"; // Support both 'release_debug' and 'debug' for the template data directory name templateDirPath = Path.Combine(Internal.FullTemplatesDir, TemplateDirName()); validTemplatePathFound = true; if (!Directory.Exists(templateDirPath)) validTemplatePathFound = false; } } if (!validTemplatePathFound) throw new FileNotFoundException("Data template directory not found", templateDirPath); string outputDataDir = Path.Combine(outputDir, DetermineDataDirNameForProject()); if (Directory.Exists(outputDataDir)) Directory.Delete(outputDataDir, recursive: true); // Clean first Directory.CreateDirectory(outputDataDir); foreach (string dir in Directory.GetDirectories(templateDirPath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(Path.Combine(outputDataDir, dir.Substring(templateDirPath.Length + 1))); } foreach (string file in Directory.GetFiles(templateDirPath, "*", SearchOption.AllDirectories)) { File.Copy(file, Path.Combine(outputDataDir, file.Substring(templateDirPath.Length + 1))); } return outputDataDir; } private static bool PlatformHasTemplateDir(string platform) { // OSX export templates are contained in a zip, so we place our custom template inside it and let Godot do the rest. return !new[] {OS.Platforms.OSX, OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5}.Contains(platform); } private static bool DeterminePlatformFromFeatures(IEnumerable<string> features, out string platform) { foreach (var feature in features) { if (OS.PlatformNameMap.TryGetValue(feature, out platform)) return true; } platform = null; return false; } private static string GetBclProfileDir(string profile) { string templatesDir = Internal.FullTemplatesDir; return Path.Combine(templatesDir, "bcl", profile); } private static string DeterminePlatformBclDir(string platform) { string templatesDir = Internal.FullTemplatesDir; string platformBclDir = Path.Combine(templatesDir, "bcl", platform); if (!File.Exists(Path.Combine(platformBclDir, "mscorlib.dll"))) { string profile = DeterminePlatformBclProfile(platform); platformBclDir = Path.Combine(templatesDir, "bcl", profile); if (!File.Exists(Path.Combine(platformBclDir, "mscorlib.dll"))) { if (PlatformRequiresCustomBcl(platform)) throw new FileNotFoundException($"Missing BCL (Base Class Library) for platform: {platform}"); platformBclDir = typeof(object).Assembly.Location.GetBaseDir(); // Use the one we're running on } } return platformBclDir; } /// <summary> /// Determines whether the BCL bundled with the Godot editor can be used for the target platform, /// or if it requires a custom BCL that must be distributed with the export templates. /// </summary> private static bool PlatformRequiresCustomBcl(string platform) { if (new[] {OS.Platforms.Android, OS.Platforms.iOS, OS.Platforms.HTML5}.Contains(platform)) return true; // The 'net_4_x' BCL is not compatible between Windows and the other platforms. // We use the names 'net_4_x_win' and 'net_4_x' to differentiate between the two. bool isWinOrUwp = new[] { OS.Platforms.Windows, OS.Platforms.UWP }.Contains(platform); return OS.IsWindows ? !isWinOrUwp : isWinOrUwp; } private static string DeterminePlatformBclProfile(string platform) { switch (platform) { case OS.Platforms.Windows: case OS.Platforms.UWP: return "net_4_x_win"; case OS.Platforms.OSX: case OS.Platforms.LinuxBSD: case OS.Platforms.Server: case OS.Platforms.Haiku: return "net_4_x"; case OS.Platforms.Android: return "monodroid"; case OS.Platforms.iOS: return "monotouch"; case OS.Platforms.HTML5: return "wasm"; default: throw new NotSupportedException($"Platform not supported: {platform}"); } } private static string DetermineDataDirNameForProject() { var appName = (string)ProjectSettings.GetSetting("application/config/name"); string appNameSafe = appName.ToSafeDirName(); return $"data_{appNameSafe}"; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void internal_GetExportedAssemblyDependencies(Godot.Collections.Dictionary<string, string> initialAssemblies, string buildConfig, string customBclDir, Godot.Collections.Dictionary<string, string> dependencyAssemblies); } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Drawing; using System.Drawing.Drawing2D; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.WinForms.Utilities; namespace TheArtOfDev.HtmlRenderer.WinForms.Adapters { /// <summary> /// Adapter for WinForms Graphics for core. /// </summary> internal sealed class GraphicsAdapter : RGraphics { #region Fields and Consts /// <summary> /// used for <see cref="MeasureString(string,RFont,double,out int,out double)"/> calculation. /// </summary> private static readonly int[] _charFit = new int[1]; /// <summary> /// used for <see cref="MeasureString(string,RFont,double,out int,out double)"/> calculation. /// </summary> private static readonly int[] _charFitWidth = new int[1000]; /// <summary> /// Used for GDI+ measure string. /// </summary> private static readonly CharacterRange[] _characterRanges = new CharacterRange[1]; /// <summary> /// The string format to use for measuring strings for GDI+ text rendering /// </summary> private static readonly StringFormat _stringFormat; /// <summary> /// The string format to use for rendering strings for GDI+ text rendering /// </summary> private static readonly StringFormat _stringFormat2; /// <summary> /// The wrapped WinForms graphics object /// </summary> private readonly Graphics _g; /// <summary> /// Use GDI+ text rendering to measure/draw text. /// </summary> private readonly bool _useGdiPlusTextRendering; #if !MONO /// <summary> /// the initialized HDC used /// </summary> private IntPtr _hdc; #endif /// <summary> /// if to release the graphics object on dispose /// </summary> private readonly bool _releaseGraphics; /// <summary> /// If text alignment was set to RTL /// </summary> private bool _setRtl; #endregion /// <summary> /// Init static resources. /// </summary> static GraphicsAdapter() { _stringFormat = new StringFormat(StringFormat.GenericTypographic); _stringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.MeasureTrailingSpaces; _stringFormat2 = new StringFormat(StringFormat.GenericTypographic); } /// <summary> /// Init. /// </summary> /// <param name="g">the win forms graphics object to use</param> /// <param name="useGdiPlusTextRendering">Use GDI+ text rendering to measure/draw text</param> /// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param> public GraphicsAdapter(Graphics g, bool useGdiPlusTextRendering, bool releaseGraphics = false) : base(WinFormsAdapter.Instance, Utils.Convert(g.ClipBounds)) { ArgChecker.AssertArgNotNull(g, "g"); _g = g; _releaseGraphics = releaseGraphics; #if MONO _useGdiPlusTextRendering = true; #else _useGdiPlusTextRendering = useGdiPlusTextRendering; #endif } public override void PopClip() { ReleaseHdc(); _clipStack.Pop(); _g.SetClip(Utils.Convert(_clipStack.Peek()), CombineMode.Replace); } public override void PushClip(RRect rect) { ReleaseHdc(); _clipStack.Push(rect); _g.SetClip(Utils.Convert(rect), CombineMode.Replace); } public override void PushClipExclude(RRect rect) { ReleaseHdc(); _clipStack.Push(_clipStack.Peek()); _g.SetClip(Utils.Convert(rect), CombineMode.Exclude); } public override Object SetAntiAliasSmoothingMode() { ReleaseHdc(); var prevMode = _g.SmoothingMode; _g.SmoothingMode = SmoothingMode.AntiAlias; return prevMode; } public override void ReturnPreviousSmoothingMode(Object prevMode) { if (prevMode != null) { ReleaseHdc(); _g.SmoothingMode = (SmoothingMode)prevMode; } } public override RSize MeasureString(string str, RFont font) { if (_useGdiPlusTextRendering) { ReleaseHdc(); var fontAdapter = (FontAdapter)font; var realFont = fontAdapter.Font; _characterRanges[0] = new CharacterRange(0, str.Length); _stringFormat.SetMeasurableCharacterRanges(_characterRanges); var size = _g.MeasureCharacterRanges(str, realFont, RectangleF.Empty, _stringFormat)[0].GetBounds(_g).Size; if (font.Height < 0) { var height = realFont.Height; var descent = realFont.Size * realFont.FontFamily.GetCellDescent(realFont.Style) / realFont.FontFamily.GetEmHeight(realFont.Style); fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + .5f))); } return Utils.Convert(size); } else { #if !MONO SetFont(font); var size = new Size(); Win32Utils.GetTextExtentPoint32(_hdc, str, str.Length, ref size); if (font.Height < 0) { TextMetric lptm; Win32Utils.GetTextMetrics(_hdc, out lptm); ((FontAdapter)font).SetMetrics(size.Height, lptm.tmHeight - lptm.tmDescent + lptm.tmUnderlined + 1); } return Utils.Convert(size); #else throw new InvalidProgramException("Invalid Mono code"); #endif } } public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth) { charFit = 0; charFitWidth = 0; if (_useGdiPlusTextRendering) { ReleaseHdc(); var size = MeasureString(str, font); for (int i = 1; i <= str.Length; i++) { charFit = i - 1; RSize pSize = MeasureString(str.Substring(0, i), font); if (pSize.Height <= size.Height && pSize.Width < maxWidth) charFitWidth = pSize.Width; else break; } } else { #if !MONO SetFont(font); var size = new Size(); Win32Utils.GetTextExtentExPoint(_hdc, str, str.Length, (int)Math.Round(maxWidth), _charFit, _charFitWidth, ref size); charFit = _charFit[0]; charFitWidth = charFit > 0 ? _charFitWidth[charFit - 1] : 0; #endif } } public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl) { if (_useGdiPlusTextRendering) { ReleaseHdc(); SetRtlAlignGdiPlus(rtl); var brush = ((BrushAdapter)_adapter.GetSolidBrush(color)).Brush; _g.DrawString(str, ((FontAdapter)font).Font, brush, (int)(Math.Round(point.X) + (rtl ? size.Width : 0)), (int)Math.Round(point.Y), _stringFormat2); } else { #if !MONO var pointConv = Utils.ConvertRound(point); var colorConv = Utils.Convert(color); if (color.A == 255) { SetFont(font); SetTextColor(colorConv); SetRtlAlignGdi(rtl); Win32Utils.TextOut(_hdc, pointConv.X, pointConv.Y, str, str.Length); } else { InitHdc(); SetRtlAlignGdi(rtl); DrawTransparentText(_hdc, str, font, pointConv, Utils.ConvertRound(size), colorConv); } #endif } } public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation) { var brush = new TextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect)); brush.TranslateTransform((float)translateTransformLocation.X, (float)translateTransformLocation.Y); return new BrushAdapter(brush, true); } public override RGraphicsPath GetGraphicsPath() { return new GraphicsPathAdapter(); } public override void Dispose() { ReleaseHdc(); if (_releaseGraphics) _g.Dispose(); if (_useGdiPlusTextRendering && _setRtl) _stringFormat2.FormatFlags ^= StringFormatFlags.DirectionRightToLeft; } #region Delegate graphics methods public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2) { ReleaseHdc(); _g.DrawLine(((PenAdapter)pen).Pen, (float)x1, (float)y1, (float)x2, (float)y2); } public override void DrawRectangle(RPen pen, double x, double y, double width, double height) { ReleaseHdc(); _g.DrawRectangle(((PenAdapter)pen).Pen, (float)x, (float)y, (float)width, (float)height); } public override void DrawRectangle(RBrush brush, double x, double y, double width, double height) { ReleaseHdc(); _g.FillRectangle(((BrushAdapter)brush).Brush, (float)x, (float)y, (float)width, (float)height); } public override void DrawImage(RImage image, RRect destRect, RRect srcRect) { ReleaseHdc(); _g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), Utils.Convert(srcRect), GraphicsUnit.Pixel); } public override void DrawImage(RImage image, RRect destRect) { ReleaseHdc(); _g.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect)); } public override void DrawPath(RPen pen, RGraphicsPath path) { _g.DrawPath(((PenAdapter)pen).Pen, ((GraphicsPathAdapter)path).GraphicsPath); } public override void DrawPath(RBrush brush, RGraphicsPath path) { ReleaseHdc(); _g.FillPath(((BrushAdapter)brush).Brush, ((GraphicsPathAdapter)path).GraphicsPath); } public override void DrawPolygon(RBrush brush, RPoint[] points) { if (points != null && points.Length > 0) { ReleaseHdc(); _g.FillPolygon(((BrushAdapter)brush).Brush, Utils.Convert(points)); } } #endregion #region Private methods /// <summary> /// Release current HDC to be able to use <see cref="Graphics"/> methods. /// </summary> private void ReleaseHdc() { #if !MONO if (_hdc != IntPtr.Zero) { Win32Utils.SelectClipRgn(_hdc, IntPtr.Zero); _g.ReleaseHdc(_hdc); _hdc = IntPtr.Zero; } #endif } #if !MONO /// <summary> /// Init HDC for the current graphics object to be used to call GDI directly. /// </summary> private void InitHdc() { if (_hdc == IntPtr.Zero) { var clip = _g.Clip.GetHrgn(_g); _hdc = _g.GetHdc(); _setRtl = false; Win32Utils.SetBkMode(_hdc, 1); Win32Utils.SelectClipRgn(_hdc, clip); Win32Utils.DeleteObject(clip); } } /// <summary> /// Set a resource (e.g. a font) for the specified device context. /// WARNING: Calling Font.ToHfont() many times without releasing the font handle crashes the app. /// </summary> private void SetFont(RFont font) { InitHdc(); Win32Utils.SelectObject(_hdc, ((FontAdapter)font).HFont); } /// <summary> /// Set the text color of the device context. /// </summary> private void SetTextColor(Color color) { InitHdc(); int rgb = (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R; Win32Utils.SetTextColor(_hdc, rgb); } /// <summary> /// Change text align to Left-to-Right or Right-to-Left if required. /// </summary> private void SetRtlAlignGdi(bool rtl) { if (_setRtl) { if (!rtl) Win32Utils.SetTextAlign(_hdc, Win32Utils.TextAlignDefault); } else if (rtl) { Win32Utils.SetTextAlign(_hdc, Win32Utils.TextAlignRtl); } _setRtl = rtl; } /// <summary> /// Special draw logic to draw transparent text using GDI.<br/> /// 1. Create in-memory DC<br/> /// 2. Copy background to in-memory DC<br/> /// 3. Draw the text to in-memory DC<br/> /// 4. Copy the in-memory DC to the proper location with alpha blend<br/> /// </summary> private static void DrawTransparentText(IntPtr hdc, string str, RFont font, Point point, Size size, Color color) { IntPtr dib; var memoryHdc = Win32Utils.CreateMemoryHdc(hdc, size.Width, size.Height, out dib); try { // copy target background to memory HDC so when copied back it will have the proper background Win32Utils.BitBlt(memoryHdc, 0, 0, size.Width, size.Height, hdc, point.X, point.Y, Win32Utils.BitBltCopy); // Create and select font Win32Utils.SelectObject(memoryHdc, ((FontAdapter)font).HFont); Win32Utils.SetTextColor(memoryHdc, (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R); // Draw text to memory HDC Win32Utils.TextOut(memoryHdc, 0, 0, str, str.Length); // copy from memory HDC to normal HDC with alpha blend so achieve the transparent text Win32Utils.AlphaBlend(hdc, point.X, point.Y, size.Width, size.Height, memoryHdc, 0, 0, size.Width, size.Height, new BlendFunction(color.A)); } finally { Win32Utils.ReleaseMemoryHdc(memoryHdc, dib); } } #endif /// <summary> /// Change text align to Left-to-Right or Right-to-Left if required. /// </summary> private void SetRtlAlignGdiPlus(bool rtl) { if (_setRtl) { if (!rtl) _stringFormat2.FormatFlags ^= StringFormatFlags.DirectionRightToLeft; } else if (rtl) { _stringFormat2.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } _setRtl = rtl; } #endregion } }
// --------------------------------------------------------------------------- // <copyright file="SimplePropertyBag.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the SimplePropertyBag class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System.Collections.Generic; /// <summary> /// Represents a simple property bag. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> internal class SimplePropertyBag<TKey> : IEnumerable<KeyValuePair<TKey, object>> { private Dictionary<TKey, object> items = new Dictionary<TKey, object>(); private List<TKey> removedItems = new List<TKey>(); private List<TKey> addedItems = new List<TKey>(); private List<TKey> modifiedItems = new List<TKey>(); /// <summary> /// Add item to change list. /// </summary> /// <param name="key">The key.</param> /// <param name="changeList">The change list.</param> private static void InternalAddItemToChangeList(TKey key, List<TKey> changeList) { if (!changeList.Contains(key)) { changeList.Add(key); } } /// <summary> /// Triggers dispatch of the change event. /// </summary> private void Changed() { if (this.OnChange != null) { this.OnChange(); } } /// <summary> /// Remove item. /// </summary> /// <param name="key">The key.</param> private void InternalRemoveItem(TKey key) { object value; if (this.TryGetValue(key, out value)) { this.items.Remove(key); this.removedItems.Add(key); this.Changed(); } } /// <summary> /// Gets the added items. /// </summary> /// <value>The added items.</value> internal IEnumerable<TKey> AddedItems { get { return this.addedItems; } } /// <summary> /// Gets the removed items. /// </summary> /// <value>The removed items.</value> internal IEnumerable<TKey> RemovedItems { get { return this.removedItems; } } /// <summary> /// Gets the modified items. /// </summary> /// <value>The modified items.</value> internal IEnumerable<TKey> ModifiedItems { get { return this.modifiedItems; } } /// <summary> /// Initializes a new instance of the <see cref="SimplePropertyBag&lt;TKey&gt;"/> class. /// </summary> public SimplePropertyBag() { } /// <summary> /// Clears the change log. /// </summary> public void ClearChangeLog() { this.removedItems.Clear(); this.addedItems.Clear(); this.modifiedItems.Clear(); } /// <summary> /// Determines whether the specified key is in the property bag. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key exists; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { return this.items.ContainsKey(key); } /// <summary> /// Tries to get value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns>True if value exists in property bag.</returns> public bool TryGetValue(TKey key, out object value) { return this.items.TryGetValue(key, out value); } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <param name="key">Key.</param> /// <value>Value associated with key.</value> public object this[TKey key] { get { object value; if (this.TryGetValue(key, out value)) { return value; } else { return null; } } set { if (value == null) { this.InternalRemoveItem(key); } else { // If the item was to be deleted, the deletion becomes an update. if (this.removedItems.Remove(key)) { InternalAddItemToChangeList(key, this.modifiedItems); } else { // If the property value was not set, we have a newly set property. if (!this.ContainsKey(key)) { InternalAddItemToChangeList(key, this.addedItems); } else { // The last case is that we have a modified property. if (!this.modifiedItems.Contains(key)) { InternalAddItemToChangeList(key, this.modifiedItems); } } } this.items[key] = value; this.Changed(); } } } /// <summary> /// Occurs when Changed. /// </summary> public event PropertyBagChangedDelegate OnChange; #region IEnumerable<KeyValuePair<TKey,object>> Members /// <summary> /// Gets an enumerator that iterates through the elements of the collection. /// </summary> /// <returns>An IEnumerator for the collection.</returns> public IEnumerator<KeyValuePair<TKey, object>> GetEnumerator() { return this.items.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Gets an enumerator that iterates through the elements of the collection. /// </summary> /// <returns>An IEnumerator for the collection.</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.items.GetEnumerator(); } #endregion } }
using Lucene.Net.Util; using System; using System.Collections; using System.Collections.Generic; namespace Lucene.Net.Codecs { /* * 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. */ /// <summary> /// A utility class to write missing values for SORTED as if they were the empty string /// (to simulate pre-Lucene4.5 dv behavior for testing old codecs). /// </summary> public static class MissingOrdRemapper // LUCENENET specific: CA1052 Static holder types should be Static or NotInheritable { /// <summary> /// Insert an empty byte[] to the front of this enumerable.</summary> public static IEnumerable<BytesRef> InsertEmptyValue(IEnumerable<BytesRef> iterable) { return new IterableAnonymousClass(iterable); } private class IterableAnonymousClass : IEnumerable<BytesRef> { private readonly IEnumerable<BytesRef> iterable; public IterableAnonymousClass(IEnumerable<BytesRef> iterable) { this.iterable = iterable; } public IEnumerator<BytesRef> GetEnumerator() { return new IteratorAnonymousClass(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class IteratorAnonymousClass : IEnumerator<BytesRef> { public IteratorAnonymousClass(IterableAnonymousClass outerInstance) { seenEmpty = false; @in = outerInstance.iterable.GetEnumerator(); } private bool seenEmpty; private readonly IEnumerator<BytesRef> @in; private BytesRef current; public bool MoveNext() { if (!seenEmpty) { seenEmpty = true; current = new BytesRef(); return true; } if (@in.MoveNext()) { current = @in.Current; return true; } return false; } public BytesRef Current => current; object IEnumerator.Current => Current; public void Reset() => throw UnsupportedOperationException.Create(); public void Dispose() => @in.Dispose(); } } /// <summary> /// Remaps ord -1 to ord 0 on this enumerable. </summary> public static IEnumerable<long?> MapMissingToOrd0(IEnumerable<long?> iterable) { return new IterableAnonymousClass2(iterable); } private class IterableAnonymousClass2 : IEnumerable<long?> { private readonly IEnumerable<long?> iterable; public IterableAnonymousClass2(IEnumerable<long?> iterable) { this.iterable = iterable; } public IEnumerator<long?> GetEnumerator() { return new IteratorAnonymousClass2(this); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private class IteratorAnonymousClass2 : IEnumerator<long?> { public IteratorAnonymousClass2(IterableAnonymousClass2 outerInstance) { @in = outerInstance.iterable.GetEnumerator(); } private readonly IEnumerator<long?> @in; private long current; public bool MoveNext() { if ([email protected]()) { return false; } long n = @in.Current.Value; current = n == -1 ? 0 : n; return true; } public long? Current => current; object IEnumerator.Current => Current; public void Reset() => throw UnsupportedOperationException.Create(); public void Dispose() => @in.Dispose(); } } /// <summary> /// Remaps every ord+1 on this enumerable. </summary> public static IEnumerable<long?> MapAllOrds(IEnumerable<long?> iterable) { return new IterableAnonymousClass3(iterable); } private class IterableAnonymousClass3 : IEnumerable<long?> { private readonly IEnumerable<long?> iterable; public IterableAnonymousClass3(IEnumerable<long?> iterable) { this.iterable = iterable; } public IEnumerator<long?> GetEnumerator() { return new IteratorAnonymousClass3(this); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); private class IteratorAnonymousClass3 : IEnumerator<long?> { public IteratorAnonymousClass3(IterableAnonymousClass3 outerInstance) { @in = outerInstance.iterable.GetEnumerator(); } private readonly IEnumerator<long?> @in; private long current; public bool MoveNext() { if ([email protected]()) { return false; } long n = @in.Current.Value; current = n + 1; return true; } public long? Current => current; object IEnumerator.Current => Current; public void Reset() => throw UnsupportedOperationException.Create(); public void Dispose() => @in.Dispose(); } } } }
// Copyright (c) 2021 Alachisoft // // 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.Text; using Alachisoft.ContentOptimization.Diagnostics.Logging; using Alachisoft.NCache.ContentOptimization.Configurations; using System.IO; using Alachisoft.NCache.ContentOptimization.Util; using System.Diagnostics; namespace Alachisoft.NCache.ContentOptimization.Diagnostics { class FileBasedTraceProvider : ITraceProvider,IDisposable { private TextWriter writer; private object _sync_mutex = new object(); static FileBasedTraceProvider s_trace; static FileBasedTraceProvider() { s_trace = new FileBasedTraceProvider(); if (ConfigurationProvider.Settings.EnableTrace) { string filename = "contentoptimization." + Process.GetCurrentProcess().Id; s_trace.Initialize(filename, "ContentOptimizationLogs"); } } public static FileBasedTraceProvider Current { get { return s_trace; } } #region ITraceProvider Members public void WriteTrace(TraceSeverity level, string categoryName, string message) { if (ConfigurationProvider.Settings.EnableTrace) { WriteLogEntry(GetServerityCompatibleString(level), message); } } #endregion public void WriteTrace(TraceSeverity level,string message) { if (ConfigurationProvider.Settings.EnableTrace) { WriteLogEntry(GetServerityCompatibleString(level), message); } } private string GetServerityCompatibleString(TraceSeverity serverity) { string servertiyString = ""; switch (serverity) { case TraceSeverity.InformationEvent: case TraceSeverity.Medium: case TraceSeverity.Monitorable: case TraceSeverity.Verbose: servertiyString = "information"; break; case TraceSeverity.WarningEvent: servertiyString = "warning"; break; case TraceSeverity.CriticalEvent: servertiyString = "critical"; break; case TraceSeverity.Exception: case TraceSeverity.Unexpected: servertiyString = "error"; break; default: servertiyString = "unspecified"; break; } return servertiyString; } /// <summary> /// True if writer is not instantiated, false otherwise /// </summary> public bool IsWriterNull { get { if (writer == null) return true; else return false; } } /// <summary> /// Creates logs in installation folder /// </summary> /// <param name="fileName">name of file</param> /// <param name="directory">directory in which the logs are to be made</param> public void Initialize(string fileName, string directory) { Initialize(fileName, null, directory); } /// <summary> /// Creates logs in provided folder /// </summary> /// <param name="fileName">name of file</param> /// <param name="filepath">path where logs are to be created</param> /// <param name="directory">directory in which the logs are to be made</param> public void Initialize(string fileName, string filepath, string directory) { lock (_sync_mutex) { string filename = fileName + "." + Environment.MachineName.ToLower() + "." + DateTime.Now.ToString("dd-MM-yy HH-mm-ss") + @".logs.txt"; if (filepath == null || filepath == string.Empty) { if (!DirectoryUtil.SearchGlobalDirectory("log-files", false, out filepath)) { try { DirectoryUtil.SearchLocalDirectory("log-files", true, out filepath); } catch (Exception ex) { throw new Exception("Unable to initialize the log file", ex); } } } try { filepath = Path.Combine(filepath, directory); if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath); filepath = Path.Combine(filepath, filename); writer = TextWriter.Synchronized(new StreamWriter(filepath, false)); } catch (Exception) { throw; } } } /// <summary> /// Write to log file /// </summary> /// <param name="module">module</param> /// <param name="logText">text</param> public void WriteLogEntry(string severity, string logText) { if (writer != null) { int space2 = 40; string line = null; severity = "[" + severity + "]"; line = System.DateTime.Now.ToString("dd-MM-yy HH:mm:ss:ffff") + ": " + severity.PadRight(space2, ' ')+ logText; lock (_sync_mutex) { writer.WriteLine(line); writer.Flush(); } } } /// <summary> /// Close writer /// </summary> public void Close() { lock (_sync_mutex) { if (writer != null) { lock (writer) { writer.Close(); writer = null; } } } } #region IDisposable Members public void Dispose() { Close(); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedSecuritySettingsServiceClientSnippets { /// <summary>Snippet for CreateSecuritySettings</summary> public void CreateSecuritySettingsRequestObject() { // Snippet: CreateSecuritySettings(CreateSecuritySettingsRequest, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) CreateSecuritySettingsRequest request = new CreateSecuritySettingsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SecuritySettings = new SecuritySettings(), }; // Make the request SecuritySettings response = securitySettingsServiceClient.CreateSecuritySettings(request); // End snippet } /// <summary>Snippet for CreateSecuritySettingsAsync</summary> public async Task CreateSecuritySettingsRequestObjectAsync() { // Snippet: CreateSecuritySettingsAsync(CreateSecuritySettingsRequest, CallSettings) // Additional: CreateSecuritySettingsAsync(CreateSecuritySettingsRequest, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) CreateSecuritySettingsRequest request = new CreateSecuritySettingsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), SecuritySettings = new SecuritySettings(), }; // Make the request SecuritySettings response = await securitySettingsServiceClient.CreateSecuritySettingsAsync(request); // End snippet } /// <summary>Snippet for CreateSecuritySettings</summary> public void CreateSecuritySettings() { // Snippet: CreateSecuritySettings(string, SecuritySettings, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; SecuritySettings securitySettings = new SecuritySettings(); // Make the request SecuritySettings response = securitySettingsServiceClient.CreateSecuritySettings(parent, securitySettings); // End snippet } /// <summary>Snippet for CreateSecuritySettingsAsync</summary> public async Task CreateSecuritySettingsAsync() { // Snippet: CreateSecuritySettingsAsync(string, SecuritySettings, CallSettings) // Additional: CreateSecuritySettingsAsync(string, SecuritySettings, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; SecuritySettings securitySettings = new SecuritySettings(); // Make the request SecuritySettings response = await securitySettingsServiceClient.CreateSecuritySettingsAsync(parent, securitySettings); // End snippet } /// <summary>Snippet for CreateSecuritySettings</summary> public void CreateSecuritySettingsResourceNames() { // Snippet: CreateSecuritySettings(LocationName, SecuritySettings, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); SecuritySettings securitySettings = new SecuritySettings(); // Make the request SecuritySettings response = securitySettingsServiceClient.CreateSecuritySettings(parent, securitySettings); // End snippet } /// <summary>Snippet for CreateSecuritySettingsAsync</summary> public async Task CreateSecuritySettingsResourceNamesAsync() { // Snippet: CreateSecuritySettingsAsync(LocationName, SecuritySettings, CallSettings) // Additional: CreateSecuritySettingsAsync(LocationName, SecuritySettings, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); SecuritySettings securitySettings = new SecuritySettings(); // Make the request SecuritySettings response = await securitySettingsServiceClient.CreateSecuritySettingsAsync(parent, securitySettings); // End snippet } /// <summary>Snippet for GetSecuritySettings</summary> public void GetSecuritySettingsRequestObject() { // Snippet: GetSecuritySettings(GetSecuritySettingsRequest, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) GetSecuritySettingsRequest request = new GetSecuritySettingsRequest { SecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), }; // Make the request SecuritySettings response = securitySettingsServiceClient.GetSecuritySettings(request); // End snippet } /// <summary>Snippet for GetSecuritySettingsAsync</summary> public async Task GetSecuritySettingsRequestObjectAsync() { // Snippet: GetSecuritySettingsAsync(GetSecuritySettingsRequest, CallSettings) // Additional: GetSecuritySettingsAsync(GetSecuritySettingsRequest, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) GetSecuritySettingsRequest request = new GetSecuritySettingsRequest { SecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), }; // Make the request SecuritySettings response = await securitySettingsServiceClient.GetSecuritySettingsAsync(request); // End snippet } /// <summary>Snippet for GetSecuritySettings</summary> public void GetSecuritySettings() { // Snippet: GetSecuritySettings(string, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/securitySettings/[SECURITY_SETTINGS]"; // Make the request SecuritySettings response = securitySettingsServiceClient.GetSecuritySettings(name); // End snippet } /// <summary>Snippet for GetSecuritySettingsAsync</summary> public async Task GetSecuritySettingsAsync() { // Snippet: GetSecuritySettingsAsync(string, CallSettings) // Additional: GetSecuritySettingsAsync(string, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/securitySettings/[SECURITY_SETTINGS]"; // Make the request SecuritySettings response = await securitySettingsServiceClient.GetSecuritySettingsAsync(name); // End snippet } /// <summary>Snippet for GetSecuritySettings</summary> public void GetSecuritySettingsResourceNames() { // Snippet: GetSecuritySettings(SecuritySettingsName, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) SecuritySettingsName name = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"); // Make the request SecuritySettings response = securitySettingsServiceClient.GetSecuritySettings(name); // End snippet } /// <summary>Snippet for GetSecuritySettingsAsync</summary> public async Task GetSecuritySettingsResourceNamesAsync() { // Snippet: GetSecuritySettingsAsync(SecuritySettingsName, CallSettings) // Additional: GetSecuritySettingsAsync(SecuritySettingsName, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) SecuritySettingsName name = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"); // Make the request SecuritySettings response = await securitySettingsServiceClient.GetSecuritySettingsAsync(name); // End snippet } /// <summary>Snippet for UpdateSecuritySettings</summary> public void UpdateSecuritySettingsRequestObject() { // Snippet: UpdateSecuritySettings(UpdateSecuritySettingsRequest, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) UpdateSecuritySettingsRequest request = new UpdateSecuritySettingsRequest { SecuritySettings = new SecuritySettings(), UpdateMask = new FieldMask(), }; // Make the request SecuritySettings response = securitySettingsServiceClient.UpdateSecuritySettings(request); // End snippet } /// <summary>Snippet for UpdateSecuritySettingsAsync</summary> public async Task UpdateSecuritySettingsRequestObjectAsync() { // Snippet: UpdateSecuritySettingsAsync(UpdateSecuritySettingsRequest, CallSettings) // Additional: UpdateSecuritySettingsAsync(UpdateSecuritySettingsRequest, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) UpdateSecuritySettingsRequest request = new UpdateSecuritySettingsRequest { SecuritySettings = new SecuritySettings(), UpdateMask = new FieldMask(), }; // Make the request SecuritySettings response = await securitySettingsServiceClient.UpdateSecuritySettingsAsync(request); // End snippet } /// <summary>Snippet for UpdateSecuritySettings</summary> public void UpdateSecuritySettings() { // Snippet: UpdateSecuritySettings(SecuritySettings, FieldMask, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) SecuritySettings securitySettings = new SecuritySettings(); FieldMask updateMask = new FieldMask(); // Make the request SecuritySettings response = securitySettingsServiceClient.UpdateSecuritySettings(securitySettings, updateMask); // End snippet } /// <summary>Snippet for UpdateSecuritySettingsAsync</summary> public async Task UpdateSecuritySettingsAsync() { // Snippet: UpdateSecuritySettingsAsync(SecuritySettings, FieldMask, CallSettings) // Additional: UpdateSecuritySettingsAsync(SecuritySettings, FieldMask, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) SecuritySettings securitySettings = new SecuritySettings(); FieldMask updateMask = new FieldMask(); // Make the request SecuritySettings response = await securitySettingsServiceClient.UpdateSecuritySettingsAsync(securitySettings, updateMask); // End snippet } /// <summary>Snippet for ListSecuritySettings</summary> public void ListSecuritySettingsRequestObject() { // Snippet: ListSecuritySettings(ListSecuritySettingsRequest, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) ListSecuritySettingsRequest request = new ListSecuritySettingsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListSecuritySettingsResponse, SecuritySettings> response = securitySettingsServiceClient.ListSecuritySettings(request); // Iterate over all response items, lazily performing RPCs as required foreach (SecuritySettings item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSecuritySettingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SecuritySettings item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SecuritySettings> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SecuritySettings item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSecuritySettingsAsync</summary> public async Task ListSecuritySettingsRequestObjectAsync() { // Snippet: ListSecuritySettingsAsync(ListSecuritySettingsRequest, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) ListSecuritySettingsRequest request = new ListSecuritySettingsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedAsyncEnumerable<ListSecuritySettingsResponse, SecuritySettings> response = securitySettingsServiceClient.ListSecuritySettingsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((SecuritySettings item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSecuritySettingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SecuritySettings item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SecuritySettings> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SecuritySettings item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSecuritySettings</summary> public void ListSecuritySettings() { // Snippet: ListSecuritySettings(string, string, int?, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListSecuritySettingsResponse, SecuritySettings> response = securitySettingsServiceClient.ListSecuritySettings(parent); // Iterate over all response items, lazily performing RPCs as required foreach (SecuritySettings item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSecuritySettingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SecuritySettings item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SecuritySettings> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SecuritySettings item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSecuritySettingsAsync</summary> public async Task ListSecuritySettingsAsync() { // Snippet: ListSecuritySettingsAsync(string, string, int?, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListSecuritySettingsResponse, SecuritySettings> response = securitySettingsServiceClient.ListSecuritySettingsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((SecuritySettings item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSecuritySettingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SecuritySettings item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SecuritySettings> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SecuritySettings item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSecuritySettings</summary> public void ListSecuritySettingsResourceNames() { // Snippet: ListSecuritySettings(LocationName, string, int?, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListSecuritySettingsResponse, SecuritySettings> response = securitySettingsServiceClient.ListSecuritySettings(parent); // Iterate over all response items, lazily performing RPCs as required foreach (SecuritySettings item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSecuritySettingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SecuritySettings item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SecuritySettings> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SecuritySettings item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSecuritySettingsAsync</summary> public async Task ListSecuritySettingsResourceNamesAsync() { // Snippet: ListSecuritySettingsAsync(LocationName, string, int?, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListSecuritySettingsResponse, SecuritySettings> response = securitySettingsServiceClient.ListSecuritySettingsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((SecuritySettings item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSecuritySettingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SecuritySettings item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SecuritySettings> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SecuritySettings item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteSecuritySettings</summary> public void DeleteSecuritySettingsRequestObject() { // Snippet: DeleteSecuritySettings(DeleteSecuritySettingsRequest, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) DeleteSecuritySettingsRequest request = new DeleteSecuritySettingsRequest { SecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), }; // Make the request securitySettingsServiceClient.DeleteSecuritySettings(request); // End snippet } /// <summary>Snippet for DeleteSecuritySettingsAsync</summary> public async Task DeleteSecuritySettingsRequestObjectAsync() { // Snippet: DeleteSecuritySettingsAsync(DeleteSecuritySettingsRequest, CallSettings) // Additional: DeleteSecuritySettingsAsync(DeleteSecuritySettingsRequest, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) DeleteSecuritySettingsRequest request = new DeleteSecuritySettingsRequest { SecuritySettingsName = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), }; // Make the request await securitySettingsServiceClient.DeleteSecuritySettingsAsync(request); // End snippet } /// <summary>Snippet for DeleteSecuritySettings</summary> public void DeleteSecuritySettings() { // Snippet: DeleteSecuritySettings(string, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/securitySettings/[SECURITY_SETTINGS]"; // Make the request securitySettingsServiceClient.DeleteSecuritySettings(name); // End snippet } /// <summary>Snippet for DeleteSecuritySettingsAsync</summary> public async Task DeleteSecuritySettingsAsync() { // Snippet: DeleteSecuritySettingsAsync(string, CallSettings) // Additional: DeleteSecuritySettingsAsync(string, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/securitySettings/[SECURITY_SETTINGS]"; // Make the request await securitySettingsServiceClient.DeleteSecuritySettingsAsync(name); // End snippet } /// <summary>Snippet for DeleteSecuritySettings</summary> public void DeleteSecuritySettingsResourceNames() { // Snippet: DeleteSecuritySettings(SecuritySettingsName, CallSettings) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = SecuritySettingsServiceClient.Create(); // Initialize request argument(s) SecuritySettingsName name = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"); // Make the request securitySettingsServiceClient.DeleteSecuritySettings(name); // End snippet } /// <summary>Snippet for DeleteSecuritySettingsAsync</summary> public async Task DeleteSecuritySettingsResourceNamesAsync() { // Snippet: DeleteSecuritySettingsAsync(SecuritySettingsName, CallSettings) // Additional: DeleteSecuritySettingsAsync(SecuritySettingsName, CancellationToken) // Create client SecuritySettingsServiceClient securitySettingsServiceClient = await SecuritySettingsServiceClient.CreateAsync(); // Initialize request argument(s) SecuritySettingsName name = SecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"); // Make the request await securitySettingsServiceClient.DeleteSecuritySettingsAsync(name); // End snippet } } }
using Client.QuoteLineItemEditor.Model; using jQueryApi; using KnockoutApi; using Slick; using SparkleXrm; using SparkleXrm.GridEditor; using System; using System.Collections.Generic; using System.Html; using Xrm; using Xrm.Sdk; namespace Client.QuoteLineItemEditor.ViewModels { public class QuoteLineItemEditorViewModel : ViewModelBase { #region Fields public EntityDataViewModel Lines; public Observable<ObservableQuoteDetail> SelectedQuoteDetail = Knockout.Observable<ObservableQuoteDetail>(); private string _transactionCurrencyId; #endregion #region Constructors public QuoteLineItemEditorViewModel() { Lines = new EntityDataViewModel(10, typeof(QuoteDetail), false); Lines.OnSelectedRowsChanged += OnSelectedRowsChanged; Lines.FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' returntotalrecordcount='true' no-lock='true' distinct='false' count='{0}' paging-cookie='{1}' page='{2}'> <entity name='quotedetail'> <attribute name='productid' /> <attribute name='productdescription' /> <attribute name='priceperunit' /> <attribute name='quantity' /> <attribute name='extendedamount' /> <attribute name='quotedetailid' /> <attribute name='isproductoverridden' /> <attribute name='ispriceoverridden' /> <attribute name='manualdiscountamount' /> <attribute name='lineitemnumber' /> <attribute name='description' /> <attribute name='transactioncurrencyid' /> <attribute name='baseamount' /> <attribute name='requestdeliveryby' /> <attribute name='salesrepid' /> <attribute name='uomid' /> {3} <link-entity name='quote' from='quoteid' to='quoteid' alias='ac'> <filter type='and'> <condition attribute='quoteid' operator='eq' uiname='tes' uitype='quote' value='" + GetQuoteId() + @"' /> </filter> </link-entity> </entity> </fetch>"; Lines.SortBy(new SortCol("lineitemnumber", true)); Lines.NewItemFactory = NewLineFactory; QuoteDetailValidation.Register(Lines.ValidationBinder); SelectedQuoteDetail.SetValue(new ObservableQuoteDetail()); } #endregion #region Methods public bool IsEditForm() { if (ParentPage.Ui != null) return (ParentPage.Ui.GetFormType() == FormTypes.Update); else return true; // Debug } public string GetQuoteId() { string quoteId = "DB040ECD-5ED4-E211-9BE0-000C299FFE7D"; // Debug if (ParentPage.Ui != null) { string guid = ParentPage.Data.Entity.GetId(); if (guid != null) quoteId = guid.Replace("{", "").Replace("}", ""); this._transactionCurrencyId = ((Lookup[])ParentPage.GetAttribute("transactioncurrencyid").GetValue())[0].Id; } return quoteId; } public Entity NewLineFactory(object item) { QuoteDetail newLine = new QuoteDetail(); jQuery.Extend(newLine, item); newLine.LineItemNumber = Lines.GetPagingInfo().TotalRows + 1; newLine.QuoteId = new EntityReference(new Guid(GetQuoteId()), "quote", null); if (_transactionCurrencyId!=null) newLine.TransactionCurrencyId = new EntityReference(new Guid(_transactionCurrencyId), "transactioncurrency", ""); return newLine; } private void OnSelectedRowsChanged() { SelectedRange[] selectedContacts = Lines.GetSelectedRows(); if (selectedContacts.Length > 0) { ObservableQuoteDetail observableQuoteDetail = SelectedQuoteDetail.GetValue(); if (observableQuoteDetail.InnerQuoteDetail != null) observableQuoteDetail.InnerQuoteDetail.PropertyChanged -= quote_PropertyChanged; QuoteDetail selectedQuoteDetail = (QuoteDetail)Lines.GetItem(selectedContacts[0].FromRow.Value); if (selectedQuoteDetail != null) selectedQuoteDetail.PropertyChanged += quote_PropertyChanged; SelectedQuoteDetail.GetValue().SetValue(selectedQuoteDetail); } else SelectedQuoteDetail.GetValue().SetValue(null); } void quote_PropertyChanged(object sender, Xrm.ComponentModel.PropertyChangedEventArgs e) { Window.SetTimeout(delegate() { Lines.Refresh(); }, 0); } public void ProductSearchCommand(string term, Action<EntityCollection> callback) { // Get products from the search term string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='product'> <attribute name='productid' /> <attribute name='name' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='name' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } public void UoMSearchCommand(string term, Action<EntityCollection> callback) { string fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='uom'> <attribute name='uomid' /> <attribute name='name' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='name' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } public void SalesRepSearchCommand(string term, Action<EntityCollection> callback) { string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='systemuser'> <attribute name='fullname' /> <attribute name='businessunitid' /> <attribute name='title' /> <attribute name='address1_telephone1' /> <attribute name='systemuserid' /> <order attribute='fullname' descending='false' /> <filter type='and'> <condition attribute='fullname' operator='like' value='%{0}%' /> </filter> </entity> </fetch>"; fetchXml = string.Format(fetchXml, XmlHelper.Encode(term)); OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result) { EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity)); callback(fetchResult); }); } private void SaveNextRecord(List<QuoteDetail> dirtyCollection, List<string> errorMessages, Action callBack) { QuoteDetail itemToSave = dirtyCollection[0]; if (itemToSave.EntityState == EntityStates.Deleted) { OrganizationServiceProxy.BeginDelete("quotedetail",itemToSave.QuoteDetailId, delegate(object r) { try { OrganizationServiceProxy.EndDelete(r); itemToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with delete errorMessages.Add(ex.Message); } FinishSaveRecord(dirtyCollection, errorMessages, callBack, itemToSave); }); } else if (itemToSave.QuoteDetailId == null) { OrganizationServiceProxy.BeginCreate(itemToSave, delegate(object r) { try { Guid newID = OrganizationServiceProxy.EndCreate(r); itemToSave.QuoteDetailId = newID; itemToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with create errorMessages.Add(ex.Message); } FinishSaveRecord(dirtyCollection, errorMessages, callBack, itemToSave); }); } else { OrganizationServiceProxy.BeginUpdate(itemToSave, delegate(object r) { try { OrganizationServiceProxy.EndUpdate(r); itemToSave.EntityState = EntityStates.Unchanged; } catch (Exception ex) { // Something when wrong with update errorMessages.Add(ex.Message); } FinishSaveRecord(dirtyCollection, errorMessages, callBack, itemToSave); }); } } private void FinishSaveRecord(List<QuoteDetail> dirtyCollection, List<string> errorMessages, Action callBack, QuoteDetail itemToSave) { dirtyCollection.Remove(itemToSave); if (dirtyCollection.Count == 0) callBack(); else SaveNextRecord(dirtyCollection, errorMessages, callBack); } #endregion #region Commands private Action _saveCommand; public Action SaveCommand() { if (_saveCommand == null) { _saveCommand = delegate() { if (!CommitEdit()) return; List<QuoteDetail> dirtyCollection = new List<QuoteDetail>(); // Add new/changed items foreach (Entity item in this.Lines.Data) { if (item != null && item.EntityState != EntityStates.Unchanged) dirtyCollection.Add((QuoteDetail)item); } // Add deleted items if (this.Lines.DeleteData != null) { foreach (Entity item in this.Lines.DeleteData) { if (item.EntityState == EntityStates.Deleted) dirtyCollection.Add((QuoteDetail)item); } } int itemCount = dirtyCollection.Count; if (itemCount == 0) return; bool confirmed = Script.Confirm(String.Format("Are you sure that you want to save the {0} quote lines in the Grid?", itemCount)); if (!confirmed) return; IsBusy.SetValue(true); List<string> errorMessages = new List<string>(); SaveNextRecord(dirtyCollection, errorMessages, delegate() { if (errorMessages.Count > 0) { Script.Alert("One or more records failed to save.\nPlease contact your System Administrator.\n\n" + errorMessages.Join(",")); } if (Lines.DeleteData != null) Lines.DeleteData.Clear(); Lines.Refresh(); IsBusy.SetValue(false); }); }; } return _saveCommand; } private Action _deleteCommand; public Action DeleteCommand() { if (_deleteCommand == null) { _deleteCommand = delegate() { List<int> selectedRows = DataViewBase.RangesToRows(Lines.GetSelectedRows()); if (selectedRows.Count == 0) return; bool confirmed = Script.Confirm(String.Format("Are you sure that you want to delete the {0} quote lines in the Grid?", selectedRows.Count)); if (!confirmed) return; List<Entity> itemsToRemove = new List<Entity>(); foreach (int row in selectedRows) { itemsToRemove.Add((Entity)Lines.GetItem(row)); } foreach (Entity item in itemsToRemove) { item.EntityState = EntityStates.Deleted; Lines.RemoveItem(item); } Lines.Refresh(); }; } return _deleteCommand; } private Action _moveUpCommand; public Action MoveUpCommand() { if (_moveUpCommand == null) { _moveUpCommand = delegate() { // reindex all the items by moving the selected index up SelectedRange[] range = Lines.GetSelectedRows(); int fromRow = (int)range[0].FromRow; if (fromRow == 0) return; QuoteDetail line = (QuoteDetail)Lines.GetItem(fromRow); QuoteDetail lineBefore = (QuoteDetail)Lines.GetItem(fromRow - 1); // swap the indexes from the item before int? lineItemNumber = line.LineItemNumber; line.LineItemNumber = lineBefore.LineItemNumber; lineBefore.LineItemNumber = lineItemNumber; line.RaisePropertyChanged("LineItemNumber"); lineBefore.RaisePropertyChanged("LineItemNumber"); range[0].FromRow--; Lines.RaiseOnSelectedRowsChanged(range); Lines.SortBy(new SortCol("lineitemnumber", true)); Lines.Refresh(); }; } return _moveUpCommand; } private Action _moveDownCommand; public Action MoveDownCommand() { if (_moveDownCommand == null) { _moveDownCommand = delegate() { // reindex all the items by moving the selected index up SelectedRange[] range = Lines.GetSelectedRows(); int fromRow = (int)range[0].FromRow; if (fromRow == Lines.GetLength() - 1) return; QuoteDetail line = (QuoteDetail)Lines.GetItem(fromRow); QuoteDetail lineAfter = (QuoteDetail)Lines.GetItem(fromRow + 1); // swap the indexes from the item before int? lineItemNumber = line.LineItemNumber; line.RaisePropertyChanged("LineItemNumber"); lineAfter.RaisePropertyChanged("LineItemNumber"); line.LineItemNumber = lineAfter.LineItemNumber; lineAfter.LineItemNumber = lineItemNumber; range[0].FromRow++; Lines.RaiseOnSelectedRowsChanged(range); Lines.SortBy(new SortCol("lineitemnumber", true)); Lines.Refresh(); }; } return _moveDownCommand; } #endregion } }
using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using System; using System.Reflection; using System.Collections.Immutable; using System.Runtime.ExceptionServices; namespace RefactoringEssentials { #if NR6 public #endif static class SyntaxExtensions { /// <summary> /// Look inside a trivia list for a skipped token that contains the given position. /// </summary> private static readonly Func<SyntaxTriviaList, int, SyntaxToken> s_findSkippedTokenBackward = (l, p) => FindTokenHelper.FindSkippedTokenBackward(GetSkippedTokens(l), p); /// <summary> /// return only skipped tokens /// </summary> private static IEnumerable<SyntaxToken> GetSkippedTokens(SyntaxTriviaList list) { return list.Where(trivia => trivia.RawKind == (int)SyntaxKind.SkippedTokensTrivia) .SelectMany(t => ((SkippedTokensTriviaSyntax)t.GetStructure()).Tokens); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxNode root, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { var skippedTokenFinder = includeSkipped ? s_findSkippedTokenBackward : (Func<SyntaxTriviaList, int, SyntaxToken>)null; return FindTokenHelper.FindTokenOnLeftOfPosition<CompilationUnitSyntax>( root, position, skippedTokenFinder, includeSkipped, includeDirectives, includeDocumentationComments); } // public static bool IntersectsWith(this SyntaxToken token, int position) // { // return token.Span.IntersectsWith(position); // } // public static bool IsLeftSideOfDot(this ExpressionSyntax syntax) // { // return (bool)isLeftSideOfDotMethod.Invoke(null, new object[] { syntax }); // } // // public static bool IsRightSideOfDot(this ExpressionSyntax syntax) // { // return (bool)isRightSideOfDotMethod.Invoke(null, new object[] { syntax }); // } // public static INamedTypeSymbol GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) // { // return (INamedTypeSymbol)getEnclosingNamedTypeMethod.Invoke(null, new object[] { semanticModel, position, cancellationToken }); // } // [RoslynReflectionUsage(RoslynReflectionAllowedContext.CodeFixes)] static ImmutableArray<SyntaxToken> GetLocalDeclarationMap(this MemberDeclarationSyntax member, string localName) { try { object map = RoslynReflection.MemberDeclarationSyntaxExtensions.GetLocalDeclarationMapMethod.Invoke(null, new object[] { member }); return (ImmutableArray<SyntaxToken>)RoslynReflection.MemberDeclarationSyntaxExtensions_LocalDeclarationMap.LocalDeclarationMapIndexer.GetValue(map, new object[] { localName }); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return ImmutableArray<SyntaxToken>.Empty; } } [RoslynReflectionUsage(RoslynReflectionAllowedContext.CodeFixes)] static IEnumerable<T> GetAncestors<T>(this SyntaxToken token) where T : SyntaxNode { try { return (IEnumerable<T>)RoslynReflection.SyntaxTokenExtensions.GetAncestorsMethod.MakeGenericMethod(typeof(T)).Invoke(null, new object[] { token }); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return null; } } public static ExpressionSyntax SkipParens(this ExpressionSyntax expression) { if (expression == null) return null; while (expression != null && expression.IsKind(SyntaxKind.ParenthesizedExpression)) { expression = ((ParenthesizedExpressionSyntax)expression).Expression; } return expression; } public static SyntaxNode SkipArgument(this SyntaxNode expression) { if (expression is Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax) return ((Microsoft.CodeAnalysis.CSharp.Syntax.ArgumentSyntax)expression).Expression; if (expression is Microsoft.CodeAnalysis.VisualBasic.Syntax.ArgumentSyntax) return ((Microsoft.CodeAnalysis.VisualBasic.Syntax.ArgumentSyntax)expression).GetExpression(); return expression; } [RoslynReflectionUsage(RoslynReflectionAllowedContext.CodeFixes)] public static bool CanRemoveParentheses(this ParenthesizedExpressionSyntax node) { try { return (bool)RoslynReflection.ParenthesizedExpressionSyntaxExtensions.CanRemoveParenthesesMethod.Invoke(null, new object[] { node }); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return false; } } public static bool IsParentKind(this SyntaxNode node, SyntaxKind kind) { return node != null && node.Parent.IsKind(kind); } public static bool IsParentKind(this SyntaxToken node, SyntaxKind kind) { return node.Parent != null && node.Parent.IsKind(kind); } [RoslynReflectionUsage(RoslynReflectionAllowedContext.CodeFixes)] public static bool CanReplaceWithReducedName( this MemberAccessExpressionSyntax memberAccess, ExpressionSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!IsThisOrTypeOrNamespace(memberAccess, semanticModel)) { return false; } var speculationAnalyzer = new SpeculationAnalyzer(memberAccess, reducedName, semanticModel, cancellationToken); if (!speculationAnalyzer.SymbolsForOriginalAndReplacedNodesAreCompatible() || speculationAnalyzer.ReplacementChangesSemantics()) { return false; } if (WillConflictWithExistingLocal(memberAccess, reducedName)) { return false; } if (IsMemberAccessADynamicInvocation(memberAccess, semanticModel)) { return false; } if (memberAccess.AccessMethodWithDynamicArgumentInsideStructConstructor(semanticModel)) { return false; } if (memberAccess.Expression.Kind() == SyntaxKind.BaseExpression) { var enclosingNamedType = semanticModel.GetEnclosingNamedType(memberAccess.SpanStart, cancellationToken); var symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol; if (enclosingNamedType != null && !enclosingNamedType.IsSealed && symbol != null && symbol.IsOverridable()) { return false; } } var invalidTransformation1 = ParserWouldTreatExpressionAsCast(reducedName, memberAccess); return !invalidTransformation1; } public static INamedTypeSymbol GetEnclosingNamedType(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(position, cancellationToken); } public static TSymbol GetEnclosingSymbol<TSymbol>(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) where TSymbol : ISymbol { for (var symbol = semanticModel.GetEnclosingSymbol(position, cancellationToken); symbol != null; symbol = symbol.ContainingSymbol) { if (symbol is TSymbol) { return (TSymbol)symbol; } } return default(TSymbol); } internal static bool IsValidSymbolInfo(ISymbol symbol) { // name bound to only one symbol is valid return symbol != null && !symbol.IsErrorType(); } private static bool IsThisOrTypeOrNamespace(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel) { if (memberAccess.Expression.Kind() == SyntaxKind.ThisExpression) { var previousToken = memberAccess.Expression.GetFirstToken().GetPreviousToken(); var symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol; if (previousToken.Kind() == SyntaxKind.OpenParenToken && previousToken.IsParentKind(SyntaxKind.ParenthesizedExpression) && !previousToken.Parent.IsParentKind(SyntaxKind.ParenthesizedExpression) && ((ParenthesizedExpressionSyntax)previousToken.Parent).Expression.Kind() == SyntaxKind.SimpleMemberAccessExpression && symbol != null && symbol.Kind == SymbolKind.Method) { return false; } return true; } var expressionInfo = semanticModel.GetSymbolInfo(memberAccess.Expression); if (IsValidSymbolInfo(expressionInfo.Symbol)) { if (expressionInfo.Symbol is INamespaceOrTypeSymbol) { return true; } if (expressionInfo.Symbol.IsThisParameter()) { return true; } } return false; } private static bool WillConflictWithExistingLocal(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { if (simplifiedNode.Kind() == SyntaxKind.IdentifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var identifierName = (IdentifierNameSyntax)simplifiedNode; var enclosingDeclarationSpace = FindImmediatelyEnclosingLocalVariableDeclarationSpace(expression); var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (enclosingDeclarationSpace != null && enclosingMemberDeclaration != null) { var locals = enclosingMemberDeclaration.GetLocalDeclarationMap(identifierName.Identifier.ValueText); foreach (var token in locals) { if (GetAncestors<SyntaxNode>(token).Contains(enclosingDeclarationSpace)) { return true; } } } } return false; } private static SyntaxNode FindImmediatelyEnclosingLocalVariableDeclarationSpace(SyntaxNode syntax) { for (var declSpace = syntax; declSpace != null; declSpace = declSpace.Parent) { switch (declSpace.Kind()) { // These are declaration-space-defining syntaxes, by the spec: case SyntaxKind.MethodDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.Block: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SwitchStatement: case SyntaxKind.ForEachKeyword: case SyntaxKind.ForStatement: case SyntaxKind.UsingStatement: // SPEC VIOLATION: We also want to stop walking out if, say, we are in a field // initializer. Technically according to the wording of the spec it should be // legal to use a simple name inconsistently inside a field initializer because // it does not define a local variable declaration space. In practice of course // we want to check for that. (As the native compiler does as well.) case SyntaxKind.FieldDeclaration: return declSpace; } } return null; } private static bool ParserWouldTreatExpressionAsCast(ExpressionSyntax reducedNode, MemberAccessExpressionSyntax originalNode) { SyntaxNode parent = originalNode; while (parent != null) { if (parent.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)) { parent = parent.Parent; continue; } if (!parent.IsParentKind(SyntaxKind.ParenthesizedExpression)) { return false; } break; } var newExpression = parent.ReplaceNode((SyntaxNode)originalNode, reducedNode); // detect cast ambiguities according to C# spec #7.7.6 if (IsNameOrMemberAccessButNoExpression(newExpression)) { var nextToken = parent.Parent.GetLastToken().GetNextToken(); return nextToken.Kind() == SyntaxKind.OpenParenToken || nextToken.Kind() == SyntaxKind.TildeToken || nextToken.Kind() == SyntaxKind.ExclamationToken || (SyntaxFacts.IsKeywordKind(nextToken.Kind()) && !(nextToken.Kind() == SyntaxKind.AsKeyword || nextToken.Kind() == SyntaxKind.IsKeyword)); } return false; } private static bool IsMemberAccessADynamicInvocation(MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel) { var ancestorInvocation = memberAccess.FirstAncestorOrSelf<InvocationExpressionSyntax>(); if (ancestorInvocation != null && ancestorInvocation.SpanStart == memberAccess.SpanStart) { var typeInfo = semanticModel.GetTypeInfo(ancestorInvocation); if (typeInfo.Type != null && typeInfo.Type.Kind == SymbolKind.DynamicType) { return true; } } return false; } private static bool IsNameOrMemberAccessButNoExpression(SyntaxNode node) { if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)node; return memberAccess.Expression.IsKind(SyntaxKind.IdentifierName) || IsNameOrMemberAccessButNoExpression(memberAccess.Expression); } return node.IsKind(SyntaxKind.IdentifierName); } private static bool AccessMethodWithDynamicArgumentInsideStructConstructor(this MemberAccessExpressionSyntax memberAccess, SemanticModel semanticModel) { var constructor = memberAccess.Ancestors().OfType<ConstructorDeclarationSyntax>().SingleOrDefault(); if (constructor == null || constructor.Parent.Kind() != SyntaxKind.StructDeclaration) { return false; } return semanticModel.GetSymbolInfo(memberAccess.Name).CandidateReason == CandidateReason.LateBound; } [RoslynReflectionUsage(RoslynReflectionAllowedContext.CodeFixes)] public static bool CanReplaceWithReducedName(this NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken) { var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken); if (speculationAnalyzer.ReplacementChangesSemantics()) { return false; } return CanReplaceWithReducedNameInContext(name, reducedName, semanticModel, cancellationToken); } private static bool CanReplaceWithReducedNameInContext(this NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken) { // Special case. if this new minimal name parses out to a predefined type, then we // have to make sure that we're not in a using alias. That's the one place where the // language doesn't allow predefined types. You have to use the fully qualified name // instead. var invalidTransformation1 = IsNonNameSyntaxInUsingDirective(name, reducedName); var invalidTransformation2 = WillConflictWithExistingLocal(name, reducedName); var invalidTransformation3 = IsAmbiguousCast(name, reducedName); var invalidTransformation4 = IsNullableTypeInPointerExpression(name, reducedName); var isNotNullableReplacable = name.IsNotNullableReplacable(reducedName); if (invalidTransformation1 || invalidTransformation2 || invalidTransformation3 || invalidTransformation4 || isNotNullableReplacable) { return false; } return true; } private static bool IsNullableTypeInPointerExpression(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { // Note: nullable type syntax is not allowed in pointer type syntax if (simplifiedNode.Kind() == SyntaxKind.NullableType && simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax)) { return true; } return false; } private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { // Can't simplify a type name in a cast expression if it would then cause the cast to be // parsed differently. For example: (Foo::Bar)+1 is a cast. But if that simplifies to // (Bar)+1 then that's an arithmetic expression. if (expression.IsParentKind(SyntaxKind.CastExpression)) { var castExpression = (CastExpressionSyntax)expression.Parent; if (castExpression.Type == expression) { var newCastExpression = castExpression.ReplaceNode((SyntaxNode)castExpression.Type, simplifiedNode); var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString()); if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression)) { return true; } } } return false; } private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { return expression.IsParentKind(SyntaxKind.UsingDirective) && !(simplifiedNode is NameSyntax); } private static bool IsNotNullableReplacable(this NameSyntax name, TypeSyntax reducedName) { var isNotNullableReplacable = false; // var isLeftSideOfDot = name.IsLeftSideOfDot(); // var isRightSideOfDot = name.IsRightSideOfDot(); if (reducedName.Kind() == SyntaxKind.NullableType) { if (((NullableTypeSyntax)reducedName).ElementType.Kind() == SyntaxKind.OmittedTypeArgument) { isNotNullableReplacable = true; } else { isNotNullableReplacable = name.IsLeftSideOfDot() || name.IsRightSideOfDot(); } } return isNotNullableReplacable; } public static SyntaxTokenList GetModifiers(this MemberDeclarationSyntax member) { if (member == null) throw new ArgumentNullException("member"); var method = member as BaseMethodDeclarationSyntax; if (method != null) return method.Modifiers; var property = member as BasePropertyDeclarationSyntax; if (property != null) return property.Modifiers; var field = member as BaseFieldDeclarationSyntax; if (field != null) return field.Modifiers; return new SyntaxTokenList(); } public static ExplicitInterfaceSpecifierSyntax GetExplicitInterfaceSpecifierSyntax(this MemberDeclarationSyntax member) { if (member == null) throw new ArgumentNullException("member"); var method = member as MethodDeclarationSyntax; if (method != null) return method.ExplicitInterfaceSpecifier; var property = member as BasePropertyDeclarationSyntax; if (property != null) return property.ExplicitInterfaceSpecifier; var evt = member as EventDeclarationSyntax; if (evt != null) return evt.ExplicitInterfaceSpecifier; return null; } // public static bool IsKind(this SyntaxToken token, SyntaxKind kind) // { // return token.RawKind == (int)kind; // } // // public static bool IsKind(this SyntaxTrivia trivia, SyntaxKind kind) // { // return trivia.RawKind == (int)kind; // } // // public static bool IsKind(this SyntaxNode node, SyntaxKind kind) // { // return node?.RawKind == (int)kind; // } // // public static bool IsKind(this SyntaxNodeOrToken nodeOrToken, SyntaxKind kind) // { // return nodeOrToken.RawKind == (int)kind; // } // // public static SyntaxNode GetParent(this SyntaxNode node) // { // return node != null ? node.Parent : null; // } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent { using Microsoft.Azure.Management.Compute.Fluent.Models; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal partial class VirtualMachinesImpl { /// <summary> /// Gets available virtual machine sizes. /// </summary> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachineSizes Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Sizes { get { return this.Sizes(); } } /// <summary> /// Captures the virtual machine by copying virtual hard disks of the VM and returns template as a JSON /// string that can be used to create similar VMs. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="containerName">Destination container name to store the captured VHD.</param> /// <param name="vhdPrefix">The prefix for the VHD holding captured image.</param> /// <param name="overwriteVhd">Whether to overwrites destination VHD if it exists.</param> /// <return>The template as JSON string.</return> string Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Capture(string groupName, string name, string containerName, string vhdPrefix, bool overwriteVhd) { return this.Capture(groupName, name, containerName, vhdPrefix, overwriteVhd); } /// <summary> /// Captures the virtual machine by copying virtual hard disks of the VM asynchronously. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="containerName">Destination container name to store the captured VHD.</param> /// <param name="vhdPrefix">The prefix for the VHD holding captured image.</param> /// <param name="overwriteVhd">Whether to overwrites destination VHD if it exists.</param> /// <return>A representation of the deferred computation of this call.</return> async Task<string> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.CaptureAsync(string groupName, string name, string containerName, string vhdPrefix, bool overwriteVhd, CancellationToken cancellationToken) { return await this.CaptureAsync(groupName, name, containerName, vhdPrefix, overwriteVhd, cancellationToken); } /// <summary> /// Shuts down the virtual machine and releases the compute resources. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Deallocate(string groupName, string name) { this.Deallocate(groupName, name); } /// <summary> /// Shuts down the virtual machine and releases the compute resources asynchronously. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.DeallocateAsync(string groupName, string name, CancellationToken cancellationToken) { await this.DeallocateAsync(groupName, name, cancellationToken); } /// <summary> /// Begins a definition for a new resource. /// This is the beginning of the builder pattern used to create top level resources /// in Azure. The final method completing the definition and starting the actual resource creation /// process in Azure is Creatable.create(). /// Note that the Creatable.create() method is /// only available at the stage of the resource definition that has the minimum set of input /// parameters specified. If you do not see Creatable.create() among the available methods, it /// means you have not yet specified all the required input settings. Input settings generally begin /// with the word "with", for example: <code>.withNewResourceGroup()</code> and return the next stage /// of the resource definition, as an interface in the "fluent interface" style. /// </summary> /// <param name="name">The name of the new resource.</param> /// <return>The first stage of the new resource definition.</return> VirtualMachine.Definition.IBlank Microsoft.Azure.Management.ResourceManager.Fluent.Core.CollectionActions.ISupportsCreating<VirtualMachine.Definition.IBlank>.Define(string name) { return this.Define(name); } /// <summary> /// Generalizes the virtual machine. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Generalize(string groupName, string name) { this.Generalize(groupName, name); } /// <summary> /// Generalizes the virtual machine asynchronously. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.GeneralizeAsync(string groupName, string name, CancellationToken cancellationToken) { await this.GeneralizeAsync(groupName, name, cancellationToken); } /// <summary> /// Migrates the virtual machine with unmanaged disks to use managed disks. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.MigrateToManaged(string groupName, string name) { this.MigrateToManaged(groupName, name); } /// <summary> /// Converts (migrates) the virtual machine with un-managed disks to use managed disk asynchronously. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.MigrateToManagedAsync(string groupName, string name, CancellationToken cancellationToken) { await this.MigrateToManagedAsync(groupName, name, cancellationToken); } /// <summary> /// Powers off (stops) a virtual machine. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.PowerOff(string groupName, string name) { this.PowerOff(groupName, name); } /// <summary> /// Powers off (stops) the virtual machine asynchronously. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.PowerOffAsync(string groupName, string name, CancellationToken cancellationToken) { await this.PowerOffAsync(groupName, name, cancellationToken); } /// <summary> /// Redeploys a virtual machine. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Redeploy(string groupName, string name) { this.Redeploy(groupName, name); } /// <summary> /// Redeploys the virtual machine asynchronously. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.RedeployAsync(string groupName, string name, CancellationToken cancellationToken) { await this.RedeployAsync(groupName, name, cancellationToken); } /// <summary> /// Restarts a virtual machine. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Restart(string groupName, string name) { this.Restart(groupName, name); } /// <summary> /// Restarts the virtual machine asynchronously. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.RestartAsync(string groupName, string name, CancellationToken cancellationToken) { await this.RestartAsync(groupName, name, cancellationToken); } /// <summary> /// Run commands in a virtual machine. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="inputCommand">Command input.</param> /// <return>Result of execution.</return> Models.RunCommandResultInner Microsoft.Azure.Management.Compute.Fluent.IVirtualMachinesBeta.RunCommand(string groupName, string name, RunCommandInput inputCommand) { return this.RunCommand(groupName, name, inputCommand); } /// <summary> /// Run commands in a virtual machine asynchronously. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="inputCommand">Command input.</param> /// <return>Handle to the asynchronous execution.</return> async Task<Models.RunCommandResultInner> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachinesBeta.RunCommandAsync(string groupName, string name, RunCommandInput inputCommand, CancellationToken cancellationToken) { return await this.RunCommandAsync(groupName, name, inputCommand, cancellationToken); } /// <summary> /// Run shell script in a virtual machine. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="scriptLines">PowerShell script lines.</param> /// <param name="scriptParameters">Script parameters.</param> /// <return>Result of PowerShell script execution.</return> Models.RunCommandResultInner Microsoft.Azure.Management.Compute.Fluent.IVirtualMachinesBeta.RunPowerShellScript(string groupName, string name, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters) { return this.RunPowerShellScript(groupName, name, scriptLines, scriptParameters); } /// <summary> /// Run shell script in a virtual machine asynchronously. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="scriptLines">PowerShell script lines.</param> /// <param name="scriptParameters">Script parameters.</param> /// <return>Handle to the asynchronous execution.</return> async Task<Models.RunCommandResultInner> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachinesBeta.RunPowerShellScriptAsync(string groupName, string name, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken) { return await this.RunPowerShellScriptAsync(groupName, name, scriptLines, scriptParameters, cancellationToken); } /// <summary> /// Run shell script in a virtual machine. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="scriptLines">Shell script lines.</param> /// <param name="scriptParameters">Script parameters.</param> /// <return>Result of shell script execution.</return> Models.RunCommandResultInner Microsoft.Azure.Management.Compute.Fluent.IVirtualMachinesBeta.RunShellScript(string groupName, string name, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters) { return this.RunShellScript(groupName, name, scriptLines, scriptParameters); } /// <summary> /// Run shell script in a virtual machine asynchronously. /// </summary> /// <param name="groupName">The resource group name.</param> /// <param name="name">The virtual machine name.</param> /// <param name="scriptLines">Shell script lines.</param> /// <param name="scriptParameters">Script parameters.</param> /// <return>Handle to the asynchronous execution.</return> async Task<Models.RunCommandResultInner> Microsoft.Azure.Management.Compute.Fluent.IVirtualMachinesBeta.RunShellScriptAsync(string groupName, string name, IList<string> scriptLines, IList<Models.RunCommandInputParameter> scriptParameters, CancellationToken cancellationToken) { return await this.RunShellScriptAsync(groupName, name, scriptLines, scriptParameters, cancellationToken); } /// <summary> /// Starts a virtual machine. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> void Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.Start(string groupName, string name) { this.Start(groupName, name); } /// <summary> /// Starts the virtual machine asynchronously. /// </summary> /// <param name="groupName">The name of the resource group the virtual machine is in.</param> /// <param name="name">The virtual machine name.</param> /// <return>A representation of the deferred computation of this call.</return> async Task Microsoft.Azure.Management.Compute.Fluent.IVirtualMachines.StartAsync(string groupName, string name, CancellationToken cancellationToken) { await this.StartAsync(groupName, name, cancellationToken); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using StandardFilter = Lucene.Net.Analysis.Standard.StandardFilter; using StandardTokenizer = Lucene.Net.Analysis.Standard.StandardTokenizer; using PositionIncrementAttribute = Lucene.Net.Analysis.Tokenattributes.PositionIncrementAttribute; using TermAttribute = Lucene.Net.Analysis.Tokenattributes.TermAttribute; using AttributeSource = Lucene.Net.Util.AttributeSource; using English = Lucene.Net.Util.English; namespace Lucene.Net.Analysis { /// <summary> tests for the TestTeeSinkTokenFilter</summary> [TestFixture] public class TestTeeSinkTokenFilter:BaseTokenStreamTestCase { public class AnonymousClassSinkFilter:TeeSinkTokenFilter.SinkFilter { public override bool Accept(AttributeSource a) { TermAttribute termAtt = (TermAttribute) a.GetAttribute(typeof(TermAttribute)); return termAtt.Term().ToUpper().Equals("The".ToUpper()); } } public class AnonymousClassSinkFilter1:TeeSinkTokenFilter.SinkFilter { public override bool Accept(AttributeSource a) { TermAttribute termAtt = (TermAttribute) a.GetAttribute(typeof(TermAttribute)); return termAtt.Term().ToUpper().Equals("Dogs".ToUpper()); } } protected internal System.Text.StringBuilder buffer1; protected internal System.Text.StringBuilder buffer2; protected internal System.String[] tokens1; protected internal System.String[] tokens2; public TestTeeSinkTokenFilter(System.String s):base(s) { } public TestTeeSinkTokenFilter() { } [SetUp] public override void SetUp() { base.SetUp(); tokens1 = new System.String[]{"The", "quick", "Burgundy", "Fox", "jumped", "over", "the", "lazy", "Red", "Dogs"}; tokens2 = new System.String[]{"The", "Lazy", "Dogs", "should", "stay", "on", "the", "porch"}; buffer1 = new System.Text.StringBuilder(); for (int i = 0; i < tokens1.Length; i++) { buffer1.Append(tokens1[i]).Append(' '); } buffer2 = new System.Text.StringBuilder(); for (int i = 0; i < tokens2.Length; i++) { buffer2.Append(tokens2[i]).Append(' '); } } internal static readonly TeeSinkTokenFilter.SinkFilter theFilter; internal static readonly TeeSinkTokenFilter.SinkFilter dogFilter; [Test] public virtual void TestGeneral() { TeeSinkTokenFilter source = new TeeSinkTokenFilter(new WhitespaceTokenizer(new System.IO.StringReader(buffer1.ToString()))); TokenStream sink1 = source.NewSinkTokenStream(); TokenStream sink2 = source.NewSinkTokenStream(theFilter); source.AddAttribute(typeof(CheckClearAttributesAttribute)); sink1.AddAttribute(typeof(CheckClearAttributesAttribute)); sink2.AddAttribute(typeof(CheckClearAttributesAttribute)); AssertTokenStreamContents(source, tokens1); AssertTokenStreamContents(sink1, tokens1); } [Test] public virtual void TestMultipleSources() { TeeSinkTokenFilter tee1 = new TeeSinkTokenFilter(new WhitespaceTokenizer(new System.IO.StringReader(buffer1.ToString()))); TeeSinkTokenFilter.SinkTokenStream dogDetector = tee1.NewSinkTokenStream(dogFilter); TeeSinkTokenFilter.SinkTokenStream theDetector = tee1.NewSinkTokenStream(theFilter); TokenStream source1 = new CachingTokenFilter(tee1); tee1.AddAttribute(typeof(CheckClearAttributesAttribute)); dogDetector.AddAttribute(typeof(CheckClearAttributesAttribute)); theDetector.AddAttribute(typeof(CheckClearAttributesAttribute)); TeeSinkTokenFilter tee2 = new TeeSinkTokenFilter(new WhitespaceTokenizer(new System.IO.StringReader(buffer2.ToString()))); tee2.AddSinkTokenStream(dogDetector); tee2.AddSinkTokenStream(theDetector); TokenStream source2 = tee2; AssertTokenStreamContents(source1, tokens1); AssertTokenStreamContents(source2, tokens2); AssertTokenStreamContents(theDetector, new String[] { "The", "the", "The", "the" }); source1.Reset(); TokenStream lowerCasing = new LowerCaseFilter(source1); String[] lowerCaseTokens = new String[tokens1.Length]; for (int i = 0; i < tokens1.Length; i++) lowerCaseTokens[i] = tokens1[i].ToLower(); } /// <summary> Not an explicit test, just useful to print out some info on performance /// /// </summary> /// <throws> Exception </throws> public virtual void Performance() { int[] tokCount = new int[]{100, 500, 1000, 2000, 5000, 10000}; int[] modCounts = new int[]{1, 2, 5, 10, 20, 50, 100, 200, 500}; for (int k = 0; k < tokCount.Length; k++) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); System.Console.Out.WriteLine("-----Tokens: " + tokCount[k] + "-----"); for (int i = 0; i < tokCount[k]; i++) { buffer.Append(English.IntToEnglish(i).ToUpper()).Append(' '); } //make sure we produce the same tokens TeeSinkTokenFilter teeStream = new TeeSinkTokenFilter(new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString())))); TokenStream sink = teeStream.NewSinkTokenStream(new ModuloSinkFilter(this, 100)); teeStream.ConsumeAllTokens(); TokenStream stream = new ModuloTokenFilter(this, new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))), 100); TermAttribute tfTok = (TermAttribute) stream.AddAttribute(typeof(TermAttribute)); TermAttribute sinkTok = (TermAttribute) sink.AddAttribute(typeof(TermAttribute)); for (int i = 0; stream.IncrementToken(); i++) { Assert.IsTrue(sink.IncrementToken()); Assert.IsTrue(tfTok.Equals(sinkTok) == true, tfTok + " is not equal to " + sinkTok + " at token: " + i); } //simulate two fields, each being analyzed once, for 20 documents for (int j = 0; j < modCounts.Length; j++) { int tfPos = 0; long start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); for (int i = 0; i < 20; i++) { stream = new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))); PositionIncrementAttribute posIncrAtt = (PositionIncrementAttribute) stream.GetAttribute(typeof(PositionIncrementAttribute)); while (stream.IncrementToken()) { tfPos += posIncrAtt.GetPositionIncrement(); } stream = new ModuloTokenFilter(this, new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString()))), modCounts[j]); posIncrAtt = (PositionIncrementAttribute) stream.GetAttribute(typeof(PositionIncrementAttribute)); while (stream.IncrementToken()) { tfPos += posIncrAtt.GetPositionIncrement(); } } long finish = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); System.Console.Out.WriteLine("ModCount: " + modCounts[j] + " Two fields took " + (finish - start) + " ms"); int sinkPos = 0; //simulate one field with one sink start = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); for (int i = 0; i < 20; i++) { teeStream = new TeeSinkTokenFilter(new StandardFilter(new StandardTokenizer(new System.IO.StringReader(buffer.ToString())))); sink = teeStream.NewSinkTokenStream(new ModuloSinkFilter(this, modCounts[j])); PositionIncrementAttribute posIncrAtt = (PositionIncrementAttribute) teeStream.GetAttribute(typeof(PositionIncrementAttribute)); while (teeStream.IncrementToken()) { sinkPos += posIncrAtt.GetPositionIncrement(); } //System.out.println("Modulo--------"); posIncrAtt = (PositionIncrementAttribute) sink.GetAttribute(typeof(PositionIncrementAttribute)); while (sink.IncrementToken()) { sinkPos += posIncrAtt.GetPositionIncrement(); } } finish = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond); System.Console.Out.WriteLine("ModCount: " + modCounts[j] + " Tee fields took " + (finish - start) + " ms"); Assert.IsTrue(sinkPos == tfPos, sinkPos + " does not equal: " + tfPos); } System.Console.Out.WriteLine("- End Tokens: " + tokCount[k] + "-----"); } } internal class ModuloTokenFilter:TokenFilter { private void InitBlock(TestTeeSinkTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeSinkTokenFilter enclosingInstance; public TestTeeSinkTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal int modCount; internal ModuloTokenFilter(TestTeeSinkTokenFilter enclosingInstance, TokenStream input, int mc):base(input) { InitBlock(enclosingInstance); modCount = mc; } internal int count = 0; //return every 100 tokens public override bool IncrementToken() { bool hasNext; for (hasNext = input.IncrementToken(); hasNext && count % modCount != 0; hasNext = input.IncrementToken()) { count++; } count++; return hasNext; } } internal class ModuloSinkFilter:TeeSinkTokenFilter.SinkFilter { private void InitBlock(TestTeeSinkTokenFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestTeeSinkTokenFilter enclosingInstance; public TestTeeSinkTokenFilter Enclosing_Instance { get { return enclosingInstance; } } internal int count = 0; internal int modCount; internal ModuloSinkFilter(TestTeeSinkTokenFilter enclosingInstance, int mc) { InitBlock(enclosingInstance); modCount = mc; } public override bool Accept(AttributeSource a) { bool b = (a != null && count % modCount == 0); count++; return b; } } static TestTeeSinkTokenFilter() { theFilter = new AnonymousClassSinkFilter(); dogFilter = new AnonymousClassSinkFilter1(); } } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: ViewModel.tt using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; using Controls=WPAppStudio.Controls; using Entities=WPAppStudio.Entities; using EntitiesBase=WPAppStudio.Entities.Base; using IServices=WPAppStudio.Services.Interfaces; using IViewModels=WPAppStudio.ViewModel.Interfaces; using Localization=WPAppStudio.Localization; using Repositories=WPAppStudio.Repositories; using Services=WPAppStudio.Services; using ViewModelsBase=WPAppStudio.ViewModel.Base; using WPAppStudio; using WPAppStudio.Shared; namespace WPAppStudio.ViewModel { /// <summary> /// Implementation of Videos_DetailVideos ViewModel. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public partial class Videos_DetailVideosViewModel : ViewModelsBase.VMBase, IViewModels.IVideos_DetailVideosViewModel, ViewModelsBase.INavigable { private readonly Repositories.Videos_Videos _videos_Videos; private readonly IServices.IDialogService _dialogService; private readonly IServices.INavigationService _navigationService; private readonly IServices.ISpeechService _speechService; private readonly IServices.IShareService _shareService; private readonly IServices.ILiveTileService _liveTileService; /// <summary> /// Initializes a new instance of the <see cref="Videos_DetailVideosViewModel" /> class. /// </summary> /// <param name="videos_Videos">The Videos_ Videos.</param> /// <param name="dialogService">The Dialog Service.</param> /// <param name="navigationService">The Navigation Service.</param> /// <param name="speechService">The Speech Service.</param> /// <param name="shareService">The Share Service.</param> /// <param name="liveTileService">The Live Tile Service.</param> public Videos_DetailVideosViewModel(Repositories.Videos_Videos videos_Videos, IServices.IDialogService dialogService, IServices.INavigationService navigationService, IServices.ISpeechService speechService, IServices.IShareService shareService, IServices.ILiveTileService liveTileService) { _videos_Videos = videos_Videos; _dialogService = dialogService; _navigationService = navigationService; _speechService = speechService; _shareService = shareService; _liveTileService = liveTileService; } private EntitiesBase.YouTubeVideo _currentYouTubeVideo; /// <summary> /// CurrentYouTubeVideo property. /// </summary> public EntitiesBase.YouTubeVideo CurrentYouTubeVideo { get { return _currentYouTubeVideo; } set { SetProperty(ref _currentYouTubeVideo, value); } } private bool _hasNextpanoramaVideos_DetailVideos0; /// <summary> /// HasNextpanoramaVideos_DetailVideos0 property. /// </summary> public bool HasNextpanoramaVideos_DetailVideos0 { get { return _hasNextpanoramaVideos_DetailVideos0; } set { SetProperty(ref _hasNextpanoramaVideos_DetailVideos0, value); } } private bool _hasPreviouspanoramaVideos_DetailVideos0; /// <summary> /// HasPreviouspanoramaVideos_DetailVideos0 property. /// </summary> public bool HasPreviouspanoramaVideos_DetailVideos0 { get { return _hasPreviouspanoramaVideos_DetailVideos0; } set { SetProperty(ref _hasPreviouspanoramaVideos_DetailVideos0, value); } } /// <summary> /// Delegate method for the TextToSpeechVideos_DetailVideosStaticControlCommand command. /// </summary> public void TextToSpeechVideos_DetailVideosStaticControlCommandDelegate() { _speechService.TextToSpeech(CurrentYouTubeVideo.Title + " " + CurrentYouTubeVideo.Summary); } private ICommand _textToSpeechVideos_DetailVideosStaticControlCommand; /// <summary> /// Gets the TextToSpeechVideos_DetailVideosStaticControlCommand command. /// </summary> public ICommand TextToSpeechVideos_DetailVideosStaticControlCommand { get { return _textToSpeechVideos_DetailVideosStaticControlCommand = _textToSpeechVideos_DetailVideosStaticControlCommand ?? new ViewModelsBase.DelegateCommand(TextToSpeechVideos_DetailVideosStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the ShareVideos_DetailVideosStaticControlCommand command. /// </summary> public void ShareVideos_DetailVideosStaticControlCommandDelegate() { _shareService.Share(CurrentYouTubeVideo.Title, CurrentYouTubeVideo.Summary, CurrentYouTubeVideo.ExternalUrl, CurrentYouTubeVideo.VideoId); } private ICommand _shareVideos_DetailVideosStaticControlCommand; /// <summary> /// Gets the ShareVideos_DetailVideosStaticControlCommand command. /// </summary> public ICommand ShareVideos_DetailVideosStaticControlCommand { get { return _shareVideos_DetailVideosStaticControlCommand = _shareVideos_DetailVideosStaticControlCommand ?? new ViewModelsBase.DelegateCommand(ShareVideos_DetailVideosStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the PinToStartVideos_DetailVideosStaticControlCommand command. /// </summary> public void PinToStartVideos_DetailVideosStaticControlCommandDelegate() { _liveTileService.PinToStart(typeof(IViewModels.IVideos_DetailVideosViewModel), CreateTileInfoVideos_DetailVideosStaticControl()); } private ICommand _pinToStartVideos_DetailVideosStaticControlCommand; /// <summary> /// Gets the PinToStartVideos_DetailVideosStaticControlCommand command. /// </summary> public ICommand PinToStartVideos_DetailVideosStaticControlCommand { get { return _pinToStartVideos_DetailVideosStaticControlCommand = _pinToStartVideos_DetailVideosStaticControlCommand ?? new ViewModelsBase.DelegateCommand(PinToStartVideos_DetailVideosStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the GoToSourceVideos_DetailVideosStaticControlCommand command. /// </summary> public void GoToSourceVideos_DetailVideosStaticControlCommandDelegate() { _navigationService.NavigateTo(string.IsNullOrEmpty(CurrentYouTubeVideo.ExternalUrl) ? null : new Uri(CurrentYouTubeVideo.ExternalUrl)); } private ICommand _goToSourceVideos_DetailVideosStaticControlCommand; /// <summary> /// Gets the GoToSourceVideos_DetailVideosStaticControlCommand command. /// </summary> public ICommand GoToSourceVideos_DetailVideosStaticControlCommand { get { return _goToSourceVideos_DetailVideosStaticControlCommand = _goToSourceVideos_DetailVideosStaticControlCommand ?? new ViewModelsBase.DelegateCommand(GoToSourceVideos_DetailVideosStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the NextpanoramaVideos_DetailVideos0 command. /// </summary> public async void NextpanoramaVideos_DetailVideos0Delegate() { LoadingCurrentYouTubeVideo = true; var next = await _videos_Videos.Next(CurrentYouTubeVideo); if(next != null) CurrentYouTubeVideo = next; RefreshHasPrevNext(); } private bool _loadingCurrentYouTubeVideo; public bool LoadingCurrentYouTubeVideo { get { return _loadingCurrentYouTubeVideo; } set { SetProperty(ref _loadingCurrentYouTubeVideo, value); } } private ICommand _nextpanoramaVideos_DetailVideos0; /// <summary> /// Gets the NextpanoramaVideos_DetailVideos0 command. /// </summary> public ICommand NextpanoramaVideos_DetailVideos0 { get { return _nextpanoramaVideos_DetailVideos0 = _nextpanoramaVideos_DetailVideos0 ?? new ViewModelsBase.DelegateCommand(NextpanoramaVideos_DetailVideos0Delegate); } } /// <summary> /// Delegate method for the PreviouspanoramaVideos_DetailVideos0 command. /// </summary> public void PreviouspanoramaVideos_DetailVideos0Delegate() { var prev = _videos_Videos.Previous(CurrentYouTubeVideo); if(prev != null) CurrentYouTubeVideo = prev; RefreshHasPrevNext(); } private ICommand _previouspanoramaVideos_DetailVideos0; /// <summary> /// Gets the PreviouspanoramaVideos_DetailVideos0 command. /// </summary> public ICommand PreviouspanoramaVideos_DetailVideos0 { get { return _previouspanoramaVideos_DetailVideos0 = _previouspanoramaVideos_DetailVideos0 ?? new ViewModelsBase.DelegateCommand(PreviouspanoramaVideos_DetailVideos0Delegate); } } private async void RefreshHasPrevNext() { HasPreviouspanoramaVideos_DetailVideos0 = _videos_Videos.HasPrevious(CurrentYouTubeVideo); HasNextpanoramaVideos_DetailVideos0 = await _videos_Videos.HasNext(CurrentYouTubeVideo); LoadingCurrentYouTubeVideo = false; } public object NavigationContext { set { if (!(value is EntitiesBase.YouTubeVideo)) { return; } CurrentYouTubeVideo = value as EntitiesBase.YouTubeVideo; RefreshHasPrevNext(); } } /// <summary> /// Initializes a <see cref="Services.TileInfo" /> object for the Videos_DetailVideosStaticControl control. /// </summary> /// <returns>A <see cref="Services.TileInfo" /> object.</returns> public Services.TileInfo CreateTileInfoVideos_DetailVideosStaticControl() { var tileInfo = new Services.TileInfo { CurrentId = CurrentYouTubeVideo.VideoId, Title = CurrentYouTubeVideo.Title, BackTitle = CurrentYouTubeVideo.Title, BackContent = CurrentYouTubeVideo.Summary, Count = 0, BackgroundImagePath = CurrentYouTubeVideo.VideoImageUrl, BackBackgroundImagePath = CurrentYouTubeVideo.VideoImageUrl, LogoPath = "Logo-242457de-80da-42c9-9fbb-98b5451c622c.png" }; return tileInfo; } } }
#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.Globalization; using System.ComponentModel; #if HAVE_BIG_INTEGER using System.Numerics; #endif #if !HAVE_GUID_TRY_PARSE using System.Text; using System.Text.RegularExpressions; #endif using Newtonsoft.Json.Serialization; using System.Reflection; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #endif #if HAVE_ADO_NET using System.Data.SqlTypes; #endif namespace Newtonsoft.Json.Utilities { internal enum PrimitiveTypeCode { Empty = 0, Object = 1, Char = 2, CharNullable = 3, Boolean = 4, BooleanNullable = 5, SByte = 6, SByteNullable = 7, Int16 = 8, Int16Nullable = 9, UInt16 = 10, UInt16Nullable = 11, Int32 = 12, Int32Nullable = 13, Byte = 14, ByteNullable = 15, UInt32 = 16, UInt32Nullable = 17, Int64 = 18, Int64Nullable = 19, UInt64 = 20, UInt64Nullable = 21, Single = 22, SingleNullable = 23, Double = 24, DoubleNullable = 25, DateTime = 26, DateTimeNullable = 27, DateTimeOffset = 28, DateTimeOffsetNullable = 29, Decimal = 30, DecimalNullable = 31, Guid = 32, GuidNullable = 33, TimeSpan = 34, TimeSpanNullable = 35, BigInteger = 36, BigIntegerNullable = 37, Uri = 38, String = 39, Bytes = 40, DBNull = 41 } internal class TypeInformation { public Type Type { get; set; } public PrimitiveTypeCode TypeCode { get; set; } } internal enum ParseResult { None = 0, Success = 1, Overflow = 2, Invalid = 3 } internal static class ConvertUtils { private static readonly Dictionary<Type, PrimitiveTypeCode> TypeCodeMap = new Dictionary<Type, PrimitiveTypeCode> { { typeof(char), PrimitiveTypeCode.Char }, { typeof(char?), PrimitiveTypeCode.CharNullable }, { typeof(bool), PrimitiveTypeCode.Boolean }, { typeof(bool?), PrimitiveTypeCode.BooleanNullable }, { typeof(sbyte), PrimitiveTypeCode.SByte }, { typeof(sbyte?), PrimitiveTypeCode.SByteNullable }, { typeof(short), PrimitiveTypeCode.Int16 }, { typeof(short?), PrimitiveTypeCode.Int16Nullable }, { typeof(ushort), PrimitiveTypeCode.UInt16 }, { typeof(ushort?), PrimitiveTypeCode.UInt16Nullable }, { typeof(int), PrimitiveTypeCode.Int32 }, { typeof(int?), PrimitiveTypeCode.Int32Nullable }, { typeof(byte), PrimitiveTypeCode.Byte }, { typeof(byte?), PrimitiveTypeCode.ByteNullable }, { typeof(uint), PrimitiveTypeCode.UInt32 }, { typeof(uint?), PrimitiveTypeCode.UInt32Nullable }, { typeof(long), PrimitiveTypeCode.Int64 }, { typeof(long?), PrimitiveTypeCode.Int64Nullable }, { typeof(ulong), PrimitiveTypeCode.UInt64 }, { typeof(ulong?), PrimitiveTypeCode.UInt64Nullable }, { typeof(float), PrimitiveTypeCode.Single }, { typeof(float?), PrimitiveTypeCode.SingleNullable }, { typeof(double), PrimitiveTypeCode.Double }, { typeof(double?), PrimitiveTypeCode.DoubleNullable }, { typeof(DateTime), PrimitiveTypeCode.DateTime }, { typeof(DateTime?), PrimitiveTypeCode.DateTimeNullable }, #if HAVE_DATE_TIME_OFFSET { typeof(DateTimeOffset), PrimitiveTypeCode.DateTimeOffset }, { typeof(DateTimeOffset?), PrimitiveTypeCode.DateTimeOffsetNullable }, #endif { typeof(decimal), PrimitiveTypeCode.Decimal }, { typeof(decimal?), PrimitiveTypeCode.DecimalNullable }, { typeof(Guid), PrimitiveTypeCode.Guid }, { typeof(Guid?), PrimitiveTypeCode.GuidNullable }, { typeof(TimeSpan), PrimitiveTypeCode.TimeSpan }, { typeof(TimeSpan?), PrimitiveTypeCode.TimeSpanNullable }, #if HAVE_BIG_INTEGER { typeof(BigInteger), PrimitiveTypeCode.BigInteger }, { typeof(BigInteger?), PrimitiveTypeCode.BigIntegerNullable }, #endif { typeof(Uri), PrimitiveTypeCode.Uri }, { typeof(string), PrimitiveTypeCode.String }, { typeof(byte[]), PrimitiveTypeCode.Bytes }, #if HAVE_ADO_NET { typeof(DBNull), PrimitiveTypeCode.DBNull } #endif }; #if HAVE_ICONVERTIBLE private static readonly TypeInformation[] PrimitiveTypeCodes = { // need all of these. lookup against the index with TypeCode value new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Object }, new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.DBNull }, new TypeInformation { Type = typeof(bool), TypeCode = PrimitiveTypeCode.Boolean }, new TypeInformation { Type = typeof(char), TypeCode = PrimitiveTypeCode.Char }, new TypeInformation { Type = typeof(sbyte), TypeCode = PrimitiveTypeCode.SByte }, new TypeInformation { Type = typeof(byte), TypeCode = PrimitiveTypeCode.Byte }, new TypeInformation { Type = typeof(short), TypeCode = PrimitiveTypeCode.Int16 }, new TypeInformation { Type = typeof(ushort), TypeCode = PrimitiveTypeCode.UInt16 }, new TypeInformation { Type = typeof(int), TypeCode = PrimitiveTypeCode.Int32 }, new TypeInformation { Type = typeof(uint), TypeCode = PrimitiveTypeCode.UInt32 }, new TypeInformation { Type = typeof(long), TypeCode = PrimitiveTypeCode.Int64 }, new TypeInformation { Type = typeof(ulong), TypeCode = PrimitiveTypeCode.UInt64 }, new TypeInformation { Type = typeof(float), TypeCode = PrimitiveTypeCode.Single }, new TypeInformation { Type = typeof(double), TypeCode = PrimitiveTypeCode.Double }, new TypeInformation { Type = typeof(decimal), TypeCode = PrimitiveTypeCode.Decimal }, new TypeInformation { Type = typeof(DateTime), TypeCode = PrimitiveTypeCode.DateTime }, new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, // no 17 in TypeCode for some reason new TypeInformation { Type = typeof(string), TypeCode = PrimitiveTypeCode.String } }; #endif public static PrimitiveTypeCode GetTypeCode(Type t) { return GetTypeCode(t, out _); } public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum) { if (TypeCodeMap.TryGetValue(t, out PrimitiveTypeCode typeCode)) { isEnum = false; return typeCode; } if (t.IsEnum()) { isEnum = true; return GetTypeCode(Enum.GetUnderlyingType(t)); } // performance? if (ReflectionUtils.IsNullableType(t)) { Type nonNullable = Nullable.GetUnderlyingType(t); if (nonNullable.IsEnum()) { Type nullableUnderlyingType = typeof(Nullable<>).MakeGenericType(Enum.GetUnderlyingType(nonNullable)); isEnum = true; return GetTypeCode(nullableUnderlyingType); } } isEnum = false; return PrimitiveTypeCode.Object; } #if HAVE_ICONVERTIBLE public static TypeInformation GetTypeInformation(IConvertible convertable) { TypeInformation typeInformation = PrimitiveTypeCodes[(int)convertable.GetTypeCode()]; return typeInformation; } #endif public static bool IsConvertible(Type t) { #if HAVE_ICONVERTIBLE return typeof(IConvertible).IsAssignableFrom(t); #else return ( t == typeof(bool) || t == typeof(byte) || t == typeof(char) || t == typeof(DateTime) || t == typeof(decimal) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long) || t == typeof(sbyte) || t == typeof(float) || t == typeof(string) || t == typeof(ushort) || t == typeof(uint) || t == typeof(ulong) || t.IsEnum()); #endif } public static TimeSpan ParseTimeSpan(string input) { #if HAVE_TIME_SPAN_PARSE_WITH_CULTURE return TimeSpan.Parse(input, CultureInfo.InvariantCulture); #else return TimeSpan.Parse(input); #endif } private static readonly ThreadSafeStore<StructMultiKey<Type, Type>, Func<object, object>> CastConverters = new ThreadSafeStore<StructMultiKey<Type, Type>, Func<object, object>>(CreateCastConverter); private static Func<object, object> CreateCastConverter(StructMultiKey<Type, Type> t) { Type initialType = t.Value1; Type targetType = t.Value2; MethodInfo castMethodInfo = targetType.GetMethod("op_Implicit", new[] { initialType }) ?? targetType.GetMethod("op_Explicit", new[] { initialType }); if (castMethodInfo == null) { return null; } MethodCall<object, object> call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(castMethodInfo); return o => call(null, o); } #if HAVE_BIG_INTEGER internal static BigInteger ToBigInteger(object value) { if (value is BigInteger integer) { return integer; } if (value is string s) { return BigInteger.Parse(s, CultureInfo.InvariantCulture); } if (value is float f) { return new BigInteger(f); } if (value is double d) { return new BigInteger(d); } if (value is decimal @decimal) { return new BigInteger(@decimal); } if (value is int i) { return new BigInteger(i); } if (value is long l) { return new BigInteger(l); } if (value is uint u) { return new BigInteger(u); } if (value is ulong @ulong) { return new BigInteger(@ulong); } if (value is byte[] bytes) { return new BigInteger(bytes); } throw new InvalidCastException("Cannot convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } public static object FromBigInteger(BigInteger i, Type targetType) { if (targetType == typeof(decimal)) { return (decimal)i; } if (targetType == typeof(double)) { return (double)i; } if (targetType == typeof(float)) { return (float)i; } if (targetType == typeof(ulong)) { return (ulong)i; } if (targetType == typeof(bool)) { return i != 0; } try { return System.Convert.ChangeType((long)i, targetType, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new InvalidOperationException("Can not convert from BigInteger to {0}.".FormatWith(CultureInfo.InvariantCulture, targetType), ex); } } #endif #region TryConvert internal enum ConvertResult { Success = 0, CannotConvertNull = 1, NotInstantiableType = 2, NoValidConversion = 3 } public static object Convert(object initialValue, CultureInfo culture, Type targetType) { switch (TryConvertInternal(initialValue, culture, targetType, out object value)) { case ConvertResult.Success: return value; case ConvertResult.CannotConvertNull: throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); case ConvertResult.NotInstantiableType: throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(CultureInfo.InvariantCulture, targetType), nameof(targetType)); case ConvertResult.NoValidConversion: throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); default: throw new InvalidOperationException("Unexpected conversion result."); } } private static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object value) { try { if (TryConvertInternal(initialValue, culture, targetType, out value) == ConvertResult.Success) { return true; } value = null; return false; } catch { value = null; return false; } } private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value) { if (initialValue == null) { throw new ArgumentNullException(nameof(initialValue)); } if (ReflectionUtils.IsNullableType(targetType)) { targetType = Nullable.GetUnderlyingType(targetType); } Type initialType = initialValue.GetType(); if (targetType == initialType) { value = initialValue; return ConvertResult.Success; } // use Convert.ChangeType if both types are IConvertible if (IsConvertible(initialValue.GetType()) && IsConvertible(targetType)) { if (targetType.IsEnum()) { if (initialValue is string) { value = Enum.Parse(targetType, initialValue.ToString(), true); return ConvertResult.Success; } else if (IsInteger(initialValue)) { value = Enum.ToObject(targetType, initialValue); return ConvertResult.Success; } } value = System.Convert.ChangeType(initialValue, targetType, culture); return ConvertResult.Success; } #if HAVE_DATE_TIME_OFFSET if (initialValue is DateTime dt && targetType == typeof(DateTimeOffset)) { value = new DateTimeOffset(dt); return ConvertResult.Success; } #endif if (initialValue is byte[] bytes && targetType == typeof(Guid)) { value = new Guid(bytes); return ConvertResult.Success; } if (initialValue is Guid guid && targetType == typeof(byte[])) { value = guid.ToByteArray(); return ConvertResult.Success; } if (initialValue is string s) { if (targetType == typeof(Guid)) { value = new Guid(s); return ConvertResult.Success; } if (targetType == typeof(Uri)) { value = new Uri(s, UriKind.RelativeOrAbsolute); return ConvertResult.Success; } if (targetType == typeof(TimeSpan)) { value = ParseTimeSpan(s); return ConvertResult.Success; } if (targetType == typeof(byte[])) { value = System.Convert.FromBase64String(s); return ConvertResult.Success; } if (targetType == typeof(System.Version)) { if (VersionTryParse(s, out var result)) { value = result; return ConvertResult.Success; } value = null; return ConvertResult.NoValidConversion; } if (typeof(Type).IsAssignableFrom(targetType)) { value = Type.GetType(s, true); return ConvertResult.Success; } } #if HAVE_BIG_INTEGER if (targetType == typeof(BigInteger)) { value = ToBigInteger(initialValue); return ConvertResult.Success; } if (initialValue is BigInteger integer) { value = FromBigInteger(integer, targetType); return ConvertResult.Success; } #endif #if HAVE_TYPE_DESCRIPTOR // see if source or target types have a TypeConverter that converts between the two TypeConverter toConverter = TypeDescriptor.GetConverter(initialType); if (toConverter != null && toConverter.CanConvertTo(targetType)) { value = toConverter.ConvertTo(null, culture, initialValue, targetType); return ConvertResult.Success; } TypeConverter fromConverter = TypeDescriptor.GetConverter(targetType); if (fromConverter != null && fromConverter.CanConvertFrom(initialType)) { value = fromConverter.ConvertFrom(null, culture, initialValue); return ConvertResult.Success; } #endif #if HAVE_ADO_NET // handle DBNull if (initialValue == DBNull.Value) { if (ReflectionUtils.IsNullable(targetType)) { value = EnsureTypeAssignable(null, initialType, targetType); return ConvertResult.Success; } // cannot convert null to non-nullable value = null; return ConvertResult.CannotConvertNull; } #endif if (targetType.IsInterface() || targetType.IsGenericTypeDefinition() || targetType.IsAbstract()) { value = null; return ConvertResult.NotInstantiableType; } value = null; return ConvertResult.NoValidConversion; } #endregion #region ConvertOrCast /// <summary> /// Converts the value to the specified type. If the value is unable to be converted, the /// value is checked whether it assignable to the specified type. /// </summary> /// <param name="initialValue">The value to convert.</param> /// <param name="culture">The culture to use when converting.</param> /// <param name="targetType">The type to convert or cast the value to.</param> /// <returns> /// The converted type. If conversion was unsuccessful, the initial value /// is returned if assignable to the target type. /// </returns> public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType) { if (targetType == typeof(object)) { return initialValue; } if (initialValue == null && ReflectionUtils.IsNullable(targetType)) { return null; } if (TryConvert(initialValue, culture, targetType, out object convertedValue)) { return convertedValue; } return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); } #endregion private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) { Type valueType = value?.GetType(); if (value != null) { if (targetType.IsAssignableFrom(valueType)) { return value; } Func<object, object> castConverter = CastConverters.Get(new StructMultiKey<Type, Type>(valueType, targetType)); if (castConverter != null) { return castConverter(value); } } else { if (ReflectionUtils.IsNullable(targetType)) { return null; } } throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType?.ToString() ?? "{null}", targetType)); } public static bool VersionTryParse(string input, out System.Version result) { #if HAVE_VERSION_TRY_PARSE return System.Version.TryParse(input, out result); #else // improve failure performance with regex? try { result = new System.Version(input); return true; } catch { result = null; return false; } #endif } public static bool IsInteger(object value) { switch (GetTypeCode(value.GetType())) { case PrimitiveTypeCode.SByte: case PrimitiveTypeCode.Byte: case PrimitiveTypeCode.Int16: case PrimitiveTypeCode.UInt16: case PrimitiveTypeCode.Int32: case PrimitiveTypeCode.UInt32: case PrimitiveTypeCode.Int64: case PrimitiveTypeCode.UInt64: return true; default: return false; } } public static ParseResult Int32TryParse(char[] chars, int start, int length, out int value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int end = start + length; // Int32.MaxValue and MinValue are 10 chars // Or is 10 chars and start is greater than two // Need to improve this! if (length > 10 || (length == 10 && chars[start] - '0' > 2)) { // invalid result takes precedence over overflow for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } int newValue = (10 * value) - c; // overflow has caused the number to loop around if (newValue > value) { i++; // double check the rest of the string that there wasn't anything invalid // invalid result takes precedence over overflow result for (; i < end; i++) { c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } value = newValue; } // go from negative to positive to avoids overflow // negative can be slightly bigger than positive if (!isNegative) { // negative integer can be one bigger than positive if (value == int.MinValue) { return ParseResult.Overflow; } value = -value; } return ParseResult.Success; } public static ParseResult Int64TryParse(char[] chars, int start, int length, out long value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int end = start + length; // Int64.MaxValue and MinValue are 19 chars if (length > 19) { // invalid result takes precedence over overflow for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } for (int i = start; i < end; i++) { int c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } long newValue = (10 * value) - c; // overflow has caused the number to loop around if (newValue > value) { i++; // double check the rest of the string that there wasn't anything invalid // invalid result takes precedence over overflow result for (; i < end; i++) { c = chars[i] - '0'; if (c < 0 || c > 9) { return ParseResult.Invalid; } } return ParseResult.Overflow; } value = newValue; } // go from negative to positive to avoids overflow // negative can be slightly bigger than positive if (!isNegative) { // negative integer can be one bigger than positive if (value == long.MinValue) { return ParseResult.Overflow; } value = -value; } return ParseResult.Success; } #if HAS_CUSTOM_DOUBLE_PARSE private static class IEEE754 { /// <summary> /// Exponents for both powers of 10 and 0.1 /// </summary> private static readonly int[] MultExp64Power10 = new int[] { 4, 7, 10, 14, 17, 20, 24, 27, 30, 34, 37, 40, 44, 47, 50 }; /// <summary> /// Normalized powers of 10 /// </summary> private static readonly ulong[] MultVal64Power10 = new ulong[] { 0xa000000000000000, 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000, 0xc350000000000000, 0xf424000000000000, 0x9896800000000000, 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000, 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000, 0xb5e620f480000000, 0xe35fa931a0000000, }; /// <summary> /// Normalized powers of 0.1 /// </summary> private static readonly ulong[] MultVal64Power10Inv = new ulong[] { 0xcccccccccccccccd, 0xa3d70a3d70a3d70b, 0x83126e978d4fdf3c, 0xd1b71758e219652e, 0xa7c5ac471b478425, 0x8637bd05af6c69b7, 0xd6bf94d5e57a42be, 0xabcc77118461ceff, 0x89705f4136b4a599, 0xdbe6fecebdedd5c2, 0xafebff0bcb24ab02, 0x8cbccc096f5088cf, 0xe12e13424bb40e18, 0xb424dc35095cd813, 0x901d7cf73ab0acdc, }; /// <summary> /// Exponents for both powers of 10^16 and 0.1^16 /// </summary> private static readonly int[] MultExp64Power10By16 = new int[] { 54, 107, 160, 213, 266, 319, 373, 426, 479, 532, 585, 638, 691, 745, 798, 851, 904, 957, 1010, 1064, 1117, }; /// <summary> /// Normalized powers of 10^16 /// </summary> private static readonly ulong[] MultVal64Power10By16 = new ulong[] { 0x8e1bc9bf04000000, 0x9dc5ada82b70b59e, 0xaf298d050e4395d6, 0xc2781f49ffcfa6d4, 0xd7e77a8f87daf7fa, 0xefb3ab16c59b14a0, 0x850fadc09923329c, 0x93ba47c980e98cde, 0xa402b9c5a8d3a6e6, 0xb616a12b7fe617a8, 0xca28a291859bbf90, 0xe070f78d39275566, 0xf92e0c3537826140, 0x8a5296ffe33cc92c, 0x9991a6f3d6bf1762, 0xaa7eebfb9df9de8a, 0xbd49d14aa79dbc7e, 0xd226fc195c6a2f88, 0xe950df20247c83f8, 0x81842f29f2cce373, 0x8fcac257558ee4e2, }; /// <summary> /// Normalized powers of 0.1^16 /// </summary> private static readonly ulong[] MultVal64Power10By16Inv = new ulong[] { 0xe69594bec44de160, 0xcfb11ead453994c3, 0xbb127c53b17ec165, 0xa87fea27a539e9b3, 0x97c560ba6b0919b5, 0x88b402f7fd7553ab, 0xf64335bcf065d3a0, 0xddd0467c64bce4c4, 0xc7caba6e7c5382ed, 0xb3f4e093db73a0b7, 0xa21727db38cb0053, 0x91ff83775423cc29, 0x8380dea93da4bc82, 0xece53cec4a314f00, 0xd5605fcdcf32e217, 0xc0314325637a1978, 0xad1c8eab5ee43ba2, 0x9becce62836ac5b0, 0x8c71dcd9ba0b495c, 0xfd00b89747823938, 0xe3e27a444d8d991a, }; /// <summary> /// Packs <paramref name="val"/>*10^<paramref name="scale"/> as 64-bit floating point value according to IEEE 754 standard /// </summary> /// <param name="negative">Sign</param> /// <param name="val">Mantissa</param> /// <param name="scale">Exponent</param> /// <remarks> /// Adoption of native function NumberToDouble() from coreclr sources, /// see https://github.com/dotnet/coreclr/blob/master/src/classlibnative/bcltype/number.cpp#L451 /// </remarks> public static double PackDouble(bool negative, ulong val, int scale) { // handle zero value if (val == 0) { return negative ? -0.0 : 0.0; } // normalize the mantissa int exp = 64; if ((val & 0xFFFFFFFF00000000) == 0) { val <<= 32; exp -= 32; } if ((val & 0xFFFF000000000000) == 0) { val <<= 16; exp -= 16; } if ((val & 0xFF00000000000000) == 0) { val <<= 8; exp -= 8; } if ((val & 0xF000000000000000) == 0) { val <<= 4; exp -= 4; } if ((val & 0xC000000000000000) == 0) { val <<= 2; exp -= 2; } if ((val & 0x8000000000000000) == 0) { val <<= 1; exp -= 1; } if (scale < 0) { scale = -scale; // check scale bounds if (scale >= 22 * 16) { // underflow return negative ? -0.0 : 0.0; } // perform scaling int index = scale & 15; if (index != 0) { exp -= MultExp64Power10[index - 1] - 1; val = Mul64Lossy(val, MultVal64Power10Inv[index - 1], ref exp); } index = scale >> 4; if (index != 0) { exp -= MultExp64Power10By16[index - 1] - 1; val = Mul64Lossy(val, MultVal64Power10By16Inv[index - 1], ref exp); } } else { // check scale bounds if (scale >= 22 * 16) { // overflow return negative ? double.NegativeInfinity : double.PositiveInfinity; } // perform scaling int index = scale & 15; if (index != 0) { exp += MultExp64Power10[index - 1]; val = Mul64Lossy(val, MultVal64Power10[index - 1], ref exp); } index = scale >> 4; if (index != 0) { exp += MultExp64Power10By16[index - 1]; val = Mul64Lossy(val, MultVal64Power10By16[index - 1], ref exp); } } // round & scale down if ((val & (1 << 10)) != 0) { // IEEE round to even ulong tmp = val + ((1UL << 10) - 1 + ((val >> 11) & 1)); if (tmp < val) { // overflow tmp = (tmp >> 1) | 0x8000000000000000; exp++; } val = tmp; } // return the exponent to a biased state exp += 0x3FE; // handle overflow, underflow, "Epsilon - 1/2 Epsilon", denormalized, and the normal case if (exp <= 0) { if (exp == -52 && (val >= 0x8000000000000058)) { // round X where {Epsilon > X >= 2.470328229206232730000000E-324} up to Epsilon (instead of down to zero) val = 0x0000000000000001; } else if (exp <= -52) { // underflow val = 0; } else { // denormalized value val >>= (-exp + 12); } } else if (exp >= 0x7FF) { // overflow val = 0x7FF0000000000000; } else { // normal positive exponent case val = ((ulong)exp << 52) | ((val >> 11) & 0x000FFFFFFFFFFFFF); } // apply sign if (negative) { val |= 0x8000000000000000; } return BitConverter.Int64BitsToDouble((long)val); } private static ulong Mul64Lossy(ulong a, ulong b, ref int exp) { ulong a_hi = (a >> 32); uint a_lo = (uint)a; ulong b_hi = (b >> 32); uint b_lo = (uint)b; ulong result = a_hi * b_hi; // save some multiplications if lo-parts aren't big enough to produce carry // (hi-parts will be always big enough, since a and b are normalized) if ((b_lo & 0xFFFF0000) != 0) { result += (a_hi * b_lo) >> 32; } if ((a_lo & 0xFFFF0000) != 0) { result += (a_lo * b_hi) >> 32; } // normalize if ((result & 0x8000000000000000) == 0) { result <<= 1; exp--; } return result; } } public static ParseResult DoubleTryParse(char[] chars, int start, int length, out double value) { value = 0; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int i = start; int end = start + length; int numDecimalStart = end; int numDecimalEnd = end; int exponent = 0; ulong mantissa = 0UL; int mantissaDigits = 0; int exponentFromMantissa = 0; for (; i < end; i++) { char c = chars[i]; switch (c) { case '.': if (i == start) { return ParseResult.Invalid; } if (i + 1 == end) { return ParseResult.Invalid; } if (numDecimalStart != end) { // multiple decimal points return ParseResult.Invalid; } numDecimalStart = i + 1; break; case 'e': case 'E': if (i == start) { return ParseResult.Invalid; } if (i == numDecimalStart) { // E follows decimal point return ParseResult.Invalid; } i++; if (i == end) { return ParseResult.Invalid; } if (numDecimalStart < end) { numDecimalEnd = i - 1; } c = chars[i]; bool exponentNegative = false; switch (c) { case '-': exponentNegative = true; i++; break; case '+': i++; break; } // parse 3 digit for (; i < end; i++) { c = chars[i]; if (c < '0' || c > '9') { return ParseResult.Invalid; } int newExponent = (10 * exponent) + (c - '0'); // stops updating exponent when overflowing if (exponent < newExponent) { exponent = newExponent; } } if (exponentNegative) { exponent = -exponent; } break; default: if (c < '0' || c > '9') { return ParseResult.Invalid; } if (i == start && c == '0') { i++; if (i != end) { c = chars[i]; if (c == '.') { goto case '.'; } if (c == 'e' || c == 'E') { goto case 'E'; } return ParseResult.Invalid; } } if (mantissaDigits < 19) { mantissa = (10 * mantissa) + (ulong)(c - '0'); if (mantissa > 0) { ++mantissaDigits; } } else { ++exponentFromMantissa; } break; } } exponent += exponentFromMantissa; // correct the decimal point exponent -= (numDecimalEnd - numDecimalStart); value = IEEE754.PackDouble(isNegative, mantissa, exponent); return double.IsInfinity(value) ? ParseResult.Overflow : ParseResult.Success; } #endif public static ParseResult DecimalTryParse(char[] chars, int start, int length, out decimal value) { value = 0M; const decimal decimalMaxValueHi28 = 7922816251426433759354395033M; const ulong decimalMaxValueHi19 = 7922816251426433759UL; const ulong decimalMaxValueLo9 = 354395033UL; const char decimalMaxValueLo1 = '5'; if (length == 0) { return ParseResult.Invalid; } bool isNegative = (chars[start] == '-'); if (isNegative) { // text just a negative sign if (length == 1) { return ParseResult.Invalid; } start++; length--; } int i = start; int end = start + length; int numDecimalStart = end; int numDecimalEnd = end; int exponent = 0; ulong hi19 = 0UL; ulong lo10 = 0UL; int mantissaDigits = 0; int exponentFromMantissa = 0; char? digit29 = null; bool? storeOnly28Digits = null; for (; i < end; i++) { char c = chars[i]; switch (c) { case '.': if (i == start) { return ParseResult.Invalid; } if (i + 1 == end) { return ParseResult.Invalid; } if (numDecimalStart != end) { // multiple decimal points return ParseResult.Invalid; } numDecimalStart = i + 1; break; case 'e': case 'E': if (i == start) { return ParseResult.Invalid; } if (i == numDecimalStart) { // E follows decimal point return ParseResult.Invalid; } i++; if (i == end) { return ParseResult.Invalid; } if (numDecimalStart < end) { numDecimalEnd = i - 1; } c = chars[i]; bool exponentNegative = false; switch (c) { case '-': exponentNegative = true; i++; break; case '+': i++; break; } // parse 3 digit for (; i < end; i++) { c = chars[i]; if (c < '0' || c > '9') { return ParseResult.Invalid; } int newExponent = (10 * exponent) + (c - '0'); // stops updating exponent when overflowing if (exponent < newExponent) { exponent = newExponent; } } if (exponentNegative) { exponent = -exponent; } break; default: if (c < '0' || c > '9') { return ParseResult.Invalid; } if (i == start && c == '0') { i++; if (i != end) { c = chars[i]; if (c == '.') { goto case '.'; } if (c == 'e' || c == 'E') { goto case 'E'; } return ParseResult.Invalid; } } if (mantissaDigits < 29 && (mantissaDigits != 28 || !(storeOnly28Digits ?? (storeOnly28Digits = (hi19 > decimalMaxValueHi19 || (hi19 == decimalMaxValueHi19 && (lo10 > decimalMaxValueLo9 || (lo10 == decimalMaxValueLo9 && c > decimalMaxValueLo1))))).GetValueOrDefault()))) { if (mantissaDigits < 19) { hi19 = (hi19 * 10UL) + (ulong)(c - '0'); } else { lo10 = (lo10 * 10UL) + (ulong)(c - '0'); } ++mantissaDigits; } else { if (!digit29.HasValue) { digit29 = c; } ++exponentFromMantissa; } break; } } exponent += exponentFromMantissa; // correct the decimal point exponent -= (numDecimalEnd - numDecimalStart); if (mantissaDigits <= 19) { value = hi19; } else { value = (hi19 / new decimal(1, 0, 0, false, (byte)(mantissaDigits - 19))) + lo10; } if (exponent > 0) { mantissaDigits += exponent; if (mantissaDigits > 29) { return ParseResult.Overflow; } if (mantissaDigits == 29) { if (exponent > 1) { value /= new decimal(1, 0, 0, false, (byte)(exponent - 1)); if (value > decimalMaxValueHi28) { return ParseResult.Overflow; } } else if (value == decimalMaxValueHi28 && digit29 > decimalMaxValueLo1) { return ParseResult.Overflow; } value *= 10M; } else { value /= new decimal(1, 0, 0, false, (byte)exponent); } } else { if (digit29 >= '5' && exponent >= -28) { ++value; } if (exponent < 0) { if (mantissaDigits + exponent + 28 <= 0) { value = isNegative ? -0M : 0M; return ParseResult.Success; } if (exponent >= -28) { value *= new decimal(1, 0, 0, false, (byte)(-exponent)); } else { value /= 1e28M; value *= new decimal(1, 0, 0, false, (byte)(-exponent - 28)); } } } if (isNegative) { value = -value; } return ParseResult.Success; } public static bool TryConvertGuid(string s, out Guid g) { // GUID has to have format 00000000-0000-0000-0000-000000000000 #if !HAVE_GUID_TRY_PARSE if (s == null) { throw new ArgumentNullException("s"); } Regex format = new Regex("^[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}$"); Match match = format.Match(s); if (match.Success) { g = new Guid(s); return true; } g = Guid.Empty; return false; #else return Guid.TryParseExact(s, "D", out g); #endif } public static bool TryHexTextToInt(char[] text, int start, int end, out int value) { value = 0; for (int i = start; i < end; i++) { char ch = text[i]; int chValue; if (ch <= 57 && ch >= 48) { chValue = ch - 48; } else if (ch <= 70 && ch >= 65) { chValue = ch - 55; } else if (ch <= 102 && ch >= 97) { chValue = ch - 87; } else { value = 0; return false; } value += chValue << ((end - 1 - i) * 4); } return true; } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Security.Auth.Callback.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Security.Auth.Callback { /// <summary> /// <para>Needs to be implemented by classes that want to handle authentication Callbacks. A single method handle(Callback[]) must be provided that checks the type of the incoming <c> Callback </c> s and reacts accordingly. <c> CallbackHandler </c> s can be installed per application. It is also possible to configure a system-default <c> CallbackHandler </c> by setting the <c> auth.login.defaultCallbackHandler </c> property in the standard <c> security.properties </c> file. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/CallbackHandler /// </java-name> [Dot42.DexImport("javax/security/auth/callback/CallbackHandler", AccessFlags = 1537)] public partial interface ICallbackHandler /* scope: __dot42__ */ { /// <summary> /// <para>Handles the actual Callback. A <c> CallbackHandler </c> needs to implement this method. In the method, it is free to select which <c> Callback </c> s it actually wants to handle and in which way. For example, a console-based <c> CallbackHandler </c> might choose to sequentially ask the user for login and password, if it implements these <c> Callback </c> s, whereas a GUI-based one might open a single dialog window for both values. If a <c> CallbackHandler </c> is not able to handle a specific <c> Callback </c> , it needs to throw an UnsupportedCallbackException.</para><para></para> /// </summary> /// <java-name> /// handle /// </java-name> [Dot42.DexImport("handle", "([Ljavax/security/auth/callback/Callback;)V", AccessFlags = 1025)] void Handle(global::Javax.Security.Auth.Callback.ICallback[] callbacks) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Used in conjunction with a CallbackHandler to retrieve a password when needed. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/PasswordCallback /// </java-name> [Dot42.DexImport("javax/security/auth/callback/PasswordCallback", AccessFlags = 33)] public partial class PasswordCallback : global::Javax.Security.Auth.Callback.ICallback, global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new <c> PasswordCallback </c> instance.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Z)V", AccessFlags = 1)] public PasswordCallback(string prompt, bool echoOn) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the prompt that was specified when creating this <c> PasswordCallback </c></para><para></para> /// </summary> /// <returns> /// <para>the prompt </para> /// </returns> /// <java-name> /// getPrompt /// </java-name> [Dot42.DexImport("getPrompt", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPrompt() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Queries whether this <c> PasswordCallback </c> expects user input to be echoed, which is specified during the creation of the object.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if (and only if) user input should be echoed </para> /// </returns> /// <java-name> /// isEchoOn /// </java-name> [Dot42.DexImport("isEchoOn", "()Z", AccessFlags = 1)] public virtual bool IsEchoOn() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Sets the password. The CallbackHandler that performs the actual provisioning or input of the password needs to call this method to hand back the password to the security service that requested it.</para><para></para> /// </summary> /// <java-name> /// setPassword /// </java-name> [Dot42.DexImport("setPassword", "([C)V", AccessFlags = 1)] public virtual void SetPassword(char[] password) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the password. The security service that needs the password usually calls this method once the CallbackHandler has finished its work.</para><para></para> /// </summary> /// <returns> /// <para>the password. A copy of the internal password is created and returned, so subsequent changes to the internal password do not affect the result. </para> /// </returns> /// <java-name> /// getPassword /// </java-name> [Dot42.DexImport("getPassword", "()[C", AccessFlags = 1)] public virtual char[] GetPassword() /* MethodBuilder.Create */ { return default(char[]); } /// <summary> /// <para>Clears the password stored in this <c> PasswordCallback </c> . </para> /// </summary> /// <java-name> /// clearPassword /// </java-name> [Dot42.DexImport("clearPassword", "()V", AccessFlags = 1)] public virtual void ClearPassword() /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PasswordCallback() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the prompt that was specified when creating this <c> PasswordCallback </c></para><para></para> /// </summary> /// <returns> /// <para>the prompt </para> /// </returns> /// <java-name> /// getPrompt /// </java-name> public string Prompt { [Dot42.DexImport("getPrompt", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPrompt(); } } /// <summary> /// <para>Returns the password. The security service that needs the password usually calls this method once the CallbackHandler has finished its work.</para><para></para> /// </summary> /// <returns> /// <para>the password. A copy of the internal password is created and returned, so subsequent changes to the internal password do not affect the result. </para> /// </returns> /// <java-name> /// getPassword /// </java-name> public char[] Password { [Dot42.DexImport("getPassword", "()[C", AccessFlags = 1)] get{ return GetPassword(); } [Dot42.DexImport("setPassword", "([C)V", AccessFlags = 1)] set{ SetPassword(value); } } } /// <summary> /// <para>Defines an empty base interface for all <c> Callback </c> s used during authentication. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/Callback /// </java-name> [Dot42.DexImport("javax/security/auth/callback/Callback", AccessFlags = 1537)] public partial interface ICallback /* scope: __dot42__ */ { } /// <summary> /// <para>Thrown when a CallbackHandler does not support a particular Callback. </para> /// </summary> /// <java-name> /// javax/security/auth/callback/UnsupportedCallbackException /// </java-name> [Dot42.DexImport("javax/security/auth/callback/UnsupportedCallbackException", AccessFlags = 33)] public partial class UnsupportedCallbackException : global::System.Exception /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new exception instance and initializes it with just the unsupported <c> Callback </c> , but no error message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljavax/security/auth/callback/Callback;)V", AccessFlags = 1)] public UnsupportedCallbackException(global::Javax.Security.Auth.Callback.ICallback callback) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new exception instance and initializes it with both the unsupported <c> Callback </c> and an error message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljavax/security/auth/callback/Callback;Ljava/lang/String;)V", AccessFlags = 1)] public UnsupportedCallbackException(global::Javax.Security.Auth.Callback.ICallback callback, string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the unsupported <c> Callback </c> that triggered this exception.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Callback </c> </para> /// </returns> /// <java-name> /// getCallback /// </java-name> [Dot42.DexImport("getCallback", "()Ljavax/security/auth/callback/Callback;", AccessFlags = 1)] public virtual global::Javax.Security.Auth.Callback.ICallback GetCallback() /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Callback.ICallback); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal UnsupportedCallbackException() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the unsupported <c> Callback </c> that triggered this exception.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Callback </c> </para> /// </returns> /// <java-name> /// getCallback /// </java-name> public global::Javax.Security.Auth.Callback.ICallback Callback { [Dot42.DexImport("getCallback", "()Ljavax/security/auth/callback/Callback;", AccessFlags = 1)] get{ return GetCallback(); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace Microsoft.VisualStudio.Services.Agent { public sealed class HostTraceListener : TextWriterTraceListener { public bool DisableConsoleReporting { get; set; } private const string _logFileNamingPattern = "{0}_{1:yyyyMMdd-HHmmss}-utc.log"; private string _logFileDirectory; private string _logFilePrefix; private bool _enablePageLog = false; private bool _enableLogRetention = false; private int _currentPageSize; private int _pageSizeLimit; private int _retentionDays; private bool _diagErrorDetected = false; private string _logFilePath; public HostTraceListener(string logFileDirectory, string logFilePrefix, int pageSizeLimit, int retentionDays) : base() { ArgUtil.NotNullOrEmpty(logFileDirectory, nameof(logFileDirectory)); ArgUtil.NotNullOrEmpty(logFilePrefix, nameof(logFilePrefix)); _logFileDirectory = logFileDirectory; _logFilePrefix = logFilePrefix; Directory.CreateDirectory(_logFileDirectory); if (pageSizeLimit > 0) { _enablePageLog = true; _pageSizeLimit = pageSizeLimit * 1024 * 1024; _currentPageSize = 0; } if (retentionDays > 0) { _enableLogRetention = true; _retentionDays = retentionDays; } Writer = CreatePageLogWriter(); } public HostTraceListener(string logFile) : base() { ArgUtil.NotNullOrEmpty(logFile, nameof(logFile)); _logFilePath = logFile; Directory.CreateDirectory(Path.GetDirectoryName(_logFilePath)); Stream logStream = new FileStream(_logFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 4096); Writer = new StreamWriter(logStream); } // Copied and modified slightly from .Net Core source code. Modification was required to make it compile. // There must be some TraceFilter extension class that is missing in this source code. public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) { return; } WriteHeader(source, eventType, id); WriteLine(message); WriteFooter(eventCache); if (!_diagErrorDetected && !DisableConsoleReporting && eventType < TraceEventType.Warning) { Console.WriteLine(StringUtil.Loc("FoundErrorInTrace", eventType.ToString(), _logFilePath)); _diagErrorDetected = true; } } public override void WriteLine(string message) { base.WriteLine(message); if (_enablePageLog) { int messageSize = UTF8Encoding.UTF8.GetByteCount(message); _currentPageSize += messageSize; if (_currentPageSize > _pageSizeLimit) { Flush(); if (Writer != null) { Writer.Dispose(); Writer = null; } Writer = CreatePageLogWriter(); _currentPageSize = 0; } } Flush(); } public override void Write(string message) { base.Write(message); if (_enablePageLog) { int messageSize = UTF8Encoding.UTF8.GetByteCount(message); _currentPageSize += messageSize; } Flush(); } internal bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } // Altered from the original .Net Core implementation. private void WriteHeader(string source, TraceEventType eventType, int id) { string type = null; switch (eventType) { case TraceEventType.Critical: type = "CRIT"; break; case TraceEventType.Error: type = "ERR "; break; case TraceEventType.Warning: type = "WARN"; break; case TraceEventType.Information: type = "INFO"; break; case TraceEventType.Verbose: type = "VERB"; break; default: type = eventType.ToString(); break; } Write(StringUtil.Format("[{0:u} {1} {2}] ", DateTime.UtcNow, type, source)); } // Copied and modified slightly from .Net Core source code to make it compile. The original code // accesses a private indentLevel field. In this code it has been modified to use the getter/setter. private void WriteFooter(TraceEventCache eventCache) { if (eventCache == null) return; IndentLevel++; if (IsEnabled(TraceOptions.ProcessId)) WriteLine("ProcessId=" + eventCache.ProcessId); if (IsEnabled(TraceOptions.ThreadId)) WriteLine("ThreadId=" + eventCache.ThreadId); if (IsEnabled(TraceOptions.DateTime)) WriteLine("DateTime=" + eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); if (IsEnabled(TraceOptions.Timestamp)) WriteLine("Timestamp=" + eventCache.Timestamp); IndentLevel--; } private StreamWriter CreatePageLogWriter() { if (_enableLogRetention) { DirectoryInfo diags = new DirectoryInfo(_logFileDirectory); var logs = diags.GetFiles($"{_logFilePrefix}*.log"); foreach (var log in logs) { if (log.LastWriteTimeUtc.AddDays(_retentionDays) < DateTime.UtcNow) { try { log.Delete(); } catch (Exception) { // catch Exception and continue // we shouldn't block logging and fail the agent if the agent can't delete an older log file. } } } } string fileName = StringUtil.Format(_logFileNamingPattern, _logFilePrefix, DateTime.UtcNow); _logFilePath = Path.Combine(_logFileDirectory, fileName); Stream logStream; if (File.Exists(_logFilePath)) { logStream = new FileStream(_logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize: 4096); } else { logStream = new FileStream(_logFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 4096); } return new StreamWriter(logStream); } } }